Skip to content

Commit c263100

Browse files
committed
[string] _HasContiguousBytes -> withContiguousStorageIfAvailable
Switch String(decoding:as) and other entry points to call withContiguousStorageIfAvailable rather than use _HasContiguousBytes.
1 parent 19b332c commit c263100

File tree

2 files changed

+22
-23
lines changed

2 files changed

+22
-23
lines changed

stdlib/public/core/String.swift

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -407,15 +407,12 @@ extension String {
407407
return
408408
}
409409

410-
if let contigBytes = codeUnits as? _HasContiguousBytes,
411-
contigBytes._providesContiguousBytesNoCopy
412-
{
413-
self = contigBytes.withUnsafeBytes { rawBufPtr in
414-
return String._fromUTF8Repairing(
415-
UnsafeBufferPointer(
416-
start: rawBufPtr.baseAddress?.assumingMemoryBound(to: UInt8.self),
417-
count: rawBufPtr.count)).0
418-
}
410+
if let str = codeUnits.withContiguousStorageIfAvailable({
411+
(buffer: UnsafeBufferPointer<C.Element>) -> String in
412+
return String._fromUTF8Repairing(
413+
UnsafeRawBufferPointer(buffer).bindMemory(to: UInt8.self)).0
414+
}) {
415+
self = str
419416
return
420417
}
421418

stdlib/public/core/StringCreate.swift

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -228,26 +228,28 @@ extension String {
228228
return _slowFromCodeUnits(input, encoding: encoding, repair: repair)
229229
}
230230

231-
var result:String? = nil
232-
233-
if let contigBytes = input as? _HasContiguousBytes,
234-
contigBytes._providesContiguousBytesNoCopy {
235-
result = contigBytes.withUnsafeBytes { rawBufPtr in
236-
let buffer = UnsafeBufferPointer(
237-
start: rawBufPtr.baseAddress?.assumingMemoryBound(to: UInt8.self),
238-
count: rawBufPtr.count)
239-
return String._fromASCIIValidating(buffer)
240-
}
231+
// Needed for double-optional due to returning optional string in
232+
// _fromASCIIValidating in withContiguousStorageIfAvailable
233+
let resultOpt: String?
234+
235+
if let strOpt = input.withContiguousStorageIfAvailable({
236+
(buffer: UnsafeBufferPointer<Input.Element>) -> String? in
237+
return String._fromASCIIValidating(
238+
UnsafeRawBufferPointer(buffer).bindMemory(to: UInt8.self))
239+
}) {
240+
resultOpt = strOpt
241241
} else {
242-
result = Array(input).withUnsafeBufferPointer {
242+
resultOpt = Array(input).withUnsafeBufferPointer {
243243
let buffer = UnsafeRawBufferPointer($0).bindMemory(to: UInt8.self)
244244
return String._fromASCIIValidating(buffer)
245245
}
246246
}
247247

248-
return result != nil ?
249-
(result!, repairsMade: false) :
250-
_slowFromCodeUnits(input, encoding: encoding, repair: repair)
248+
guard let result = resultOpt else {
249+
return _slowFromCodeUnits(input, encoding: encoding, repair: repair)
250+
}
251+
252+
return (result, repairsMade: false)
251253
}
252254

253255
public // @testable

0 commit comments

Comments
 (0)