最终都要走到__StringStorage
的 create(realCodeUnitCapacity,countAndFlags)
方法里去。
默认实现是 UTF8
internal static func _fromCodeUnits(_ input: Input,encoding: Encoding.Type,repair: Bool) -> (String, repairsMade: Bool)?where Input.Element == Encoding.CodeUnit {// TODO(String Performance): Attempt to form smol strings// TODO(String performance): Skip intermediary array, transcode directly// into a StringStorage space.var contents: [UInt8] = []contents.reserveCapacity(input.underestimatedCount)let repaired = transcode(input.makeIterator(),from: Encoding.self,to: UTF8.self,stoppingOnError: false,into: { contents.append($0) })guard repair || !repaired else { return nil }let str = contents.withUnsafeBufferPointer { String._uncheckedFromUTF8($0) }return (str, repaired)}
可以看到,把其他的编码方式,都转为了UTF8,然后编码后的缓存序列去创建了一个__StringStorage
@usableFromInlineinternal static func _uncheckedFromUTF8(_ input: UnsafeBufferPointer, asciiPreScanResult: Bool) -> String {if let smol = _SmallString(input) {return String(_StringGuts(smol))}let isASCII = asciiPreScanResultlet storage = __StringStorage.create(initializingFrom: input, isASCII: isASCII)return storage.asString}
在创建过程中,又判断是否是_SmallString
。