Skip to content

Commit f04ed60

Browse files
committed
[stdlib] remove most uses of _asCChar and _asUInt8
1 parent 3e8d153 commit f04ed60

File tree

2 files changed

+11
-9
lines changed

2 files changed

+11
-9
lines changed

stdlib/public/core/CString.swift

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,9 @@ extension String {
4545
/// - Parameter nullTerminatedUTF8: A pointer to a null-terminated UTF-8 code sequence.
4646
public init(cString nullTerminatedUTF8: UnsafePointer<CChar>) {
4747
let len = UTF8._nullCodeUnitOffset(in: nullTerminatedUTF8)
48-
self = String._fromUTF8Repairing(
49-
UnsafeBufferPointer(start: nullTerminatedUTF8._asUInt8, count: len)).0
48+
self = nullTerminatedUTF8.withMemoryRebound(to: UInt8.self, capacity: len) {
49+
String._fromUTF8Repairing(UnsafeBufferPointer(start: $0, count: len)).0
50+
}
5051
}
5152

5253
@inlinable
@@ -150,8 +151,9 @@ extension String {
150151
/// - Parameter cString: A pointer to a null-terminated UTF-8 code sequence.
151152
public init?(validatingUTF8 cString: UnsafePointer<CChar>) {
152153
let len = UTF8._nullCodeUnitOffset(in: cString)
153-
guard let str = String._tryFromUTF8(
154-
UnsafeBufferPointer(start: cString._asUInt8, count: len))
154+
guard let str = cString.withMemoryRebound(to: UInt8.self, capacity: len, {
155+
String._tryFromUTF8(UnsafeBufferPointer(start: $0, count: len))
156+
})
155157
else { return nil }
156158

157159
self = str
@@ -165,9 +167,10 @@ extension String {
165167
"input of String.init(validatingUTF8:) must be null-terminated"
166168
)
167169
}
168-
guard let string = cString.prefix(length).withUnsafeBytes({
169-
String._tryFromUTF8($0.assumingMemoryBound(to: UInt8.self))
170-
}) else { return nil }
170+
guard let string = cString.prefix(length).withUnsafeBufferPointer({
171+
$0.withMemoryRebound(to: UInt8.self, String._tryFromUTF8(_:))
172+
})
173+
else { return nil }
171174

172175
self = string
173176
}

stdlib/public/core/StringGuts.swift

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -167,8 +167,7 @@ extension _StringGuts {
167167
_ f: (UnsafeBufferPointer<CChar>) throws -> R
168168
) rethrows -> R {
169169
return try self.withFastUTF8 { utf8 in
170-
let ptr = utf8.baseAddress._unsafelyUnwrappedUnchecked._asCChar
171-
return try f(UnsafeBufferPointer(start: ptr, count: utf8.count))
170+
return try utf8.withMemoryRebound(to: CChar.self, f)
172171
}
173172
}
174173
}

0 commit comments

Comments
 (0)