Currently, the documentation for UnsafeMutableBufferPointer.initialize(from: Sequence)
says:
/// Initializes the buffer's memory with the given elements.
///
/// When calling the `initialize(from:)` method on a buffer `b`, the memory
/// referenced by `b` must be uninitialized or the `Element` type must be a
/// trivial type. After the call, the memory referenced by this buffer up
/// to, but not including, the returned index is initialized. The buffer
/// must contain sufficient memory to accommodate
/// `source.underestimatedCount`.
///
/// The returned index is the position of the element in the buffer one past
/// the last element written. If `source` contains no elements, the returned
/// index is equal to the buffer's `startIndex`. If `source` contains an
/// equal or greater number of elements than the buffer can hold, the
/// returned index is equal to the buffer's `endIndex`.
///
/// - Parameter source: A sequence of elements with which to initializer the
/// buffer.
/// - Returns: An iterator to any elements of `source` that didn't fit in the
/// buffer, and an index to the point in the buffer one past the last
/// element written.
public func initialize<S: Sequence>(from source: S) -> (S.Iterator, Index)
where S.Element == Element
I'd like to discuss relaxing this condition:
The buffer must contain sufficient memory to accommodate
source.underestimatedCount
.
Because this is an unsafe type, the word "must" implies that violating this condition will result in undefined behaviour. Only standard library types are able to customise how this function is implemented (via the _copyContents(initializing:)
requirement on Sequence
), and none of them will over-write the bounds of the buffer if this condition is not met - either they calculate the minimum of their and the buffer's counts and initialise that many elements, trigger a runtime error, or use the default implementation which fills the buffer from an iterator and doesn't care about underestimatedCount
.
I'd like to understand why this requirement is in place, and if there is no good reason for keeping it, I think it should be removed. This would mean changing the standard library's customisations to always initialise as much of the buffer as they can rather than trigger runtime errors, and remove this line from the documentation.
Thoughts?