Skip to content

Commit 4ff7332

Browse files
author
Dave Abrahams
authored
[stdlib] Correct UnsafeBufferPointer._copyContents
The implementation imposed stricter requirements on its inputs than those allowed by Sequence
1 parent e1a4bf3 commit 4ff7332

File tree

1 file changed

+13
-18
lines changed

1 file changed

+13
-18
lines changed

stdlib/public/core/UnsafeBufferPointer.swift.gyb

Lines changed: 13 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -180,26 +180,21 @@ public struct Unsafe${Mutable}BufferPointer<Element>
180180
return startIndex..<endIndex
181181
}
182182

183-
/// Copies `self` into the supplied buffer.
183+
/// Initializes the memory at `destination.baseAddress` with elements of `self`,
184+
/// stopping when either `self` or `destination` is exhausted.
184185
///
185-
/// - Precondition: The memory in `self` is uninitialized. The buffer must
186-
/// contain sufficient uninitialized memory to accommodate `source.underestimatedCount`.
187-
///
188-
/// - Postcondition: The `Pointee`s at `buffer[startIndex..<returned index]` are
189-
/// initialized.
186+
/// - Returns: an iterator over any remaining elements of `self` and the
187+
/// number of elements initialized.
188+
@inline(__always)
190189
public func _copyContents(
191-
initializing buffer: UnsafeMutableBufferPointer<Element>
192-
) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) {
193-
guard !isEmpty else { return (makeIterator(),buffer.startIndex) }
194-
195-
guard count <= buffer.count, let ptr = buffer.baseAddress else {
196-
fatalError("Insufficient space allocated to copy buffer contents")
197-
}
198-
199-
ptr.initialize(from: baseAddress!, count: self.count)
200-
var it: Iterator = self.makeIterator()
201-
it._position = it._end
202-
return (it,buffer.index(buffer.startIndex, offsetBy: self.count))
190+
initializing destination: UnsafeMutableBufferPointer<Element>
191+
) -> (Iterator, UnsafeMutableBufferPointer<Element>.Index) {
192+
guard !isEmpty && !destination.isEmpty else { return (makeIterator(), 0) }
193+
let s = self.baseAddress._unsafelyUnwrappedUnchecked
194+
let d = destination.baseAddress._unsafelyUnwrappedUnchecked
195+
let n = Swift.min(destination.count, self.count)
196+
d.initialize(from: s, count: n)
197+
return (Iterator(_position: s + n, _end: _end), n)
203198
}
204199

205200
/// Accesses the element at the specified position.

0 commit comments

Comments
 (0)