10
10
//
11
11
//===----------------------------------------------------------------------===//
12
12
13
+ // MARK: Initializing C++ string from a Swift String
14
+
13
15
extension std . string {
14
16
/// Creates a C++ string having the same content as the given Swift string.
15
17
///
@@ -23,12 +25,34 @@ extension std.string {
23
25
}
24
26
}
25
27
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
+
26
44
extension std . string : ExpressibleByStringLiteral {
27
45
public init ( stringLiteral value: String ) {
28
46
self . init ( value)
29
47
}
30
48
}
31
49
50
+ extension std . u16string : ExpressibleByStringLiteral {
51
+ public init ( stringLiteral value: String ) {
52
+ self . init ( value)
53
+ }
54
+ }
55
+
32
56
extension std . string : CustomDebugStringConvertible {
33
57
public var debugDescription : String {
34
58
return " std.string( \( String ( self ) ) ) "
@@ -41,6 +65,8 @@ extension std.string: CustomStringConvertible {
41
65
}
42
66
}
43
67
68
+ // MARK: Initializing Swift String from a C++ string
69
+
44
70
extension String {
45
71
/// Creates a String having the same content as the given C++ string.
46
72
///
@@ -58,4 +84,20 @@ extension String {
58
84
}
59
85
withExtendedLifetime ( cxxString) { }
60
86
}
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
+ }
61
103
}
0 commit comments