Skip to content

Commit d809640

Browse files
committed
[stdlib] overload for arrays passed to String.init?(validatingUTF8:)
1 parent 2ede9a7 commit d809640

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

stdlib/public/core/CString.swift

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,21 @@ extension String {
126126
self = str
127127
}
128128

129+
@inlinable
130+
@_alwaysEmitIntoClient
131+
public init?(validatingUTF8 cString: [CChar]) {
132+
guard let length = cString.firstIndex(of: 0) else {
133+
_preconditionFailure(
134+
"input of String.init(validatingUTF8:) must be null-terminated"
135+
)
136+
}
137+
guard let string = cString.prefix(length).withUnsafeBytes({
138+
String._tryFromUTF8($0.assumingMemoryBound(to: UInt8.self))
139+
}) else { return nil }
140+
141+
self = string
142+
}
143+
129144
/// Creates a new string by copying the null-terminated data referenced by
130145
/// the given pointer using the specified encoding.
131146
///

0 commit comments

Comments
 (0)