Skip to content

Commit cee927e

Browse files
authored
Fix lengthOfBytes(using:) semantics (#83334)
Fixes rdar://156675395
1 parent e96038d commit cee927e

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

stdlib/public/core/StringStorageBridge.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ extension _AbstractStringStorage {
106106
case _cocoaUTF8Encoding:
107107
return UInt(count)
108108
case _cocoaUTF16Encoding:
109-
return UInt(UTF16Length)
109+
return UInt(UTF16Length) * 2
110110
case _cocoaMacRomanEncoding:
111111
if unsafe isASCII || _allASCII(UnsafeBufferPointer(start: start, count: count)) {
112112
return UInt(count)

test/stdlib/StringBridge.swift

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,5 +174,25 @@ StringBridgeTests.test("Character from NSString") {
174174
expectNil((ns3 as String).utf8.withContiguousStorageIfAvailable(returnOne))
175175
}
176176

177+
StringBridgeTests.test("lengthOfBytes(using:)") {
178+
let ascii = "The quick brown fox jumps over the lazy dog"
179+
let utf8 = "The quick brown fox jümps over the lazy dog"
180+
let asciiAsASCIILen = ascii.lengthOfBytes(using: .ascii)
181+
let asciiAsUTF8Len = ascii.lengthOfBytes(using: .utf8)
182+
let asciiAsUTF16Len = ascii.lengthOfBytes(using: .utf16)
183+
let asciiAsMacRomanLen = ascii.lengthOfBytes(using: .macOSRoman)
184+
let utf8AsASCIILen = utf8.lengthOfBytes(using: .ascii)
185+
let utf8AsUTF8Len = utf8.lengthOfBytes(using: .utf8)
186+
let utf8AsUTF16Len = utf8.lengthOfBytes(using: .utf16)
187+
let utf8AsMacRomanLen = utf8.lengthOfBytes(using: .macOSRoman)
188+
expectEqual(asciiAsASCIILen, 43)
189+
expectEqual(asciiAsUTF8Len, 43)
190+
expectEqual(asciiAsUTF16Len, 86)
191+
expectEqual(asciiAsMacRomanLen, 43)
192+
expectEqual(utf8AsASCIILen, 0)
193+
expectEqual(utf8AsUTF8Len, 44)
194+
expectEqual(utf8AsUTF16Len, 86)
195+
expectEqual(utf8AsMacRomanLen, 43)
196+
}
177197

178198
runAllTests()

0 commit comments

Comments
 (0)