Skip to content

Commit 2ede9a7

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

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

stdlib/public/core/CString.swift

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,29 @@ extension String {
4949
UnsafeBufferPointer(start: nullTerminatedUTF8._asUInt8, count: len)).0
5050
}
5151

52+
@inlinable
53+
@_alwaysEmitIntoClient
54+
public init(cString nullTerminatedUTF8: [CChar]) {
55+
self = nullTerminatedUTF8.withUnsafeBytes {
56+
String(_checkingCString: $0.assumingMemoryBound(to: UInt8.self))
57+
}
58+
}
59+
60+
@_alwaysEmitIntoClient
61+
private init(_checkingCString bytes: UnsafeBufferPointer<UInt8>) {
62+
guard let length = bytes.firstIndex(of: 0) else {
63+
_preconditionFailure(
64+
"input of String.init(cString:) must be null-terminated"
65+
)
66+
}
67+
self = String._fromUTF8Repairing(
68+
UnsafeBufferPointer(
69+
start: bytes.baseAddress._unsafelyUnwrappedUnchecked,
70+
count: length
71+
)
72+
).0
73+
}
74+
5275
/// Creates a new string by copying the null-terminated UTF-8 data referenced
5376
/// by the given pointer.
5477
///
@@ -60,6 +83,14 @@ extension String {
6083
UnsafeBufferPointer(start: nullTerminatedUTF8, count: len)).0
6184
}
6285

86+
@inlinable
87+
@_alwaysEmitIntoClient
88+
public init(cString nullTerminatedUTF8: [UInt8]) {
89+
self = nullTerminatedUTF8.withUnsafeBufferPointer {
90+
String(_checkingCString: $0)
91+
}
92+
}
93+
6394
/// Creates a new string by copying and validating the null-terminated UTF-8
6495
/// data referenced by the given pointer.
6596
///

0 commit comments

Comments
 (0)