Skip to content

Commit b4e40ce

Browse files
authored
Add fast paths for Data initialization for common sequences (#1051)
1 parent f3bf89a commit b4e40ce

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

Foundation/Data.swift

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1082,6 +1082,43 @@ public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessColl
10821082

10831083
}
10841084

1085+
// slightly faster paths for common sequences
1086+
1087+
public init<S: Sequence>(_ elements: S) where S.Iterator.Element == UInt8 {
1088+
let underestimatedCount = elements.underestimatedCount
1089+
self.init(count: underestimatedCount)
1090+
var idx = 0
1091+
for byte in elements {
1092+
if idx < underestimatedCount {
1093+
self[idx] = byte
1094+
} else {
1095+
self.append(byte)
1096+
}
1097+
idx += 1
1098+
}
1099+
}
1100+
1101+
public init(_ bytes: Array<UInt8>) {
1102+
self.init(bytes: bytes)
1103+
}
1104+
1105+
public init(_ bytes: ArraySlice<UInt8>) {
1106+
self.init(bytes: bytes)
1107+
}
1108+
1109+
public init(_ buffer: UnsafeBufferPointer<UInt8>) {
1110+
self.init(buffer: buffer)
1111+
}
1112+
1113+
public init(_ buffer: UnsafeMutableBufferPointer<UInt8>) {
1114+
self.init(buffer: buffer)
1115+
}
1116+
1117+
public init(_ data: Data) {
1118+
_sliceRange = 0..<data.count
1119+
_backing = data._backing.mutableCopy(data._sliceRange)
1120+
}
1121+
10851122
@_versioned
10861123
internal init(backing: _DataStorage, range: Range<Index>) {
10871124
_backing = backing

0 commit comments

Comments
 (0)