@@ -291,3 +291,61 @@ extension String {
291291 withExtendedLifetime ( cxxU32String) { }
292292 }
293293}
294+
295+ // MARK: Initializing Swift String from a C++ string_view
296+
297+ extension String {
298+ /// Creates a String having the same content as the given C++ string view.
299+ ///
300+ /// If `cxxStringView` contains ill-formed UTF-8 code unit sequences, this
301+ /// initializer replaces them with the Unicode replacement character
302+ /// (`"\u{FFFD}"`).
303+ ///
304+ /// - Complexity: O(*n*), where *n* is the number of bytes in the C++ string
305+ /// view.
306+ public init ( _ cxxStringView: std . string_view ) {
307+ let buffer = UnsafeBufferPointer < CChar > (
308+ start: cxxStringView. __dataUnsafe ( ) ,
309+ count: cxxStringView. size ( ) )
310+ self = buffer. withMemoryRebound ( to: UInt8 . self) {
311+ String ( decoding: $0, as: UTF8 . self)
312+ }
313+ withExtendedLifetime ( cxxStringView) { }
314+ }
315+
316+ /// Creates a String having the same content as the given C++ UTF-16 string
317+ /// view.
318+ ///
319+ /// If `cxxU16StringView` contains ill-formed UTF-16 code unit sequences, this
320+ /// initializer replaces them with the Unicode replacement character
321+ /// (`"\u{FFFD}"`).
322+ ///
323+ /// - Complexity: O(*n*), where *n* is the number of bytes in the C++ UTF-16
324+ /// string view.
325+ public init ( _ cxxU16StringView: std . u16string_view ) {
326+ let buffer = UnsafeBufferPointer < UInt16 > (
327+ start: cxxU16StringView. __dataUnsafe ( ) ,
328+ count: cxxU16StringView. size ( ) )
329+ self = String ( decoding: buffer, as: UTF16 . self)
330+ withExtendedLifetime ( cxxU16StringView) { }
331+ }
332+
333+ /// Creates a String having the same content as the given C++ UTF-32 string
334+ /// view.
335+ ///
336+ /// If `cxxU32StringView` contains ill-formed UTF-32 code unit sequences, this
337+ /// initializer replaces them with the Unicode replacement character
338+ /// (`"\u{FFFD}"`).
339+ ///
340+ /// - Complexity: O(*n*), where *n* is the number of bytes in the C++ UTF-32
341+ /// string view.
342+ public init ( _ cxxU32StringView: std . u32string_view ) {
343+ let buffer = UnsafeBufferPointer < Unicode . Scalar > (
344+ start: cxxU32StringView. __dataUnsafe ( ) ,
345+ count: cxxU32StringView. size ( ) )
346+ self = buffer. withMemoryRebound ( to: UInt32 . self) {
347+ String ( decoding: $0, as: UTF32 . self)
348+ }
349+ withExtendedLifetime ( cxxU32StringView) { }
350+ }
351+ }
0 commit comments