1010//
1111//===----------------------------------------------------------------------===//
1212
13+ // MARK: Initializing C++ string from a Swift String
14+
1315extension std . string {
1416 /// Creates a C++ string having the same content as the given Swift string.
1517 ///
@@ -23,12 +25,34 @@ extension std.string {
2325 }
2426}
2527
28+ extension std . u16string {
29+ /// Creates a C++ UTF-16 string having the same content as the given Swift
30+ /// string.
31+ ///
32+ /// - Complexity: O(*n*), where *n* is the number of UTF-16 code units in the
33+ /// Swift string.
34+ public init ( _ string: String ) {
35+ self . init ( )
36+ for char in string. utf16 {
37+ self . push_back ( char)
38+ }
39+ }
40+ }
41+
42+ // MARK: Initializing C++ string from a Swift String literal
43+
2644extension std . string : ExpressibleByStringLiteral {
2745 public init ( stringLiteral value: String ) {
2846 self . init ( value)
2947 }
3048}
3149
50+ extension std . u16string : ExpressibleByStringLiteral {
51+ public init ( stringLiteral value: String ) {
52+ self . init ( value)
53+ }
54+ }
55+
3256extension std . string : CustomDebugStringConvertible {
3357 public var debugDescription : String {
3458 return " std.string( \( String ( self ) ) ) "
@@ -41,6 +65,8 @@ extension std.string: CustomStringConvertible {
4165 }
4266}
4367
68+ // MARK: Initializing Swift String from a C++ string
69+
4470extension String {
4571 /// Creates a String having the same content as the given C++ string.
4672 ///
@@ -58,4 +84,20 @@ extension String {
5884 }
5985 withExtendedLifetime ( cxxString) { }
6086 }
87+
88+ /// Creates a String having the same content as the given C++ UTF-16 string.
89+ ///
90+ /// If `cxxString` contains ill-formed UTF-16 code unit sequences, this
91+ /// initializer replaces them with the Unicode replacement character
92+ /// (`"\u{FFFD}"`).
93+ ///
94+ /// - Complexity: O(*n*), where *n* is the number of bytes in the C++ UTF-16
95+ /// string.
96+ public init ( _ cxxU16String: std . u16string ) {
97+ let buffer = UnsafeBufferPointer < UInt16 > (
98+ start: cxxU16String. __dataUnsafe ( ) ,
99+ count: cxxU16String. size ( ) )
100+ self = String ( decoding: buffer, as: UTF16 . self)
101+ withExtendedLifetime ( cxxU16String) { }
102+ }
61103}
0 commit comments