Skip to content

Commit af2ecd8

Browse files
authored
Add callout for FoundationEssentials to handle non-UTF encodings (#5193) (#5194)
1 parent 4c93e5b commit af2ecd8

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

Diff for: Sources/Foundation/NSString.swift

+12-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
88
//
99

10-
10+
@_spi(SwiftCorelibsFoundation) @_exported import FoundationEssentials
1111
@_implementationOnly import CoreFoundation
1212
internal import Synchronization
1313

@@ -1677,3 +1677,14 @@ extension String : CVarArg, _CVarArgObject {
16771677
}
16781678
}
16791679
#endif
1680+
1681+
// Upcall from swift-foundation for conversion of less frequently-used encodings
1682+
@_dynamicReplacement(for: _cfStringEncodingConvert(string:using:allowLossyConversion:))
1683+
private func _cfStringEncodingConvert_corelibs_foundation(string: String, using encoding: UInt, allowLossyConversion: Bool) -> Data? {
1684+
return (string as NSString).data(using: encoding, allowLossyConversion: allowLossyConversion)
1685+
}
1686+
1687+
@_dynamicReplacement(for: _cfMakeStringFromBytes(_:encoding:))
1688+
private func _cfMakeStringFromBytes_corelibs_foundation(_ bytes: UnsafeBufferPointer<UInt8>, encoding: UInt) -> String? {
1689+
return NSString(bytes: bytes.baseAddress!, length: bytes.count, encoding: encoding) as? String
1690+
}

Diff for: Tests/Foundation/TestNSString.swift

+12
Original file line numberDiff line numberDiff line change
@@ -1731,4 +1731,16 @@ class TestNSString: LoopbackServerTest {
17311731
XCTAssertNotNil(str)
17321732
XCTAssertEqual(str?.isEmpty, true)
17331733
}
1734+
1735+
func test_windows1252Encoding() {
1736+
// Define an array of CP1252 encoded bytes representing "Hallo " followed by the Euro sign
1737+
let cp1252Bytes: [UInt8] = [72, 97, 108, 108, 111, 32, 0x80]
1738+
let cp1252Data = Data(cp1252Bytes)
1739+
1740+
let nativeString = String(data: cp1252Data, encoding: .windowsCP1252)
1741+
XCTAssertEqual(nativeString, "Hallo €")
1742+
1743+
let producedData = nativeString?.data(using: .windowsCP1252)
1744+
XCTAssertEqual(producedData, cp1252Data)
1745+
}
17341746
}

0 commit comments

Comments
 (0)