[stdlib] remove most uses of _asCChar and _asUInt8

This commit is contained in:
Guillaume Lessard
2022-04-06 15:21:00 -06:00
parent 8032a7c0c9
commit 8379b2422a
2 changed files with 11 additions and 9 deletions

View File

@@ -45,8 +45,9 @@ extension String {
/// - Parameter nullTerminatedUTF8: A pointer to a null-terminated UTF-8 code sequence. /// - Parameter nullTerminatedUTF8: A pointer to a null-terminated UTF-8 code sequence.
public init(cString nullTerminatedUTF8: UnsafePointer<CChar>) { public init(cString nullTerminatedUTF8: UnsafePointer<CChar>) {
let len = UTF8._nullCodeUnitOffset(in: nullTerminatedUTF8) let len = UTF8._nullCodeUnitOffset(in: nullTerminatedUTF8)
self = String._fromUTF8Repairing( self = nullTerminatedUTF8.withMemoryRebound(to: UInt8.self, capacity: len) {
UnsafeBufferPointer(start: nullTerminatedUTF8._asUInt8, count: len)).0 String._fromUTF8Repairing(UnsafeBufferPointer(start: $0, count: len)).0
}
} }
@inlinable @inlinable
@@ -150,8 +151,9 @@ extension String {
/// - Parameter cString: A pointer to a null-terminated UTF-8 code sequence. /// - Parameter cString: A pointer to a null-terminated UTF-8 code sequence.
public init?(validatingUTF8 cString: UnsafePointer<CChar>) { public init?(validatingUTF8 cString: UnsafePointer<CChar>) {
let len = UTF8._nullCodeUnitOffset(in: cString) let len = UTF8._nullCodeUnitOffset(in: cString)
guard let str = String._tryFromUTF8( guard let str = cString.withMemoryRebound(to: UInt8.self, capacity: len, {
UnsafeBufferPointer(start: cString._asUInt8, count: len)) String._tryFromUTF8(UnsafeBufferPointer(start: $0, count: len))
})
else { return nil } else { return nil }
self = str self = str
@@ -165,9 +167,10 @@ extension String {
"input of String.init(validatingUTF8:) must be null-terminated" "input of String.init(validatingUTF8:) must be null-terminated"
) )
} }
guard let string = cString.prefix(length).withUnsafeBytes({ guard let string = cString.prefix(length).withUnsafeBufferPointer({
String._tryFromUTF8($0.assumingMemoryBound(to: UInt8.self)) $0.withMemoryRebound(to: UInt8.self, String._tryFromUTF8(_:))
}) else { return nil } })
else { return nil }
self = string self = string
} }

View File

@@ -167,8 +167,7 @@ extension _StringGuts {
_ f: (UnsafeBufferPointer<CChar>) throws -> R _ f: (UnsafeBufferPointer<CChar>) throws -> R
) rethrows -> R { ) rethrows -> R {
return try self.withFastUTF8 { utf8 in return try self.withFastUTF8 { utf8 in
let ptr = utf8.baseAddress._unsafelyUnwrappedUnchecked._asCChar return try utf8.withMemoryRebound(to: CChar.self, f)
return try f(UnsafeBufferPointer(start: ptr, count: utf8.count))
} }
} }
} }