diff --git a/Package@swift-6.0.swift b/Package@swift-6.0.swift index e04dc722..30c7fde3 100644 --- a/Package@swift-6.0.swift +++ b/Package@swift-6.0.swift @@ -273,7 +273,7 @@ let targets: [CustomTarget] = [ .target( kind: .exported, name: "DequeModule", - dependencies: ["InternalCollectionsUtilities"], + dependencies: ["ContainersPreview", "InternalCollectionsUtilities"], exclude: ["CMakeLists.txt"]), .target( kind: .test, diff --git a/Sources/BasicContainers/RigidArray+Insertions.swift b/Sources/BasicContainers/RigidArray+Insertions.swift index cc47c1f5..65fee312 100644 --- a/Sources/BasicContainers/RigidArray+Insertions.swift +++ b/Sources/BasicContainers/RigidArray+Insertions.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors +// Copyright (c) 2024 - 2026 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information @@ -206,6 +206,7 @@ extension RigidArray where Element: ~Copyable { moving items: inout RigidArray, at index: Int ) { + // FIXME: Remove this in favor of a generic algorithm over consumable containers insert(count: items.count, at: index) { target in target.withUnsafeMutableBufferPointer { dst, dstCount in items.edit { source in @@ -233,8 +234,7 @@ extension RigidArray where Element: ~Copyable { /// elements, then this method triggers a runtime error. /// /// - Parameters - /// - items: A fully initialized buffer whose contents to move into - /// the array. + /// - items: The array whose contents to move into `self`. /// - index: The position at which to insert the new items. /// `index` must be a valid index in the array. /// diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Append.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Append.swift index 83f5e7d6..4bde551c 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Append.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Append.swift @@ -56,7 +56,7 @@ extension RigidDeque where Element: ~Copyable { @available(SwiftStdlib 5.0, *) extension RigidDeque where Element: ~Copyable { /// Efficiently append a given number of items to the back of this deque by - /// populating a series of storage regions through successive calls of the + /// populating a series of storage regions through repeated calls of the /// specified callback function. /// /// If the deque does not have sufficient capacity to store the new items, @@ -76,7 +76,7 @@ extension RigidDeque where Element: ~Copyable { /// The newly appended items are not guaranteed to form a single contiguous /// storage region. Therefore, the supplied callback may be invoked multiple /// times to initialize each successive chunk of storage. However, invocations - /// cease when the callback fails to fully populate its output span or when if + /// cease when the callback fails to fully populate its output span or if /// it throws an error. In such cases, the deque keeps all items that were /// successfully initialized before the callback terminated the append. /// @@ -94,10 +94,7 @@ extension RigidDeque where Element: ~Copyable { /// - Parameters /// - count: The number of items to append to the deque. /// - body: A callback that gets called at most twice to directly - /// populate newly reserved storage within the deque. The function - /// is allowed to initialize fewer than `count` items. The deque is - /// appended however many items the callback adds to the output span - /// before it returns (or before it throws an error). + /// populate newly reserved storage within the deque. /// /// - Complexity: O(`count`) @_alwaysEmitIntoClient @@ -193,7 +190,7 @@ extension RigidDeque where Element: ~Copyable { ) { // FIXME: Remove this in favor of a generic algorithm over range-replaceable containers precondition(items.count <= freeCapacity, "RigidDeque capacity overflow") - items._handle.unsafeConsumeElements { source in + items._handle.unsafeConsumeAll { source in self._handle.uncheckedAppend(moving: source) } } diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift index 018806ed..4a74639b 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2025 Apple Inc. and the Swift project authors +// Copyright (c) 2025 - 2026 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information @@ -18,14 +18,473 @@ import ContainersPreview @available(SwiftStdlib 5.0, *) extension RigidDeque where Element: ~Copyable { + /// Inserts a new element into the deque at the specified position. + /// + /// If the deque does not have sufficient capacity to hold any more elements, + /// then this triggers a runtime error. + /// + /// The new element is inserted before the element currently at the specified + /// index. If you pass the deque's `endIndex` as the `index` parameter, then + /// the new element is appended to the container. + /// + /// Existing elements preceding or succeeding the specified position are + /// moved to make room for the new item. + /// + /// - Parameter item: The new element to insert into the array. + /// - Parameter index: The position at which to insert the new element. + /// `index` must be a valid index in the array. + /// + /// - Complexity: O(`self.count`) @_alwaysEmitIntoClient @_transparent public mutating func insert(_ newElement: consuming Element, at index: Int) { - precondition(!isFull, "RigidDeque is full") - precondition(index >= 0 && index <= count, - "Can't insert element at invalid index") + precondition(!isFull, "RigidDeque capacity overflow") + precondition(index >= 0 && index <= count, "Index out of bounds") _handle.uncheckedInsert(newElement, at: index) } } +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: ~Copyable { + /// Inserts a given number of new items into this deque at the specified + /// position, using a callback to directly initialize deque storage by + /// populating an output span. + /// + /// Existing elements preceding or succeeding the specified position are + /// moved to make room for the new items. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// var buffer = RigidDeque(capacity: 20) + /// buffer.append([-999, 999]) + /// var i = 0 + /// buffer.insert(count: 3, at: 1) { target in + /// while !target.isFull { + /// target.append(i) + /// i += 1 + /// } + /// } + /// // `buffer` now contains [-999, 0, 1, 2, 999] + /// + /// The newly prepended items are not guaranteed to form a single contiguous + /// storage region. Therefore, the supplied callback may be invoked multiple + /// times to initialize each successive chunk of storage. However, invocations + /// cease if the callback fails to fully populate its output span or if + /// it throws an error. In such cases, the deque keeps all items that were + /// successfully initialized before the callback terminated the prepend. + /// (Partial prepends create a gap in ring buffer storage that needs to be + /// closed by moving newly prepended items to their correct positions given + /// the adjusted count. This adds some overhead compared to adding exactly as + /// many items as promised.) + /// + /// - Parameters: + /// - count: The number of items to insert into the deque. + /// - index: The position at which to insert the new items. + /// `index` must be a valid index in the deque. + /// - body: A callback that gets called at most twice to directly + /// populate newly reserved storage within the deque. + /// + /// - Complexity: O(`self.count` + `count`) + @inlinable + public mutating func insert( + count: Int, + at index: Int, + initializingWith body: (inout OutputSpan) throws(E) -> Void + ) throws(E) { + // 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, "RigidDeque capacity overflow") + try _handle.uncheckedInsert(count: count, at: index, initializingWith: body) + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: ~Copyable { + /// Inserts the elements of a fully initialized buffer by moving them into + /// this deque, starting at the specified position. After this operation, + /// the supplied buffer becomes uninitialized. + /// + /// Existing elements preceding or succeeding the specified position are + /// moved to make room for the new items. + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// - Parameters + /// - items: A fully initialized buffer whose contents to move into + /// the deque. + /// - index: The position at which to insert the new items. + /// `index` must be a valid index in the array. + /// + /// - Complexity: O(`self.count` + `items.count`) + @_alwaysEmitIntoClient + public mutating func insert( + moving items: UnsafeMutableBufferPointer, + at index: Int + ) { + var remainder = items + insert(count: items.count, at: index) { target in + target.withUnsafeMutableBufferPointer { buffer, count in + buffer.moveInitializeAll( + fromContentsOf: remainder._extracting(first: buffer.count)) + remainder = remainder._extracting(droppingFirst: buffer.count) + count = buffer.count + } + } + assert(remainder.isEmpty) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Moves the elements of an input span into this deque, + /// starting at the specified position, and leaving the span empty. + /// + /// Existing elements preceding or succeeding the specified position are + /// moved to make room for the new items. + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// - Parameters + /// - items: An input span whose contents to move into + /// the deque. + /// - index: The position at which to insert the new items. + /// `index` must be a valid index in the deque. + /// + /// - Complexity: O(`self.count` + `items.count`) + @_alwaysEmitIntoClient + public mutating func insert( + moving items: inout InputSpan, + at index: Int + ) { + items.withUnsafeMutableBufferPointer { buffer, count in + let source = buffer._extracting(last: count) + unsafe self.insert(moving: source, at: index) + count = 0 + } + } +#endif + + /// Moves the elements of an output span into this deque, + /// starting at the specified position, and leaving the span empty. + /// + /// Existing elements preceding or succeeding the specified position are + /// moved to make room for the new items. + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// - Parameters + /// - items: An output span whose contents to move into + /// the deque. + /// - index: The position at which to insert the new items. + /// `index` must be a valid index in the deque. + /// + /// - Complexity: O(`self.count` + `items.count`) + @_alwaysEmitIntoClient + public mutating func insert( + moving items: inout OutputSpan, + at index: Int + ) { + items.withUnsafeMutableBufferPointer { buffer, count in + let source = buffer._extracting(first: count) + unsafe self.insert(moving: source, at: index) + count = 0 + } + } + + /// Inserts the elements of a given deque into the given position in this + /// deque by moving them between the containers. On return, the input deque + /// becomes empty, but it is not destroyed, and it preserves its original + /// storage capacity. + /// + /// Existing elements preceding or succeeding the specified position are + /// moved to make room for the new items. + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// - Parameters + /// - items: A deque whose contents to move into `self`. + /// - index: The position at which to insert the new items. + /// `index` must be a valid index in the deque. + /// + /// - Complexity: O(`count` + `items.count`) + @_alwaysEmitIntoClient + public mutating func insert( + moving items: inout RigidDeque, + at index: Int + ) { + // FIXME: Remove this in favor of a generic algorithm over consumable containers + insert(count: items.count, at: index) { target in + target.withUnsafeMutableBufferPointer { dst, dstCount in + var remainder = dst + items._handle.unsafeConsumePrefix(upTo: remainder.count) { src in + let c = remainder._moveInitializePrefix(from: src) + dstCount += c + remainder = remainder._extracting(last: c) + } + assert(remainder.isEmpty) + } + } + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: ~Copyable { +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Inserts the elements of a given deque into the given position in this + /// deque by consuming the source container. + /// + /// Existing elements preceding or succeeding the specified position are + /// moved to make room for the new items. + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// - Parameters + /// - items: The deque whose contents to move into `self`. + /// - index: The position at which to insert the new items. + /// `index` must be a valid index in the deque. + /// + /// - Complexity: O(`count` + `items.count`) + @_alwaysEmitIntoClient + public mutating func insert( + consuming items: consuming RigidDeque, + at index: Int + ) { + // FIXME: Remove this in favor of a generic algorithm over consumable containers + var items = items + self.insert(moving: &items, at: index) + } +#endif +} + +@available(SwiftStdlib 5.0, *) +extension RigidDeque /* where Element: Copyable */ { + /// Copies the elements of a fully initialized buffer pointer into this + /// deque at the specified position. + /// + /// The new elements are inserted before the element currently at the + /// specified index. If you pass the deque’s `endIndex` as the `index` + /// parameter, then the new elements are appended to the end of the array. + /// + /// Existing elements preceding or succeeding the specified position are + /// moved to make room for the new items. + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// - Parameters + /// - newElements: The new elements to insert into the deque. The buffer + /// must be fully initialized. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of `self`. + /// + /// - Complexity: O(`count` + `newElements.count`) + @inlinable + public mutating func insert( + copying newElements: UnsafeBufferPointer, at index: Int + ) { + guard newElements.count > 0 else { return } + self.insert(count: newElements.count, at: index) { target in + target.withUnsafeMutableBufferPointer { buffer, count in + buffer.initializeAll(fromContentsOf: newElements) + count = newElements.count + } + } + } + + /// Copies the elements of a fully initialized buffer pointer into this + /// deque at the specified position. + /// + /// The new elements are inserted before the element currently at the + /// specified index. If you pass the deque’s `endIndex` as the `index` + /// parameter, then the new elements are appended to the end of the deque. + /// + /// Existing elements preceding or succeeding the specified position are + /// moved to make room for the new items. + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// - Parameters + /// - newElements: The new elements to insert into the deque. The buffer + /// must be fully initialized. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of `self`. + /// + /// - Complexity: O(`count` + `newElements.count`) + @inlinable + public mutating func insert( + copying newElements: UnsafeMutableBufferPointer, + at index: Int + ) { + unsafe self.insert(copying: UnsafeBufferPointer(newElements), at: index) + } + + /// Copies the elements of a span into this deque at the specified position. + /// + /// The new elements are inserted before the element currently at the + /// specified index. If you pass the deque’s `endIndex` as the `index` + /// parameter, then the new elements are appended to the end of the deque. + /// + /// Existing elements preceding or succeeding the specified position are + /// moved to make room for the new items. + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// - Parameters + /// - newElements: The new elements to insert into the deque. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of the deque. + /// + /// - Complexity: O(`count` + `newElements.count`) + @inlinable + public mutating func insert( + copying newElements: Span, at index: Int + ) { + unsafe newElements.withUnsafeBufferPointer { + unsafe self.insert(copying: $0, at: index) + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @inlinable + internal mutating func _insertContainer< + C: Container & ~Copyable & ~Escapable + >( + at index: Int, + copying items: borrowing C, + newCount: Int + ) { + insert(count: newCount, at: index) { target in + target.withUnsafeMutableBufferPointer { buffer, count in + let copied = items._copyContents(intoPrefixOf: buffer) + precondition( + copied == newCount, + "Broken Container: count doesn't match contents") + count = newCount + } + } + } +#endif + + @inlinable + internal mutating func _insertCollection( + at index: Int, + copying items: some Collection, + newCount: Int + ) { + let done: Void? = items.withContiguousStorageIfAvailable { buffer in + self.insert(copying: buffer, at: index) + } + if done != nil { return } + + precondition(index >= 0 && index <= count, "Index out of bounds") + precondition(newCount <= freeCapacity, "RigidDeque capacity overflow") + var i = items.startIndex + self._handle.uncheckedInsert(count: newCount, at: index) { target in + target.append(items[i]) + items.formIndex(after: &i) + } + precondition(i == items.endIndex, + "Broken Collection: count doesn't match contents") + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Copies the elements of a container into this deque at the specified + /// position. + /// + /// The new elements are inserted before the element currently at the + /// specified index. If you pass the deque’s `endIndex` as the `index` + /// parameter, then the new elements are appended to the end of the deque. + /// + /// Existing elements preceding or succeeding the specified position are + /// moved to make room for the new items. + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// - Parameters + /// - newElements: The new elements to insert into the deque. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of the deque. + /// + /// - Complexity: O(`self.count` + `newElements.count`). + @_alwaysEmitIntoClient + @inline(__always) + public mutating func insert< + C: Container & ~Copyable & ~Escapable + >( + copying newElements: borrowing C, at index: Int + ) { + _insertContainer( + at: index, copying: newElements, newCount: newElements.count) + } +#endif + + /// Copies the elements of a collection into this deque at the specified + /// position. + /// + /// The new elements are inserted before the element currently at the + /// specified index. If you pass the deque’s `endIndex` as the `index` + /// parameter, then the new elements are appended to the end of the deque. + /// + /// Existing elements preceding or succeeding the specified position are + /// moved to make room for the new items. + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// - Parameters + /// - newElements: The new elements to insert into the deque. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of the deque. + /// + /// - Complexity: O(`count` + `newElements.count`) + @inlinable + @inline(__always) + public mutating func insert( + copying newElements: some Collection, at index: Int + ) { + _insertCollection( + at: index, copying: newElements, newCount: newElements.count) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Copies the elements of a container into this deque at the specified + /// position. + /// + /// The new elements are inserted before the element currently at the + /// specified index. If you pass the deque's `endIndex` as the `index` + /// parameter, then the new elements are appended to the end of the deque. + /// + /// Existing elements preceding or succeeding the specified position are + /// moved to make room for the new items. + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// - Parameters + /// - newElements: The new elements to insert into the deque. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of the deque. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @_alwaysEmitIntoClient + @inline(__always) + public mutating func insert< + C: Container & Collection + >( + copying newElements: borrowing C, at index: Int + ) { + _insertContainer( + at: index, copying: newElements, newCount: newElements.count) + } +#endif +} + #endif diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift index d439edf4..129116b3 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift @@ -56,7 +56,7 @@ extension RigidDeque where Element: ~Copyable { @available(SwiftStdlib 5.0, *) extension RigidDeque where Element: ~Copyable { /// Efficiently prepend a given number of items to the front of this deque by - /// populating a series of storage regions through successive calls of the + /// populating a series of storage regions through repeated calls of the /// specified callback function. /// /// If the deque does not have sufficient capacity to store the new items, @@ -76,7 +76,7 @@ extension RigidDeque where Element: ~Copyable { /// The newly prepended items are not guaranteed to form a single contiguous /// storage region. Therefore, the supplied callback may be invoked multiple /// times to initialize each successive chunk of storage. However, invocations - /// cease when the callback fails to fully populate its output span or when if + /// cease if the callback fails to fully populate its output span or if /// it throws an error. In such cases, the deque keeps all items that were /// successfully initialized before the callback terminated the prepend. /// (Partial prepends create a gap in ring buffer storage that needs to be @@ -98,10 +98,7 @@ extension RigidDeque where Element: ~Copyable { /// - Parameters /// - count: The number of items to append to the deque. /// - body: A callback that gets called at most twice to directly - /// populate newly reserved storage within the deque. The function - /// is allowed to initialize fewer than `count` items. The deque is - /// appended however many items the callback adds to the output span - /// before it returns (or before it throws an error). + /// populate newly reserved storage within the deque. /// /// - Complexity: O(`count`) @_alwaysEmitIntoClient @@ -198,7 +195,7 @@ extension RigidDeque where Element: ~Copyable { ) { // FIXME: Remove this in favor of a generic algorithm over range-replaceable containers precondition(items.count <= freeCapacity, "RigidDeque capacity overflow") - items._handle.unsafeConsumeElements { source in + items._handle.unsafeConsumeAll { source in self._handle.uncheckedAppend(moving: source) } } diff --git a/Sources/DequeModule/_UnsafeDequeHandle.swift b/Sources/DequeModule/_UnsafeDequeHandle.swift index c304ecb2..01461c98 100644 --- a/Sources/DequeModule/_UnsafeDequeHandle.swift +++ b/Sources/DequeModule/_UnsafeDequeHandle.swift @@ -16,6 +16,7 @@ import ContainersPreview @frozen @usableFromInline +@unsafe internal struct _UnsafeDequeHandle: ~Copyable { @usableFromInline internal typealias Slot = _DequeSlot @@ -527,7 +528,7 @@ extension _UnsafeDequeHandle { extension _UnsafeDequeHandle where Element: ~Copyable { @_alwaysEmitIntoClient @_transparent - internal mutating func unsafeConsumeElements( + internal mutating func unsafeConsumeAll( with body: (UnsafeMutableBufferPointer) -> Void ) { let segments = mutableSegments() @@ -537,6 +538,22 @@ extension _UnsafeDequeHandle where Element: ~Copyable { } self.count = 0 } + + @_alwaysEmitIntoClient + @_transparent + internal mutating func unsafeConsumePrefix( + upTo offset: Int, + with body: (UnsafeMutableBufferPointer) -> Void + ) { + assert(offset >= 0 && offset <= count) + let segments = mutableSegments(forOffsets: Range(uncheckedBounds: (0, offset))) + body(segments.first) + if let second = segments.second { + body(second) + } + self.startSlot = self.slot(forOffset: offset) + self.count &-= offset + } } // MARK: Appending and prepending @@ -616,7 +633,7 @@ extension _UnsafeDequeHandle where Element: ~Copyable { @available(SwiftStdlib 5.0, *) extension _UnsafeDequeHandle where Element: ~Copyable { /// Append a given number of items to the end of this deque by populating - /// a series of storage regions through successive calls of the specified + /// a series of storage regions through repeated calls of the specified /// callback function. /// /// This unchecked routine does not verify that the deque has sufficient @@ -655,7 +672,7 @@ extension _UnsafeDequeHandle where Element: ~Copyable { } /// Prepend a given number of items to the end of this deque by populating - /// a series of storage regions through successive calls of the specified + /// a series of storage regions through repeated calls of the specified /// callback function. /// /// This unchecked routine does not verify that the deque has sufficient @@ -695,7 +712,7 @@ extension _UnsafeDequeHandle where Element: ~Copyable { /// - body: A callback that gets called at most twice to directly /// populate newly reserved storage within the deque. The function /// is allowed to initialize fewer than `count` items. The deque is - /// appended however many items the callback adds to the output span + /// prepended however many items the callback adds to output span /// before it returns (or before it throws an error). /// /// - Complexity: O(`count`) @@ -717,6 +734,27 @@ extension _UnsafeDequeHandle where Element: ~Copyable { try second._initialize(initializedCount: &c, initializingWith: body) } } + + @_alwaysEmitIntoClient + internal mutating func uncheckedInsert( + count: Int, + at offset: Int, + initializingWith body: (inout OutputSpan) throws(E) -> Void + ) throws(E) { + guard count > 0 else { return } + let gap = self.openGap(ofSize: count, atOffset: offset) + + var c = 0 + defer { + if c < count { + closeGap(offsets: offset + c ..< offset + count) + } + } + try gap.first._initialize(initializedCount: &c, initializingWith: body) + if c == gap.first.count, let second = gap.second { + try second._initialize(initializedCount: &c, initializingWith: body) + } + } } @available(SwiftStdlib 5.0, *) diff --git a/Sources/InternalCollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift b/Sources/InternalCollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift index c47b632e..34d7f5a9 100644 --- a/Sources/InternalCollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift +++ b/Sources/InternalCollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift @@ -31,13 +31,13 @@ extension UnsafeMutableBufferPointer where Element: ~Copyable { @inline(__always) public func _extracting(unchecked bounds: Range) -> Self { assert(bounds.lowerBound >= 0 && bounds.upperBound <= count, - "Index out of range") + "Index out of range") guard let start = self.baseAddress else { return Self(start: nil, count: 0) } return Self(start: start + bounds.lowerBound, count: bounds.count) } - + /// Returns a buffer pointer containing the initial elements of this buffer, /// up to the specified maximum length. /// @@ -60,7 +60,30 @@ extension UnsafeMutableBufferPointer where Element: ~Copyable { let newCount = Swift.min(maxLength, count) return Self(start: baseAddress, count: newCount) } - + + /// Returns a buffer pointer containing all but the given number of initial + /// elements. + /// + /// If the number of elements to drop exceeds the number of elements in the + /// buffer, the result is an empty buffer. + /// + /// The returned buffer's first item is always at offset 0; unlike buffer + /// slices, extracted buffers do not share their indices with the + /// buffer from which they are extracted. + /// + /// - Parameter maxLength: The maximum number of elements to drop. + /// `maxLength` must be greater than or equal to zero. + /// - Returns: A buffer pointer with at most `maxLength` elements. + /// + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @inline(__always) + public func _extracting(droppingFirst maxLength: Int) -> Self { + precondition(maxLength >= 0, "Can't have a prefix of negative length") + let cut = Swift.min(maxLength, count) + return Self(start: baseAddress?.advanced(by: cut), count: count &- cut) + } + /// Returns a buffer pointer containing the final elements of this buffer, /// up to the given maximum length. /// @@ -83,6 +106,29 @@ extension UnsafeMutableBufferPointer where Element: ~Copyable { let newCount = Swift.min(maxLength, count) return extracting(Range(uncheckedBounds: (count - newCount, count))) } + + /// Returns a buffer pointer containing all but the given number of trailing + /// elements. + /// + /// If the number of elements to drop exceeds the number of elements in the + /// buffer, the result is an empty buffer. + /// + /// The returned buffer's first item is always at offset 0; unlike buffer + /// slices, extracted buffers do not share their indices with the + /// buffer from which they are extracted. + /// + /// - Parameter maxLength: The maximum number of elements to drop. + /// `maxLength` must be greater than or equal to zero. + /// - Returns: A buffer pointer with at most `maxLength` elements. + /// + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @inline(__always) + public func _extracting(droppingLast maxLength: Int) -> Self { + precondition(maxLength >= 0, "Can't have a prefix of negative length") + let newCount = count &- Swift.min(maxLength, count) + return Self(start: baseAddress, count: newCount) + } } extension UnsafeMutableBufferPointer where Element: ~Copyable {