Skip to content

Commit 1eee243

Browse files
committed
[stdlib] String overloads for String-from-C-string inits
1 parent 63ba39f commit 1eee243

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

stdlib/public/core/CString.swift

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,13 @@ extension String {
9191
}
9292
}
9393

94+
@inlinable
95+
@_alwaysEmitIntoClient
96+
@available(*, deprecated, message: "Operate directly on the String")
97+
public init(cString nullTerminatedUTF8: String) {
98+
self = nullTerminatedUTF8.withCString(String.init(cString:))
99+
}
100+
94101
/// Creates a new string by copying and validating the null-terminated UTF-8
95102
/// data referenced by the given pointer.
96103
///
@@ -141,6 +148,13 @@ extension String {
141148
self = string
142149
}
143150

151+
@inlinable
152+
@_alwaysEmitIntoClient
153+
@available(*, deprecated, message: "Operate directly on the String")
154+
public init?(validatingUTF8 cString: String) {
155+
self = cString.withCString(String.init(cString:))
156+
}
157+
144158
/// Creates a new string by copying the null-terminated data referenced by
145159
/// the given pointer using the specified encoding.
146160
///
@@ -248,6 +262,23 @@ extension String {
248262
}
249263
}
250264

265+
@_specialize(where Encoding == Unicode.UTF8)
266+
@_specialize(where Encoding == Unicode.UTF16)
267+
@inlinable
268+
@_alwaysEmitIntoClient
269+
@available(*, deprecated, message: "Operate directly on the String")
270+
public static func decodeCString<Encoding: _UnicodeEncoding>(
271+
_ cString: String,
272+
as encoding: Encoding.Type,
273+
repairingInvalidCodeUnits isRepairing: Bool = true
274+
) -> (result: String, repairsMade: Bool)? {
275+
return cString.withCString(encodedAs: encoding) {
276+
String.decodeCString(
277+
$0, as: encoding, repairingInvalidCodeUnits: isRepairing
278+
)
279+
}
280+
}
281+
251282
/// Creates a string from the null-terminated sequence of bytes at the given
252283
/// pointer.
253284
///
@@ -277,6 +308,20 @@ extension String {
277308
) {
278309
self = String.decodeCString(nullTerminatedCodeUnits, as: sourceEncoding)!.0
279310
}
311+
312+
@_specialize(where Encoding == Unicode.UTF8)
313+
@_specialize(where Encoding == Unicode.UTF16)
314+
@inlinable
315+
@_alwaysEmitIntoClient
316+
@available(*, deprecated, message: "Operate directly on the String")
317+
public init<Encoding: _UnicodeEncoding>(
318+
decodingCString nullTerminatedCodeUnits: String,
319+
as sourceEncoding: Encoding.Type
320+
) {
321+
self = nullTerminatedCodeUnits.withCString(encodedAs: sourceEncoding) {
322+
String(decodingCString: $0, as: sourceEncoding.self)
323+
}
324+
}
280325
}
281326

282327
extension UnsafePointer where Pointee == UInt8 {

0 commit comments

Comments
 (0)