Skip to content

Commit 5807bb9

Browse files
committed
[stdlib] Fix _scalarName to use small string if possible
1 parent fb9f7ec commit 5807bb9

File tree

1 file changed

+29
-17
lines changed

1 file changed

+29
-17
lines changed

stdlib/public/core/UnicodeScalarProperties.swift

Lines changed: 29 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1004,28 +1004,40 @@ extension Unicode.Scalar.Properties {
10041004
internal func _scalarName(
10051005
_ choice: __swift_stdlib_UCharNameChoice
10061006
) -> String? {
1007-
let initialCapacity = 256
1008-
1009-
var storage = _SwiftStringStorage<UTF8.CodeUnit>.create(
1010-
capacity: initialCapacity,
1011-
count: 0)
1007+
// Attempt to fit it into a small UTF-8 string first. Code points names are
1008+
// guaranteed by the standard to be ASCII only.
1009+
var smallString = _SmallUTF8String()
10121010
var err = __swift_stdlib_U_ZERO_ERROR
1011+
let correctSizeRaw = smallString._withMutableExcessCapacityBytes { ptr in
1012+
return __swift_stdlib_u_charName(
1013+
_value,
1014+
choice,
1015+
ptr.baseAddress._unsafelyUnwrappedUnchecked.assumingMemoryBound(
1016+
to: Int8.self),
1017+
Int32(ptr.count),
1018+
&err)
1019+
}
10131020

1014-
let correctSize = _expandingStorageIfNeeded(&storage) { storage in
1015-
return storage.start.withMemoryRebound(
1016-
to: Int8.self,
1017-
capacity: storage.capacity
1018-
) { storagePtr in
1019-
err = __swift_stdlib_U_ZERO_ERROR
1020-
return __swift_stdlib_u_charName(
1021-
_value, choice, storagePtr, Int32(storage.capacity), &err)
1022-
}
1021+
let correctSize = Int(correctSizeRaw)
1022+
if err.isSuccess {
1023+
if correctSize == 0 { return nil }
1024+
smallString.count = correctSize
1025+
return String(_StringGuts(smallString))
1026+
}
1027+
// If the call wasn't successful, the only error we expect to see is buffer
1028+
// overflow; anything else is a severe error.
1029+
guard err == __swift_stdlib_U_BUFFER_OVERFLOW_ERROR else {
1030+
fatalError("u_charName: Unexpected error retrieving scalar name.")
10231031
}
10241032

1025-
guard err.isSuccess && correctSize > 0 else {
1026-
return nil
1033+
// If it didn't fit, we need to allocate the necessary amount of memory and
1034+
// make a regular ASCII string.
1035+
var (asciiArray, ptr) = [UInt8]._allocateUninitialized(correctSize)
1036+
_ = ptr.withMemoryRebound(to: Int8.self, capacity: correctSize) { int8Ptr in
1037+
err = __swift_stdlib_U_ZERO_ERROR
1038+
__swift_stdlib_u_charName(_value, choice, int8Ptr, correctSizeRaw, &err)
10271039
}
1028-
return String(_storage: storage)
1040+
return String._fromASCII(asciiArray)
10291041
}
10301042

10311043
/// The published name of the scalar.

0 commit comments

Comments
 (0)