Skip to content

Commit e7ba163

Browse files
committed
Make sure we don't compare too many bytes if a non-native string being compared to a native one has the same utf16 count but a different utf8 count
1 parent 4fabc61 commit e7ba163

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

stdlib/public/core/StringStorageBridge.swift

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,12 @@ extension _AbstractStringStorage {
166166
// CFString will only give us ASCII bytes here, but that's fine.
167167
// We already handled non-ASCII UTF8 strings earlier since they're Swift.
168168
if let asciiEqual = unsafe withCocoaASCIIPointer(other, work: { (ascii) -> Bool in
169-
return unsafe (start == ascii || (memcmp(start, ascii, self.count) == 0))
169+
// otherUTF16Length is the same as the byte count here IFF it's ASCII
170+
// self.count could still be utf8
171+
if count != otherUTF16Length {
172+
return 0
173+
}
174+
return unsafe (start == ascii || (memcmp(start, ascii, otherUTF16Length) == 0))
170175
}) {
171176
return asciiEqual ? 1 : 0
172177
}

test/stdlib/StringBridge.swift

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,4 +195,11 @@ StringBridgeTests.test("lengthOfBytes(using:)") {
195195
expectEqual(utf8AsMacRomanLen, 43)
196196
}
197197

198+
StringBridgeTests.test("Equal UTF16 lengths but unequal UTF8") {
199+
let utf8 = "aaaaaaaaaaaaaaü" //Native, UTF16 count: 31, UTF8 count: 58
200+
let nsascii = "2166002315@874404110.1042078977" as NSString //Non-native, UTF16 count: 31, UTF8 count: 31
201+
let nsutf8 = String(decoding: utf8.utf8, as: UTF8.self) as NSString //bridged native
202+
expectTrue(nsutf8.isEqual(nsascii))
203+
}
204+
198205
runAllTests()

0 commit comments

Comments
 (0)