Skip to content

Commit d0164dd

Browse files
authored
Merge pull request #63245 from whiteio/whiteio/add-customstringconvertible-conformance-to-std-string
Make std::string conform to CustomStringConvertible
2 parents f92e4eb + 7c126bc commit d0164dd

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

stdlib/public/Cxx/std/String.swift

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,12 @@ extension std.string: CustomDebugStringConvertible {
3535
}
3636
}
3737

38+
extension std.string: CustomStringConvertible {
39+
public var description: String {
40+
return String(cxxString: self)
41+
}
42+
}
43+
3844
extension String {
3945
/// Creates a String having the same content as the given C++ string.
4046
///

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

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,14 @@ StdStringOverlayTestSuite.test("std::string <=> Swift.String") {
3535
expectEqual(cxx6.size(), 7)
3636
let swift6 = String(cxxString: cxx6)
3737
expectEqual(swift6, "xyz\0abc")
38+
39+
var cxx7 = std.string()
40+
let bytes: [UInt8] = [0xE1, 0xC1, 0xAC]
41+
for byte in bytes {
42+
cxx7.push_back(CChar(bitPattern: byte))
43+
}
44+
let swift7 = String(cxxString: cxx7)
45+
expectEqual(swift7, "���")
3846
}
3947

4048
StdStringOverlayTestSuite.test("std::string as Swift.CustomDebugStringConvertible") {
@@ -71,4 +79,19 @@ StdStringOverlayTestSuite.test("std::string as Swift.Sequence") {
7179
expectEqual(97 + 98 + 99 + 49 + 50 + 51, sum)
7280
}
7381

82+
StdStringOverlayTestSuite.test("std::string as CustomStringConvertible") {
83+
let cxx1 = std.string()
84+
expectEqual(cxx1.description, "")
85+
86+
let cxx2 = std.string("something123")
87+
expectEqual(cxx2.description, "something123")
88+
89+
let bytes: [UInt8] = [0xE1, 0xC1, 0xAC]
90+
var cxx3 = std.string()
91+
for byte in bytes {
92+
cxx3.push_back(CChar(bitPattern: byte))
93+
}
94+
expectEqual(cxx3.description, "���")
95+
}
96+
7497
runAllTests()

0 commit comments

Comments
 (0)