What have I done so far?个
-
我在公共documentation中寻找初始值设定项.
-
我看了看open source code,见下面的代码.
Detail个
在看了方法定义之后,我认为我们可以进一步澄清这个问题,即Sequence
/Array
将以连续的字节存储,而UTF8
将被使用.
/// Creates a string from the given Unicode code units in the specified
/// encoding.
///
/// - Parameters:
/// - codeUnits: A collection of code units encoded in the encoding
/// specified in `sourceEncoding`.
/// - sourceEncoding: The encoding in which `codeUnits` should be
/// interpreted.
@inlinable
@inline(__always) // Eliminate dynamic type check when possible
public init<C: Collection, Encoding: Unicode.Encoding>(
decoding codeUnits: C, as sourceEncoding: Encoding.Type
) where C.Iterator.Element == Encoding.CodeUnit {
guard _fastPath(sourceEncoding == UTF8.self) else {
self = String._fromCodeUnits(
codeUnits, encoding: sourceEncoding, repair: true)!.0
return
}
// Fast path for user-defined Collections and typed contiguous collections.
//
// Note: this comes first, as the optimizer nearly always has insight into
// wCSIA, but cannot prove that a type does not have conformance to
// _HasContiguousBytes.
if let str = codeUnits.withContiguousStorageIfAvailable({
(buffer: UnsafeBufferPointer<C.Element>) -> String in
Builtin.onFastPath() // encourage SIL Optimizer to inline this closure :-(
let rawBufPtr = UnsafeRawBufferPointer(buffer)
return String._fromUTF8Repairing(
UnsafeBufferPointer(
start: rawBufPtr.baseAddress?.assumingMemoryBound(to: UInt8.self),
count: rawBufPtr.count)).0
}) {
self = str
return
}
// Fast path for untyped raw storage and known stdlib types
if let contigBytes = codeUnits as? _HasContiguousBytes,
contigBytes._providesContiguousBytesNoCopy
{
self = contigBytes.withUnsafeBytes { rawBufPtr in
Builtin.onFastPath() // encourage SIL Optimizer to inline this closure
return String._fromUTF8Repairing(
UnsafeBufferPointer(
start: rawBufPtr.baseAddress?.assumingMemoryBound(to: UInt8.self),
count: rawBufPtr.count)).0
}
return
}
self = String._fromNonContiguousUnsafeBitcastUTF8Repairing(codeUnits).0
}