Skip to content

Commit dc8ff65

Browse files
committed
[cxx-interop] Do not crash for non-ASCII strings
This fixes a crash that happened when creating an instance of `std::string` from a `Swift.String` that contains non-ASCII characters. When converted to a UTF-8 array, such characters might be represented by numbers that fall out of `CChar`'s boundaries if they have a sign bit set to 1. This is normal and shouldn't trigger a crash or an assertion failure.
1 parent 6ad658c commit dc8ff65

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

stdlib/public/Cxx/std/String.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ extension std.string {
1414
public init(_ string: String) {
1515
self.init()
1616
for char in string.utf8 {
17-
self.push_back(value_type(char))
17+
self.push_back(value_type(bitPattern: char))
1818
}
1919
}
2020
}

test/Interop/Cxx/stdlib/overlay/std-string-overlay.swift

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,17 @@ StdStringOverlayTestSuite.test("std::string <=> Swift.String") {
1919

2020
let cxx3: std.string = "literal"
2121
expectEqual(cxx3.size(), 7)
22+
23+
// Non-ASCII characters are represented by more than one CChar.
24+
let cxx4: std.string = "тест"
25+
expectEqual(cxx4.size(), 8)
26+
let swift4 = String(cxxString: cxx4)
27+
expectEqual(swift4, "тест")
28+
29+
let cxx5: std.string = "emoji_🤖"
30+
expectEqual(cxx5.size(), 10)
31+
let swift5 = String(cxxString: cxx5)
32+
expectEqual(swift5, "emoji_🤖")
2233
}
2334

2435
extension std.string.const_iterator: UnsafeCxxInputIterator {

0 commit comments

Comments
 (0)