Skip to content

Commit bb5ab74

Browse files
author
Itai Ferber
committed
Add buffering to worst-case scenarios in Data.init<S>/.append<S>
1 parent af626bf commit bb5ab74

File tree

1 file changed

+22
-6
lines changed

1 file changed

+22
-6
lines changed

stdlib/public/Darwin/Foundation/Data.swift

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -716,6 +716,14 @@ public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessColl
716716
}
717717
}
718718

719+
@inlinable // This is @inlinable as tribially computable.
720+
mutating func append(byte: UInt8) {
721+
let count = self.count
722+
assert(count + 1 <= MemoryLayout<Buffer>.size)
723+
Swift.withUnsafeMutableBytes(of: &bytes) { $0[count] = byte }
724+
self.length += 1
725+
}
726+
719727
@inlinable // This is @inlinable as trivially computable.
720728
mutating func append(contentsOf buffer: UnsafeRawBufferPointer) {
721729
guard buffer.count > 0 else { return }
@@ -2056,10 +2064,14 @@ public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessColl
20562064
// Copy the contents of buffer...
20572065
_representation = _Representation(UnsafeRawBufferPointer(start: base, count: endIndex))
20582066

2059-
// ... and append the rest byte-wise.
2067+
// ... and append the rest byte-wise, buffering through an InlineData.
2068+
var buffer = InlineData()
20602069
while let element = iter.next() {
2061-
Swift.withUnsafeBytes(of: element) {
2062-
_representation.append(contentsOf: $0)
2070+
if buffer.count < buffer.capacity {
2071+
buffer.append(byte: element)
2072+
} else {
2073+
buffer.withUnsafeBytes {_representation.append(contentsOf: $0)}
2074+
buffer.count = 0
20632075
}
20642076
}
20652077
}
@@ -2340,10 +2352,14 @@ public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessColl
23402352
// Copy the contents of the buffer...
23412353
_representation.append(contentsOf: UnsafeRawBufferPointer(start: base, count: endIndex))
23422354

2343-
/// ... and append the rest byte-wise.
2355+
// ... and append the rest byte-wise, buffering through an InlineData.
2356+
var buffer = InlineData()
23442357
while let element = iter.next() {
2345-
Swift.withUnsafeBytes(of: element) {
2346-
_representation.append(contentsOf: $0)
2358+
if buffer.count < buffer.capacity {
2359+
buffer.append(byte: element)
2360+
} else {
2361+
buffer.withUnsafeBytes {_representation.append(contentsOf: $0)}
2362+
buffer.count = 0
23472363
}
23482364
}
23492365
}

0 commit comments

Comments
 (0)