Skip to content

Commit cbaef38

Browse files
committed
[c++-interop] Improve performance of creating a C++ std::string from a contiguous UTF-8 Swift.String
1 parent 328e8af commit cbaef38

File tree

1 file changed

+6
-15
lines changed

1 file changed

+6
-15
lines changed

stdlib/public/Cxx/std/String.swift

Lines changed: 6 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -20,25 +20,16 @@ extension std.string {
2020
/// - Complexity: O(*n*), where *n* is the number of UTF-8 code units in the
2121
/// Swift string.
2222
public init(_ string: String) {
23-
self.init()
24-
let utf8 = string.utf8
25-
self.reserve(utf8.count)
26-
for char in utf8 {
27-
self.push_back(value_type(bitPattern: char))
23+
self = string.withCString(encodedAs: UTF8.self) { buffer in
24+
std.string(buffer, string.utf8.count, .init())
2825
}
2926
}
3027

3128
public init(_ string: UnsafePointer<CChar>?) {
32-
self.init()
33-
34-
guard let str = string else {
35-
return
36-
}
37-
38-
let len = UTF8._nullCodeUnitOffset(in: str)
39-
for i in 0..<len {
40-
let char = UInt8(str[i])
41-
self.push_back(value_type(bitPattern: char))
29+
if let str = string {
30+
self.init(str, UTF8._nullCodeUnitOffset(in: str), .init())
31+
} else {
32+
self.init()
4233
}
4334
}
4435
}

0 commit comments

Comments
 (0)