Skip to content

Commit f593d92

Browse files
committed
Add callout for FoundationEssentials to handle non-UTF encodings (swiftlang#5193)
1 parent 4a9694d commit f593d92

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

Sources/Foundation/NSString.swift

Lines changed: 12 additions & 1 deletion
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

@@ -1669,3 +1669,14 @@ extension String : CVarArg, _CVarArgObject {
16691669
}
16701670
}
16711671
#endif
1672+
1673+
// Upcall from swift-foundation for conversion of less frequently-used encodings
1674+
@_dynamicReplacement(for: _cfStringEncodingConvert(string:using:allowLossyConversion:))
1675+
private func _cfStringEncodingConvert_corelibs_foundation(string: String, using encoding: UInt, allowLossyConversion: Bool) -> Data? {
1676+
return (string as NSString).data(using: encoding, allowLossyConversion: allowLossyConversion)
1677+
}
1678+
1679+
@_dynamicReplacement(for: _cfMakeStringFromBytes(_:encoding:))
1680+
private func _cfMakeStringFromBytes_corelibs_foundation(_ bytes: UnsafeBufferPointer<UInt8>, encoding: UInt) -> String? {
1681+
return NSString(bytes: bytes.baseAddress!, length: bytes.count, encoding: encoding) as? String
1682+
}

Tests/Foundation/TestNSString.swift

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1725,4 +1725,16 @@ class TestNSString: LoopbackServerTest {
17251725
XCTAssertNotNil(str)
17261726
XCTAssertEqual(str?.isEmpty, true)
17271727
}
1728+
1729+
func test_windows1252Encoding() {
1730+
// Define an array of CP1252 encoded bytes representing "Hallo " followed by the Euro sign
1731+
let cp1252Bytes: [UInt8] = [72, 97, 108, 108, 111, 32, 0x80]
1732+
let cp1252Data = Data(cp1252Bytes)
1733+
1734+
let nativeString = String(data: cp1252Data, encoding: .windowsCP1252)
1735+
XCTAssertEqual(nativeString, "Hallo €")
1736+
1737+
let producedData = nativeString?.data(using: .windowsCP1252)
1738+
XCTAssertEqual(producedData, cp1252Data)
1739+
}
17281740
}

0 commit comments

Comments
 (0)