mirror of
https://github.com/apple/swift-collections
synced 2026-11-30 05:18:44 +00:00
Rigid, Unique types: Rework OutputSpan-based append/prepend/insert/replaceSubrange primitives
This commit is contained in:
19 files changed
+887
-260
No files matched your search
@@ -60,29 +60,33 @@ extension RigidArray where Element: ~Copyable {
|
||||
/// If the array does not have sufficient capacity to store the new items in
|
||||
/// the buffer, then this triggers a runtime error.
|
||||
///
|
||||
/// - Parameters
|
||||
/// - uninitializedCount: The number of items to append to the array.
|
||||
/// - body: A callback that gets called at most once to directly
|
||||
/// If the callback fails to fully populate its output span or if
|
||||
/// it throws an error, then the array keeps all items that were
|
||||
/// successfully initialized before the callback terminated the insertion.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - newItemCount: The number of items to append to the array.
|
||||
/// - initializer: A callback that gets called at most once to directly
|
||||
/// populate newly reserved storage within the array. The function
|
||||
/// is allowed to initialize fewer than `uninitializedCount` items.
|
||||
/// is allowed to initialize fewer than `newItemCount` items.
|
||||
/// The array is appended however many items the callback adds to
|
||||
/// the output span before it returns (or before it throws an error).
|
||||
///
|
||||
/// - Complexity: O(`uninitializedCount`)
|
||||
/// - Complexity: O(`newItemCount`)
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func append<E: Error>(
|
||||
addingCapacity uninitializedCount: Int,
|
||||
initializingWith body: (inout OutputSpan<Element>) throws(E) -> Void
|
||||
addingCount newItemCount: Int,
|
||||
initializingWith initializer: (inout OutputSpan<Element>) throws(E) -> Void
|
||||
) throws(E) {
|
||||
precondition(uninitializedCount >= 0, "Negative count")
|
||||
precondition(freeCapacity >= uninitializedCount, "RigidArray capacity overflow")
|
||||
let buffer = _freeSpace._extracting(first: uninitializedCount)
|
||||
precondition(newItemCount >= 0, "Cannot add a negative number of items")
|
||||
precondition(freeCapacity >= newItemCount, "RigidArray capacity overflow")
|
||||
let buffer = _freeSpace._extracting(first: newItemCount)
|
||||
var span = OutputSpan(buffer: buffer, initializedCount: 0)
|
||||
defer {
|
||||
_count &+= span.finalize(for: buffer)
|
||||
span = OutputSpan()
|
||||
}
|
||||
return try body(&span)
|
||||
return try initializer(&span)
|
||||
}
|
||||
|
||||
/// Append a given number of items to the end of this array by populating
|
||||
@@ -91,29 +95,25 @@ extension RigidArray where Element: ~Copyable {
|
||||
/// If the array does not have sufficient capacity to store the new items in
|
||||
/// the buffer, then this triggers a runtime error.
|
||||
///
|
||||
/// If the callback fails to fully populate its output span or if
|
||||
/// it throws an error, then the items that were successfully initialized
|
||||
/// still get appended to the end of the array.
|
||||
///
|
||||
/// - Parameters
|
||||
/// - Parameters:
|
||||
/// - count: The number of items to append to the array.
|
||||
/// - body: A callback that gets called at most once to directly
|
||||
/// - initializer: A callback that gets called at most once to directly
|
||||
/// populate newly reserved storage within the array. The function
|
||||
/// is allowed to initialize fewer than `count` items. The array is
|
||||
/// appended however many items the callback adds to the output span
|
||||
/// before it returns (or before it throws an error).
|
||||
///
|
||||
/// - Complexity: O(`count`)
|
||||
@available(*, deprecated, renamed: "append(addingCapacity:initializingWith:)")
|
||||
@available(*, deprecated, renamed: "append(addingCount:initializingWith:)")
|
||||
@_alwaysEmitIntoClient
|
||||
@inline(__always)
|
||||
public mutating func append<E: Error, Result: ~Copyable>(
|
||||
count: Int,
|
||||
initializingWith body: (inout OutputSpan<Element>) throws(E) -> Result
|
||||
initializingWith initializer: (inout OutputSpan<Element>) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
var result: Result? = nil
|
||||
try append(addingCapacity: count) { target throws(E) in
|
||||
result = try body(&target)
|
||||
try append(addingCount: count) { target throws(E) in
|
||||
result = try initializer(&target)
|
||||
}
|
||||
return result.take()!
|
||||
}
|
||||
|
||||
@@ -55,10 +55,10 @@ extension RigidArray where Element: ~Copyable {
|
||||
@inlinable
|
||||
public init<E: Error>(
|
||||
capacity: Int,
|
||||
initializingWith body: (inout OutputSpan<Element>) throws(E) -> Void
|
||||
initializingWith initializer: (inout OutputSpan<Element>) throws(E) -> Void
|
||||
) throws(E) {
|
||||
self.init(capacity: capacity)
|
||||
try edit(body)
|
||||
try edit(initializer)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -52,6 +52,69 @@ extension RigidArray where Element: ~Copyable {
|
||||
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
extension RigidArray where Element: ~Copyable {
|
||||
/// Inserts a given number of new items into this array at the specified
|
||||
/// position, using a callback to directly initialize array storage by
|
||||
/// populating an output span.
|
||||
///
|
||||
/// Existing elements in the array's storage are moved towards the back as
|
||||
/// needed to make room for the new items.
|
||||
///
|
||||
/// If the capacity of the array isn't sufficient to accommodate the specified
|
||||
/// number of new elements, then this method triggers a runtime error.
|
||||
///
|
||||
/// var buffer = RigidArray<Int>(capacity: 20)
|
||||
/// buffer.append([-999, 999])
|
||||
/// var i = 0
|
||||
/// buffer.insert(capacity: 3, at: 1) { target in
|
||||
/// while !target.isFull {
|
||||
/// target.append(i)
|
||||
/// i += 1
|
||||
/// }
|
||||
/// }
|
||||
/// // `buffer` now contains [-999, 0, 1, 2, 999]
|
||||
///
|
||||
/// If the callback fails to fully populate its output span or if
|
||||
/// it throws an error, then the array keeps all items that were
|
||||
/// successfully initialized before the callback terminated the insertion.
|
||||
///
|
||||
/// Partial insertions create a gap in array storage that needs to be
|
||||
/// closed by moving already inserted items to their correct positions given
|
||||
/// the adjusted count. This adds some overhead compared to adding exactly as
|
||||
/// many items as promised.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - newItemCount: The maximum number of items to insert into the array.
|
||||
/// - index: The position at which to insert the new items.
|
||||
/// `index` must be a valid index in the array.
|
||||
/// - initializer: A callback that gets called at most once to directly
|
||||
/// populate newly reserved storage within the array. The function
|
||||
/// is always called with an empty output span.
|
||||
///
|
||||
/// - Complexity: O(`self.count` + `newItemCount`) in addition to the complexity
|
||||
/// of the callback invocations.
|
||||
@_alwaysEmitIntoClient
|
||||
@inline(__always)
|
||||
public mutating func insert<E: Error>(
|
||||
addingCount newItemCount: Int,
|
||||
at index: Int,
|
||||
initializingWith initializer: (inout OutputSpan<Element>) throws(E) -> Void
|
||||
) throws(E) {
|
||||
precondition(index >= 0 && index <= self.count, "Index out of bounds")
|
||||
precondition(newItemCount >= 0, "Cannot add a negative number of items")
|
||||
precondition(newItemCount <= freeCapacity, "RigidArray capacity overflow")
|
||||
let target = unsafe _openGap(at: index, count: newItemCount)
|
||||
var span = OutputSpan(buffer: target, initializedCount: 0)
|
||||
defer {
|
||||
let c = span.finalize(for: target)
|
||||
if c < newItemCount {
|
||||
_closeGap(at: index &+ c, count: newItemCount &- c)
|
||||
}
|
||||
_count &+= c
|
||||
span = OutputSpan()
|
||||
}
|
||||
try initializer(&span)
|
||||
}
|
||||
|
||||
/// Inserts a given number of new items into this array at the specified
|
||||
/// position, using a callback to directly initialize array storage by
|
||||
/// populating an output span.
|
||||
@@ -66,31 +129,24 @@ extension RigidArray where Element: ~Copyable {
|
||||
/// - count: The number of items to insert into the array.
|
||||
/// - index: The position at which to insert the new items.
|
||||
/// `index` must be a valid index in the array.
|
||||
/// - body: A callback that gets called at most once to directly
|
||||
/// - body: A callback that gets called exactly once to directly
|
||||
/// populate newly reserved storage within the array. The function
|
||||
/// is called with an empty output span of capacity matching the
|
||||
/// supplied count, and it must fully populate it before returning.
|
||||
///
|
||||
/// - Complexity: O(`self.count` + `count`)
|
||||
@available(*, deprecated, renamed: "insert(addingCount:at:initializingWith:)")
|
||||
@inlinable
|
||||
public mutating func insert<Result: ~Copyable>(
|
||||
count: Int,
|
||||
at index: Int,
|
||||
initializingWith body: (inout OutputSpan<Element>) -> Result
|
||||
) -> Result {
|
||||
// FIXME: This does not allow `body` to throw, to prevent having to move the tail twice. Is that okay?
|
||||
precondition(index >= 0 && index <= self.count, "Index out of bounds")
|
||||
precondition(count >= 0, "Negative count")
|
||||
precondition(count <= freeCapacity, "RigidArray capacity overflow")
|
||||
let target = unsafe _openGap(at: index, count: count)
|
||||
var span = OutputSpan(buffer: target, initializedCount: 0)
|
||||
defer {
|
||||
let c = span.finalize(for: target)
|
||||
precondition(c == count, "Inserted fewer items than promised")
|
||||
_count &+= c
|
||||
span = OutputSpan()
|
||||
var result: Result? = nil
|
||||
self.insert(addingCount: count, at: index) { target in
|
||||
result = body(&target)
|
||||
}
|
||||
return body(&span)
|
||||
return result!
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,7 +174,7 @@ extension RigidArray where Element: ~Copyable {
|
||||
moving items: UnsafeMutableBufferPointer<Element>,
|
||||
at index: Int
|
||||
) {
|
||||
insert(count: items.count, at: index) { target in
|
||||
insert(addingCount: items.count, at: index) { target in
|
||||
target._append(moving: items)
|
||||
}
|
||||
}
|
||||
@@ -205,7 +261,7 @@ extension RigidArray where Element: ~Copyable {
|
||||
) {
|
||||
// FIXME: Remove this in favor of a generic algorithm over consumable containers
|
||||
guard !items.isEmpty else { return }
|
||||
insert(count: items.count, at: index) { target in
|
||||
insert(addingCount: items.count, at: index) { target in
|
||||
items.edit { source in
|
||||
target._append(moving: &source)
|
||||
}
|
||||
@@ -270,7 +326,7 @@ extension RigidArray {
|
||||
copying newElements: UnsafeBufferPointer<Element>, at index: Int
|
||||
) {
|
||||
guard newElements.count > 0 else { return }
|
||||
self.insert(count: newElements.count, at: index) { target in
|
||||
self.insert(addingCount: newElements.count, at: index) { target in
|
||||
target._append(copying: newElements)
|
||||
}
|
||||
}
|
||||
@@ -328,7 +384,7 @@ extension RigidArray {
|
||||
copying newElements: Span<Element>, at index: Int
|
||||
) {
|
||||
guard newElements.count > 0 else { return }
|
||||
self.insert(count: newElements.count, at: index) { target in
|
||||
self.insert(addingCount: newElements.count, at: index) { target in
|
||||
target._append(copying: newElements)
|
||||
}
|
||||
}
|
||||
@@ -343,7 +399,7 @@ extension RigidArray {
|
||||
copying items: borrowing C,
|
||||
newCount: Int
|
||||
) {
|
||||
insert(count: newCount, at: index) { target in
|
||||
insert(addingCount: newCount, at: index) { target in
|
||||
target.withUnsafeMutableBufferPointer { buffer, count in
|
||||
let copied = items._copyContents(intoPrefixOf: buffer)
|
||||
precondition(
|
||||
|
||||
@@ -181,7 +181,7 @@ extension RigidArray where Element: ~Copyable {
|
||||
/// passing an input span to the given function to consume them in place.
|
||||
///
|
||||
/// - Parameter bounds: The subrange of items to consume from this array.
|
||||
/// - Parameter body: A function taking an input span of the removed items,
|
||||
/// - Parameter consumer: A function taking an input span of the removed items,
|
||||
/// allowing them to be consumed straight out of the array's storage.
|
||||
/// The function is not required to consume all items in the span;
|
||||
/// however, the span's remaining items will still be removed from
|
||||
@@ -191,14 +191,14 @@ extension RigidArray where Element: ~Copyable {
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func consumeSubrange<E: Error, Result: ~Copyable>(
|
||||
_ bounds: Range<Int>,
|
||||
consumingWith body: (inout InputSpan<Element>) throws(E) -> Result
|
||||
consumingWith consumer: (inout InputSpan<Element>) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
precondition(
|
||||
bounds.lowerBound >= 0 && bounds.upperBound <= _count,
|
||||
"Subrange out of bounds")
|
||||
guard !bounds.isEmpty else {
|
||||
var span = InputSpan<Element>()
|
||||
return try body(&span)
|
||||
return try consumer(&span)
|
||||
}
|
||||
let buffer = unsafe _storage.extracting(bounds)
|
||||
var span = InputSpan(buffer: buffer, initializedCount: buffer.count)
|
||||
@@ -209,7 +209,7 @@ extension RigidArray where Element: ~Copyable {
|
||||
_count -= bounds.count
|
||||
span = InputSpan()
|
||||
}
|
||||
return try body(&span)
|
||||
return try consumer(&span)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -18,6 +18,87 @@ import ContainersPreview
|
||||
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
extension RigidArray where Element: ~Copyable {
|
||||
/// Replaces the specified range of elements by a given count of new items,
|
||||
/// using a callback to directly initialize array storage by populating
|
||||
/// an output span.
|
||||
///
|
||||
/// The number of new items need not match the number of elements being
|
||||
/// removed.
|
||||
///
|
||||
/// This method has the same overall effect as calling
|
||||
///
|
||||
/// try array.removeSubrange(subrange)
|
||||
/// try array.insert(
|
||||
/// addingCount: newItemCount,
|
||||
/// at: subrange.lowerBound,
|
||||
/// initializingWith: initializer)
|
||||
///
|
||||
/// Except it performs faster (by a constant factor), by avoiding moving
|
||||
/// some items in the array twice.
|
||||
///
|
||||
/// If the array does not have sufficient capacity to accommodate the new
|
||||
/// elements, then this method triggers a runtime error.
|
||||
///
|
||||
/// If the callback fails to fully populate its output span or if
|
||||
/// it throws an error, then the array keeps all items that were
|
||||
/// successfully initialized before the callback terminated the prepend.
|
||||
///
|
||||
/// Partial insertions create a gap in array storage that needs to be
|
||||
/// closed by moving newly inserted items to their correct positions given
|
||||
/// the adjusted count. This adds some overhead compared to adding exactly as
|
||||
/// many items as promised.
|
||||
///
|
||||
/// - Parameters
|
||||
/// - subrange: The subrange of the array to replace. The bounds of
|
||||
/// the range must be valid indices in the array.
|
||||
/// - newItemCount: the maximum number of items to replace the old subrange.
|
||||
/// - initializer: A callback that gets called at most once to directly
|
||||
/// populate newly reserved storage within the array. The function
|
||||
/// is always called with an empty output span.
|
||||
///
|
||||
/// - Complexity: O(`self.count` + `newItemCount`) in addition to the complexity
|
||||
/// of the callback invocations.
|
||||
@inlinable
|
||||
public mutating func replaceSubrange<E: Error>(
|
||||
_ subrange: Range<Int>,
|
||||
addingCount newItemCount: Int,
|
||||
initializingWith initializer: (inout OutputSpan<Element>) throws(E) -> Void
|
||||
) throws(E) -> Void {
|
||||
precondition(
|
||||
subrange.lowerBound >= 0 && subrange.upperBound <= _count,
|
||||
"Index range out of bounds")
|
||||
precondition(newItemCount >= 0, "Cannot add a negative number of items")
|
||||
precondition(
|
||||
newItemCount - subrange.count <= freeCapacity,
|
||||
"RigidArray capacity overflow")
|
||||
try _uncheckedReplaceSubrange(
|
||||
subrange,
|
||||
addingCount: newItemCount,
|
||||
initializingWith: initializer)
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal mutating func _uncheckedReplaceSubrange<E: Error>(
|
||||
_ subrange: Range<Int>,
|
||||
addingCount newItemCount: Int,
|
||||
initializingWith initializer: (inout OutputSpan<Element>) throws(E) -> Void
|
||||
) throws(E) -> Void {
|
||||
// Destroy removed items
|
||||
unsafe _items.extracting(subrange).deinitialize()
|
||||
let target = _resizeGap(in: subrange, to: newItemCount)
|
||||
var span = OutputSpan(buffer: target, initializedCount: 0)
|
||||
defer {
|
||||
let c = span.finalize(for: target)
|
||||
if c < newItemCount {
|
||||
self._closeGap(
|
||||
at: subrange.lowerBound &+ c,
|
||||
count: capacity &- c)
|
||||
}
|
||||
span = OutputSpan()
|
||||
}
|
||||
try initializer(&span)
|
||||
}
|
||||
|
||||
/// Replaces the specified range of elements by a given count of new items,
|
||||
/// using a callback to directly initialize array storage by populating
|
||||
/// an output span.
|
||||
@@ -42,32 +123,132 @@ extension RigidArray where Element: ~Copyable {
|
||||
/// - subrange: The subrange of the array to replace. The bounds of
|
||||
/// the range must be valid indices in the array.
|
||||
/// - newCount: the number of items to replace the old subrange.
|
||||
/// - body: A callback that gets called at most once to directly
|
||||
/// - body: A callback that gets called exactly once to directly
|
||||
/// populate newly reserved storage within the array. The function
|
||||
/// is called with an empty output span of capacity `newCount`,
|
||||
/// and it must fully populate it before returning.
|
||||
///
|
||||
/// - Complexity: O(`self.count` + `newCount`)
|
||||
@available(*, deprecated, renamed: "replaceSubrange(_:addingCapacity:initializingWith:)")
|
||||
@inlinable
|
||||
public mutating func replaceSubrange<Result: ~Copyable>(
|
||||
_ subrange: Range<Int>,
|
||||
newCount: Int,
|
||||
initializingWith body: (inout OutputSpan<Element>) -> Result
|
||||
) -> Result {
|
||||
// FIXME: Should we allow throwing (and a partially filled output span)?
|
||||
// FIXME: Should we have a version of this with two closures, to allow custom-consuming the old items?
|
||||
// replaceSubrange(5..<10, newCount: 3, consumingWith: {...}, initializingWith: {...})
|
||||
let target = _gapForReplacement(of: subrange, withNewCount: newCount)
|
||||
var span = OutputSpan(buffer: target, initializedCount: 0)
|
||||
defer {
|
||||
let c = span.finalize(for: target)
|
||||
precondition(c == newCount, "Inserted fewer items than promised")
|
||||
span = OutputSpan()
|
||||
var result: Result? = nil
|
||||
self.replaceSubrange(subrange, addingCount: newCount) { target in
|
||||
result = body(&target)
|
||||
}
|
||||
return body(&span)
|
||||
return result!
|
||||
}
|
||||
}
|
||||
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
extension RigidArray where Element: ~Copyable {
|
||||
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
|
||||
/// Replaces the specified range of elements by a given count of new items,
|
||||
/// using callbacks to consume old items, and to then insert new ones.
|
||||
///
|
||||
/// The number of new items need not match the number of elements being
|
||||
/// removed.
|
||||
///
|
||||
/// This method has the same overall effect as calling
|
||||
///
|
||||
/// try array.consume(subrange, consumingWith: consumer)
|
||||
/// try array.insert(
|
||||
/// addingCount: newItemCount,
|
||||
/// at: subrange.lowerBound,
|
||||
/// initializingWith: initializer)
|
||||
///
|
||||
/// Except it performs faster (by a constant factor), by avoiding moving
|
||||
/// some items in the deque twice.
|
||||
///
|
||||
/// If the capacity of the array isn't sufficient to accommodate the specified
|
||||
/// number of new elements, then this method triggers a runtime error.
|
||||
///
|
||||
/// The `consumer` callback is not required to fully depopulate its input
|
||||
/// span. Any items the callback leaves in the span still get removed and
|
||||
/// discarded from the array before insertions begin.
|
||||
///
|
||||
/// The `initializer` callback is not required to fully populate its
|
||||
/// output span, and it is allowed to throw an error. In such cases, the
|
||||
/// deque keeps all items that were successfully initialized before the
|
||||
/// callback terminated.
|
||||
///
|
||||
/// Partial insertions create a gap in array storage that needs to be
|
||||
/// closed by moving newly inserted items to their correct positions given
|
||||
/// the adjusted count. This adds some overhead compared to adding exactly as
|
||||
/// many items as promised.
|
||||
///
|
||||
/// - Parameters
|
||||
/// - subrange: The subrange of the deque to replace. The bounds of
|
||||
/// the range must be valid indices in the deque.
|
||||
/// - newItemCount: the maximum number of items to replace the old subrange.
|
||||
/// - consumer: A callback that gets called at most once to consume
|
||||
/// the elements to be removed directly from the deque's storage. The
|
||||
/// function is always called with a non-empty input span.
|
||||
/// - initializer: A callback that gets called at most once to directly
|
||||
/// populate newly reserved storage within the deque. The function
|
||||
/// is always called with an empty output span.
|
||||
///
|
||||
/// - Complexity: O(`self.count` + `newItemCount`) in addition to the
|
||||
/// complexity of the callback invocations.
|
||||
@inlinable
|
||||
public mutating func replaceSubrange<E: Error>(
|
||||
_ subrange: Range<Int>,
|
||||
addingCount newItemCount: Int,
|
||||
consumingWith consumer: (inout InputSpan<Element>) -> Void,
|
||||
initializingWith initializer: (inout OutputSpan<Element>) throws(E) -> Void
|
||||
) throws(E) -> Void {
|
||||
precondition(
|
||||
subrange.lowerBound >= 0 && subrange.upperBound <= _count,
|
||||
"Index range out of bounds")
|
||||
precondition(newItemCount >= 0, "Cannot add a negative number of items")
|
||||
precondition(
|
||||
newItemCount - subrange.count <= freeCapacity,
|
||||
"RigidArray capacity overflow")
|
||||
try _uncheckedReplaceSubrange(
|
||||
subrange,
|
||||
addingCount: newItemCount,
|
||||
consumingWith: consumer,
|
||||
initializingWith: initializer)
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal mutating func _uncheckedReplaceSubrange<E: Error>(
|
||||
_ subrange: Range<Int>,
|
||||
addingCount newItemCount: Int,
|
||||
consumingWith consumer: (inout InputSpan<Element>) -> Void,
|
||||
initializingWith initializer: (inout OutputSpan<Element>) throws(E) -> Void
|
||||
) throws(E) -> Void {
|
||||
do {
|
||||
// Consume items to be removed
|
||||
let buffer = unsafe _storage.extracting(subrange)
|
||||
var span = InputSpan(buffer: buffer, initializedCount: buffer.count)
|
||||
consumer(&span)
|
||||
_ = consume span
|
||||
}
|
||||
do {
|
||||
// Insert new items
|
||||
let target = _resizeGap(in: subrange, to: newItemCount)
|
||||
var span = OutputSpan(buffer: target, initializedCount: 0)
|
||||
defer {
|
||||
let c = span.finalize(for: target)
|
||||
if c < newItemCount {
|
||||
self._closeGap(
|
||||
at: subrange.lowerBound &+ c,
|
||||
count: capacity &- c)
|
||||
}
|
||||
span = OutputSpan()
|
||||
}
|
||||
try initializer(&span)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
extension RigidArray where Element: ~Copyable {
|
||||
/// Replaces the specified range of elements by moving the elements of a
|
||||
@@ -103,7 +284,7 @@ extension RigidArray where Element: ~Copyable {
|
||||
_ subrange: Range<Int>,
|
||||
moving newElements: UnsafeMutableBufferPointer<Element>,
|
||||
) {
|
||||
replaceSubrange(subrange, newCount: newElements.count) { target in
|
||||
replaceSubrange(subrange, addingCount: newElements.count) { target in
|
||||
target._withUnsafeMutableBufferPointer { buffer, count in
|
||||
count = unsafe buffer._moveInitializePrefix(from: newElements)
|
||||
}
|
||||
@@ -303,7 +484,7 @@ extension RigidArray {
|
||||
_ subrange: Range<Int>,
|
||||
copying newElements: UnsafeBufferPointer<Element>
|
||||
) {
|
||||
replaceSubrange(subrange, newCount: newElements.count) { target in
|
||||
replaceSubrange(subrange, addingCount: newElements.count) { target in
|
||||
target._withUnsafeMutableBufferPointer { buffer, count in
|
||||
count = unsafe buffer._initializePrefix(copying: newElements)
|
||||
}
|
||||
@@ -392,7 +573,7 @@ extension RigidArray {
|
||||
copyingContainer newElements: borrowing C,
|
||||
newCount: Int
|
||||
) {
|
||||
self.replaceSubrange(subrange, newCount: newCount) { target in
|
||||
self.replaceSubrange(subrange, addingCapacity: newCount) { target in
|
||||
target.withUnsafeMutableBufferPointer { buffer, count in
|
||||
count = newElements._copyContents(intoPrefixOf: buffer)
|
||||
precondition(
|
||||
@@ -410,7 +591,7 @@ extension RigidArray {
|
||||
copyingCollection newElements: __owned some Collection<Element>,
|
||||
newCount: Int
|
||||
) {
|
||||
self.replaceSubrange(subrange, newCount: newCount) { target in
|
||||
self.replaceSubrange(subrange, addingCount: newCount) { target in
|
||||
target._withUnsafeMutableBufferPointer { dst, dstCount in
|
||||
let done: Void? = newElements.withContiguousStorageIfAvailable { src in
|
||||
let i = unsafe dst._initializePrefix(copying: src)
|
||||
|
||||
@@ -445,6 +445,32 @@ extension RigidArray where Element: ~Copyable {
|
||||
Range(uncheckedBounds: (index, index + count)))
|
||||
}
|
||||
|
||||
/// Resize the gap in the given subrange to have the specified count.
|
||||
/// This operation moves elements following the gap to be at their expected
|
||||
/// new location, and it adjusts the container's count to reflect the change.
|
||||
///
|
||||
/// - Returns: A buffer pointer addressing the newly opened gap, to be
|
||||
/// initialized by the caller.
|
||||
@inlinable
|
||||
@unsafe
|
||||
internal mutating func _resizeGap(
|
||||
in subrange: Range<Int>, to newItemCount: Int
|
||||
) -> UnsafeMutableBufferPointer<Element> {
|
||||
assert(subrange.lowerBound >= 0 && subrange.upperBound <= _count)
|
||||
assert(newItemCount >= 0 && newItemCount - subrange.count <= freeCapacity)
|
||||
if newItemCount > subrange.count {
|
||||
_ = unsafe _openGap(
|
||||
at: subrange.upperBound, count: newItemCount - subrange.count)
|
||||
} else if newItemCount < subrange.count {
|
||||
_closeGap(
|
||||
at: subrange.lowerBound + newItemCount, count: subrange.count - newItemCount)
|
||||
}
|
||||
_count += newItemCount - subrange.count
|
||||
let gapRange = unsafe Range(
|
||||
uncheckedBounds: (subrange.lowerBound, subrange.lowerBound + newItemCount))
|
||||
return unsafe _storage.extracting(gapRange)
|
||||
}
|
||||
|
||||
/// Perform a range replacement up to populating the newly opened gap. This
|
||||
/// deinitializes existing elements in the specified subrange, rearranges
|
||||
/// following elements to be at their final location, and sets the container's
|
||||
@@ -452,30 +478,21 @@ extension RigidArray where Element: ~Copyable {
|
||||
///
|
||||
/// - Returns: A buffer pointer addressing the newly opened gap, to be
|
||||
/// initialized by the caller.
|
||||
@inlinable
|
||||
@available(*, deprecated) // FIXME: Obsolete, remove this
|
||||
@usableFromInline
|
||||
@unsafe
|
||||
internal mutating func _gapForReplacement(
|
||||
of subrange: Range<Int>, withNewCount newCount: Int
|
||||
of subrange: Range<Int>, newItemCount: Int
|
||||
) -> UnsafeMutableBufferPointer<Element> {
|
||||
precondition(
|
||||
subrange.lowerBound >= 0 && subrange.upperBound <= _count,
|
||||
"Index range out of bounds")
|
||||
precondition(newCount >= 0, "Cannot add a negative number of items")
|
||||
precondition(newItemCount >= 0, "Cannot add a negative number of items")
|
||||
precondition(
|
||||
newCount - subrange.count <= freeCapacity,
|
||||
newItemCount - subrange.count <= freeCapacity,
|
||||
"RigidArray capacity overflow")
|
||||
unsafe _items.extracting(subrange).deinitialize()
|
||||
if newCount > subrange.count {
|
||||
_ = unsafe _openGap(
|
||||
at: subrange.upperBound, count: newCount - subrange.count)
|
||||
} else if newCount < subrange.count {
|
||||
_closeGap(
|
||||
at: subrange.lowerBound + newCount, count: subrange.count - newCount)
|
||||
}
|
||||
_count += newCount - subrange.count
|
||||
let gapRange = unsafe Range(
|
||||
uncheckedBounds: (subrange.lowerBound, subrange.lowerBound + newCount))
|
||||
return unsafe _storage.extracting(gapRange)
|
||||
return _resizeGap(in: subrange, to: newItemCount)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -36,6 +36,37 @@ extension UniqueArray where Element: ~Copyable {
|
||||
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
extension UniqueArray where Element: ~Copyable {
|
||||
/// Append a given number of items to the end of this array by populating
|
||||
/// an output span.
|
||||
///
|
||||
/// If the array does not have sufficient capacity to hold the requested
|
||||
/// number of new elements, then this reallocates the array's storage to
|
||||
/// grow its capacity, using a geometric growth rate.
|
||||
///
|
||||
/// If the callback fails to fully populate its output span or if
|
||||
/// it throws an error, then the array keeps all items that were
|
||||
/// successfully initialized before the callback terminated the insertion.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - newItemCount: The number of items to append to the array.
|
||||
/// - initializer: A callback that gets called at most once to directly
|
||||
/// populate newly reserved storage within the array. The function
|
||||
/// is allowed to initialize fewer than `uninitializedCount` items.
|
||||
/// The array is appended however many items the callback adds to the
|
||||
/// output span before it returns (or before it throws an error).
|
||||
///
|
||||
/// - Complexity: O(`uninitializedCount`)
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func append<E: Error>(
|
||||
addingCount newItemCount: Int,
|
||||
initializingWith initializer: (inout OutputSpan<Element>) throws(E) -> Void
|
||||
) throws(E) {
|
||||
_ensureFreeCapacity(newItemCount)
|
||||
return try _storage.append(
|
||||
addingCount: newItemCount,
|
||||
initializingWith: initializer)
|
||||
}
|
||||
|
||||
/// Append a given number of items to the end of this array by populating
|
||||
/// an output span.
|
||||
///
|
||||
@@ -45,20 +76,25 @@ extension UniqueArray where Element: ~Copyable {
|
||||
///
|
||||
/// - Parameters
|
||||
/// - count: The number of items to append to the array.
|
||||
/// - body: A callback that gets called at most once to directly
|
||||
/// - initializer: A callback that gets called exactly once to directly
|
||||
/// populate newly reserved storage within the array. The function
|
||||
/// is allowed to initialize fewer than `count` items. The array is
|
||||
/// appended however many items the callback adds to the output span
|
||||
/// before it returns (or before it throws an error).
|
||||
///
|
||||
/// - Complexity: O(`count`)
|
||||
@available(*, deprecated, renamed: "append(addingCount:initializingWith:)")
|
||||
@_alwaysEmitIntoClient
|
||||
@inline(__always)
|
||||
public mutating func append<E: Error, Result: ~Copyable>(
|
||||
count: Int,
|
||||
initializingWith body: (inout OutputSpan<Element>) throws(E) -> Result
|
||||
initializingWith initializer: (inout OutputSpan<Element>) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
_ensureFreeCapacity(count)
|
||||
return try _storage.append(count: count, initializingWith: body)
|
||||
var result: Result? = nil
|
||||
try append(addingCount: count) { target throws(E) in
|
||||
result = try initializer(&target)
|
||||
}
|
||||
return result.take()!
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -51,12 +51,23 @@ extension UniqueArray where Element: ~Copyable {
|
||||
/// position, using a callback to directly initialize array storage by
|
||||
/// populating an output span.
|
||||
///
|
||||
/// All existing elements at or following the specified position are moved to
|
||||
/// make room for the new items.
|
||||
/// Existing elements in the array's storage are moved towards the back as
|
||||
/// needed to make room for the new items.
|
||||
///
|
||||
/// If the array does not have sufficient capacity to hold the new elements,
|
||||
/// then this reallocates storage to extend its capacity, using a geometric
|
||||
/// growth rate.
|
||||
/// then this operation reallocates storage to extend its capacity, using a
|
||||
/// geometric growth rate.
|
||||
///
|
||||
/// var buffer = UniqueArray<Int>()
|
||||
/// buffer.append([-999, 999])
|
||||
/// var i = 0
|
||||
/// buffer.insert(capacity: 3, at: 1) { target in
|
||||
/// while !target.isFull {
|
||||
/// target.append(i)
|
||||
/// i += 1
|
||||
/// }
|
||||
/// }
|
||||
/// // `buffer` now contains [-999, 0, 1, 2, 999]
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - count: The number of items to insert into the array.
|
||||
@@ -68,15 +79,53 @@ extension UniqueArray where Element: ~Copyable {
|
||||
/// supplied count, and it must fully populate it before returning.
|
||||
///
|
||||
/// - Complexity: O(`self.count` + `count`)
|
||||
@_alwaysEmitIntoClient
|
||||
@inline(__always)
|
||||
public mutating func insert<E: Error>(
|
||||
addingCount newItemCount: Int,
|
||||
at index: Int,
|
||||
initializingWith initializer: (inout OutputSpan<Element>) throws(E) -> Void
|
||||
) throws(E) {
|
||||
_ensureFreeCapacity(newItemCount)
|
||||
try _storage.insert(
|
||||
addingCount: newItemCount,
|
||||
at: index,
|
||||
initializingWith: initializer)
|
||||
}
|
||||
|
||||
/// Inserts a given number of new items into this array at the specified
|
||||
/// position, using a callback to directly initialize array storage by
|
||||
/// populating an output span.
|
||||
///
|
||||
/// All existing elements at or following the specified position are moved to
|
||||
/// make room for the new items.
|
||||
///
|
||||
/// If the array does not have sufficient capacity to hold the new elements,
|
||||
/// then this reallocates storage to extend its capacity, using a geometric
|
||||
/// growth rate.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - count: The number of items to insert into the array.
|
||||
/// - index: The position at which to insert the new items.
|
||||
/// `index` must be a valid index in the array.
|
||||
/// - body: A callback that gets called exactly once to directly
|
||||
/// populate newly reserved storage within the array. The function
|
||||
/// is called with an empty output span of capacity matching the
|
||||
/// supplied count, and it must fully populate it before returning.
|
||||
///
|
||||
/// - Complexity: O(`self.count` + `count`)
|
||||
@available(*, deprecated, renamed: "insert(addingCount:at:initializingWith:)")
|
||||
@inlinable
|
||||
public mutating func insert<Result: ~Copyable>(
|
||||
count: Int,
|
||||
at index: Int,
|
||||
initializingWith body: (inout OutputSpan<Element>) -> Result
|
||||
) -> Result {
|
||||
// FIXME: This does not allow `body` to throw, to prevent having to move the tail twice. Is that okay?
|
||||
_ensureFreeCapacity(count)
|
||||
return _storage.insert(count: count, at: index, initializingWith: body)
|
||||
var result: Result? = nil
|
||||
self.insert(addingCount: count, at: index) { target in
|
||||
result = body(&target)
|
||||
}
|
||||
return result!
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -157,7 +157,7 @@ extension UniqueArray where Element: ~Copyable {
|
||||
/// passing an input span to the given function to consume them in place.
|
||||
///
|
||||
/// - Parameter bounds: The subrange of items to consume from this array.
|
||||
/// - Parameter body: A function taking an input span of the removed items,
|
||||
/// - Parameter consumer: A function taking an input span of the removed items,
|
||||
/// allowing them to be consumed straight out of the array's storage.
|
||||
/// The function is not required to consume all items in the span;
|
||||
/// however, the span's remaining items will still be removed from
|
||||
@@ -167,9 +167,9 @@ extension UniqueArray where Element: ~Copyable {
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func consumeSubrange<E: Error, Result: ~Copyable>(
|
||||
_ bounds: Range<Int>,
|
||||
consumingWith body: (inout InputSpan<Element>) throws(E) -> Result
|
||||
consumingWith consumer: (inout InputSpan<Element>) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
try _storage.consumeSubrange(bounds, consumingWith: body)
|
||||
try _storage.consumeSubrange(bounds, consumingWith: consumer)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -18,6 +18,65 @@ import ContainersPreview
|
||||
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
extension UniqueArray where Element: ~Copyable {
|
||||
/// Replaces the specified range of elements by a given count of new items,
|
||||
/// using a callback to directly initialize array storage by populating
|
||||
/// an output span.
|
||||
///
|
||||
/// The number of new items need not match the number of elements being
|
||||
/// removed.
|
||||
///
|
||||
/// This method has the same overall effect as calling
|
||||
///
|
||||
/// try array.removeSubrange(subrange)
|
||||
/// try array.insert(
|
||||
/// addingCount: newItemCount,
|
||||
/// at: subrange.lowerBound,
|
||||
/// initializingWith: initializer)
|
||||
///
|
||||
/// Except it performs faster (by a constant factor), by avoiding moving
|
||||
/// some items in the array twice.
|
||||
///
|
||||
/// If the array does not have sufficient capacity to perform the replacement,
|
||||
/// then this reallocates storage to extend its capacity, using a geometric
|
||||
/// growth rate.
|
||||
///
|
||||
/// If the callback fails to fully populate its output span or if
|
||||
/// it throws an error, then the array keeps all items that were
|
||||
/// successfully initialized before the callback terminated the prepend.
|
||||
///
|
||||
/// Partial insertions create a gap in array storage that needs to be
|
||||
/// closed by moving newly inserted items to their correct positions given
|
||||
/// the adjusted count. This adds some overhead compared to adding exactly as
|
||||
/// many items as promised.
|
||||
///
|
||||
/// - Parameters
|
||||
/// - subrange: The subrange of the array to replace. The bounds of
|
||||
/// the range must be valid indices in the array.
|
||||
/// - newItemCount: the maximum number of items to replace the old subrange.
|
||||
/// - initializer: A callback that gets called at most once to directly
|
||||
/// populate newly reserved storage within the array. The function
|
||||
/// is always called with an empty output span.
|
||||
///
|
||||
/// - Complexity: O(`self.count` + `newItemCount`) in addition to the complexity
|
||||
/// of the callback invocations.
|
||||
@inlinable
|
||||
public mutating func replaceSubrange<E: Error>(
|
||||
_ subrange: Range<Int>,
|
||||
addingCount newItemCount: Int,
|
||||
initializingWith initializer: (inout OutputSpan<Element>) throws(E) -> Void
|
||||
) throws(E) -> Void {
|
||||
precondition(
|
||||
subrange.lowerBound >= 0 && subrange.upperBound <= self.count,
|
||||
"Index range out of bounds")
|
||||
precondition(newItemCount >= 0, "Cannot add a negative number of items")
|
||||
// FIXME: Avoid moving the subsequent elements twice on resize.
|
||||
_ensureFreeCapacity(newItemCount - subrange.count)
|
||||
try _storage._uncheckedReplaceSubrange(
|
||||
subrange,
|
||||
addingCount: newItemCount,
|
||||
initializingWith: initializer)
|
||||
}
|
||||
|
||||
/// Replaces the specified range of elements by a given count of new items,
|
||||
/// using a callback to directly initialize array storage by populating
|
||||
/// an output span.
|
||||
@@ -43,28 +102,99 @@ extension UniqueArray where Element: ~Copyable {
|
||||
/// - subrange: The subrange of the array to replace. The bounds of
|
||||
/// the range must be valid indices in the array.
|
||||
/// - newCount: the number of items to replace the old subrange.
|
||||
/// - body: A callback that gets called at most once to directly
|
||||
/// - body: A callback that gets called exactly once to directly
|
||||
/// populate newly reserved storage within the array. The function
|
||||
/// is called with an empty output span of capacity `newCount`,
|
||||
/// and it must fully populate it before returning.
|
||||
///
|
||||
/// - Complexity: O(`self.count` + `newCount`)
|
||||
@available(*, deprecated, renamed: "replaceSubrange(_:addingCapacity:initializingWith:)")
|
||||
@inlinable
|
||||
public mutating func replaceSubrange<Result: ~Copyable>(
|
||||
_ subrange: Range<Int>,
|
||||
newCount: Int,
|
||||
initializingWith body: (inout OutputSpan<Element>) -> Result
|
||||
) -> Result {
|
||||
// FIXME: Should we allow throwing (and a partially filled output span)?
|
||||
// FIXME: Should we have a version of this with two closures, to allow custom-consuming the old items?
|
||||
// replaceSubrange(5..<10, newCount: 3, consumingWith: {...}, initializingWith: {...})
|
||||
// FIXME: Avoid moving the subsequent elements twice.
|
||||
_ensureFreeCapacity(newCount - subrange.count)
|
||||
return _storage.replaceSubrange(
|
||||
subrange, newCount: newCount, initializingWith: body)
|
||||
var result: Result? = nil
|
||||
self.replaceSubrange(subrange, addingCount: newCount) { target in
|
||||
result = body(&target)
|
||||
}
|
||||
return result!
|
||||
}
|
||||
}
|
||||
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
extension UniqueArray where Element: ~Copyable {
|
||||
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
|
||||
/// Replaces the specified range of elements by a given count of new items,
|
||||
/// using callbacks to consume old items, and to then insert new ones.
|
||||
///
|
||||
/// The number of new items need not match the number of elements being
|
||||
/// removed.
|
||||
///
|
||||
/// This method has the same overall effect as calling
|
||||
///
|
||||
/// try array.consume(subrange, consumingWith: consumer)
|
||||
/// try array.insert(
|
||||
/// addingCount: newItemCount,
|
||||
/// at: subrange.lowerBound,
|
||||
/// initializingWith: initializer)
|
||||
///
|
||||
/// Except it performs faster (by a constant factor), by avoiding moving
|
||||
/// some items in the deque twice.
|
||||
///
|
||||
/// If the array does not have sufficient capacity to perform the replacement,
|
||||
/// then this reallocates storage to extend its capacity, using a geometric
|
||||
/// growth rate.
|
||||
///
|
||||
/// The `consumer` callback is not required to fully depopulate its input
|
||||
/// span. Any items the callback leaves in the span still get removed and
|
||||
/// discarded from the array before insertions begin.
|
||||
///
|
||||
/// The `initializer` callback is not required to fully populate its
|
||||
/// output span, and it is allowed to throw an error. In such cases, the
|
||||
/// deque keeps all items that were successfully initialized before the
|
||||
/// callback terminated.
|
||||
///
|
||||
/// Partial insertions create a gap in array storage that needs to be
|
||||
/// closed by moving newly inserted items to their correct positions given
|
||||
/// the adjusted count. This adds some overhead compared to adding exactly as
|
||||
/// many items as promised.
|
||||
///
|
||||
/// - Parameters
|
||||
/// - subrange: The subrange of the deque to replace. The bounds of
|
||||
/// the range must be valid indices in the deque.
|
||||
/// - newItemCount: the maximum number of items to replace the old subrange.
|
||||
/// - consumer: A callback that gets called at most once to consume
|
||||
/// the elements to be removed directly from the deque's storage. The
|
||||
/// function is always called with a non-empty input span.
|
||||
/// - initializer: A callback that gets called at most once to directly
|
||||
/// populate newly reserved storage within the deque. The function
|
||||
/// is always called with an empty output span.
|
||||
///
|
||||
/// - Complexity: O(`self.count` + `newItemCount`) in addition to the
|
||||
/// complexity of the callback invocations.
|
||||
@inlinable
|
||||
public mutating func replaceSubrange<E: Error>(
|
||||
_ subrange: Range<Int>,
|
||||
addingCount newItemCount: Int,
|
||||
consumingWith consumer: (inout InputSpan<Element>) -> Void,
|
||||
initializingWith initializer: (inout OutputSpan<Element>) throws(E) -> Void
|
||||
) throws(E) -> Void {
|
||||
precondition(
|
||||
subrange.lowerBound >= 0 && subrange.upperBound <= self.count,
|
||||
"Index range out of bounds")
|
||||
precondition(newItemCount >= 0, "Cannot add a negative number of items")
|
||||
_ensureFreeCapacity(newItemCount - subrange.count)
|
||||
try _storage._uncheckedReplaceSubrange(
|
||||
subrange,
|
||||
addingCount: newItemCount,
|
||||
consumingWith: consumer,
|
||||
initializingWith: initializer)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
extension UniqueArray where Element: ~Copyable {
|
||||
/// Replaces the specified range of elements by moving the elements of a
|
||||
|
||||
Reference in new issue
Block a user