@@ -1004,28 +1004,40 @@ extension Unicode.Scalar.Properties {
1004
1004
internal func _scalarName(
1005
1005
_ choice: __swift_stdlib_UCharNameChoice
1006
1006
) -> 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 ( )
1012
1010
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
+ }
1013
1020
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. " )
1023
1031
}
1024
1032
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)
1027
1039
}
1028
- return String ( _storage : storage )
1040
+ return String . _fromASCII ( asciiArray )
1029
1041
}
1030
1042
1031
1043
/// The published name of the scalar.
0 commit comments