Skip to content

Add callout for FoundationEssentials to handle non-UTF encodings (#5193) #5194

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion Sources/Foundation/NSString.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//


@_spi(SwiftCorelibsFoundation) @_exported import FoundationEssentials
@_implementationOnly import CoreFoundation
internal import Synchronization

Expand Down Expand Up @@ -1669,3 +1669,14 @@ extension String : CVarArg, _CVarArgObject {
}
}
#endif

// Upcall from swift-foundation for conversion of less frequently-used encodings
@_dynamicReplacement(for: _cfStringEncodingConvert(string:using:allowLossyConversion:))
private func _cfStringEncodingConvert_corelibs_foundation(string: String, using encoding: UInt, allowLossyConversion: Bool) -> Data? {
return (string as NSString).data(using: encoding, allowLossyConversion: allowLossyConversion)
}

@_dynamicReplacement(for: _cfMakeStringFromBytes(_:encoding:))
private func _cfMakeStringFromBytes_corelibs_foundation(_ bytes: UnsafeBufferPointer<UInt8>, encoding: UInt) -> String? {
return NSString(bytes: bytes.baseAddress!, length: bytes.count, encoding: encoding) as? String
}
12 changes: 12 additions & 0 deletions Tests/Foundation/TestNSString.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1725,4 +1725,16 @@ class TestNSString: LoopbackServerTest {
XCTAssertNotNil(str)
XCTAssertEqual(str?.isEmpty, true)
}

func test_windows1252Encoding() {
// Define an array of CP1252 encoded bytes representing "Hallo " followed by the Euro sign
let cp1252Bytes: [UInt8] = [72, 97, 108, 108, 111, 32, 0x80]
let cp1252Data = Data(cp1252Bytes)

let nativeString = String(data: cp1252Data, encoding: .windowsCP1252)
XCTAssertEqual(nativeString, "Hallo €")

let producedData = nativeString?.data(using: .windowsCP1252)
XCTAssertEqual(producedData, cp1252Data)
}
}