[stdlib] Make unsafe array initializer public (#23134)

[stdlib] Make unsafe array initializer public

This implements SE-0245. The public versions of this initializer call
into the existing, underscored version, which avoids the need for
availability constraints.
This commit is contained in:
Nate Cook
2019-03-23 13:18:10 -05:00
committed by GitHub
parent a985f7ba19
commit b6bb9d2f8c
4 changed files with 127 additions and 42 deletions

View File

@@ -985,6 +985,43 @@ extension ContiguousArray {
}
extension ContiguousArray {
/// Creates an array with the specified capacity, then calls the given
/// closure with a buffer covering the array's uninitialized memory.
///
/// Inside the closure, set the `initializedCount` parameter to the number of
/// elements that are initialized by the closure. The memory in the range
/// `buffer[0..<initializedCount]` must be initialized at the end of the
/// closure's execution, and the memory in the range
/// `buffer[initializedCount...]` must be uninitialized. This postcondition
/// must hold even if the `initializer` closure throws an error.
///
/// - Note: While the resulting array may have a capacity larger than the
/// requested amount, the buffer passed to the closure will cover exactly
/// the requested number of elements.
///
/// - Parameters:
/// - unsafeUninitializedCapacity: The number of elements to allocate
/// space for in the new array.
/// - initializer: A closure that initializes elements and sets the count
/// of the new array.
/// - Parameters:
/// - buffer: A buffer covering uninitialized memory with room for the
/// specified number of of elements.
/// - initializedCount: The count of initialized elements in the array,
/// which begins as zero. Set `initializedCount` to the number of
/// elements you initialize.
@_alwaysEmitIntoClient @inlinable
public init(
unsafeUninitializedCapacity: Int,
initializingWith initializer: (
_ buffer: inout UnsafeMutableBufferPointer<Element>,
_ initializedCount: inout Int) throws -> Void
) rethrows {
self = try ContiguousArray(Array(
_unsafeUninitializedCapacity: unsafeUninitializedCapacity,
initializingWith: initializer))
}
/// Calls a closure with a pointer to the array's contiguous storage.
///
/// Often, the optimizer can eliminate bounds checks within an array