From d1d757e42542ebb192e243085cc012219aaeb0d7 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 8 Jan 2026 17:24:16 -0800 Subject: [PATCH] [RigidDeque] Implement replacement operations --- .../RigidArray+Replacements.swift | 95 +-- .../BorrowIteratorProtocol.swift | 25 + .../RigidDeque/RigidDeque+Insertions.swift | 43 +- .../RigidDeque/RigidDeque+Replacements.swift | 574 ++++++++++++++++++ .../RigidDeque/RigidDeque+Testing.swift | 8 +- Sources/DequeModule/_UnsafeDequeHandle.swift | 115 +++- .../UnsafeBufferPointer+Extras.swift | 47 ++ 7 files changed, 811 insertions(+), 96 deletions(-) create mode 100644 Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift diff --git a/Sources/BasicContainers/RigidArray+Replacements.swift b/Sources/BasicContainers/RigidArray+Replacements.swift index 654cca7d..30ba8e3e 100644 --- a/Sources/BasicContainers/RigidArray+Replacements.swift +++ b/Sources/BasicContainers/RigidArray+Replacements.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 @@ -32,11 +32,11 @@ extension RigidArray where Element: ~Copyable { /// /// If you pass a zero-length range as the `subrange` parameter, then /// this method is equivalent to calling - /// `insert(count: newCount, initializingWith: body)`. + /// `insert(count: newCount, at: subrange.lowerbound, initializingWith: body)`. /// /// Likewise, if you pass a zero for `newCount`, then this method /// removes the elements in the given subrange without any replacement. - /// Calling `removeSubrange(subrange)` is preferred in this case. + /// This case is more directly expressed by `removeSubrange(subrange)`. /// /// - Parameters /// - subrange: The subrange of the array to replace. The bounds of @@ -83,13 +83,13 @@ extension RigidArray where Element: ~Copyable { /// elements, then this method triggers a runtime error. /// /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(moving:at:)` method instead is preferred in this case. + /// inserts the elements of `newElements` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(moving:at:)`. /// /// Likewise, if you pass a zero-length buffer as the `newElements` /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. /// /// - Parameters /// - subrange: The subrange of the array to replace. The bounds of @@ -123,13 +123,13 @@ extension RigidArray where Element: ~Copyable { /// elements, then this method triggers a runtime error. /// /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(moving:at:)` method instead is preferred in this case. + /// inserts the elements of `newElements` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(moving:at:)`. /// /// Likewise, if you pass a zero-length buffer as the `newElements` /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. /// /// - Parameters /// - subrange: The subrange of the array to replace. The bounds of @@ -162,13 +162,13 @@ extension RigidArray where Element: ~Copyable { /// elements, then this method triggers a runtime error. /// /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(moving:at:)` method instead is preferred in this case. + /// inserts the elements of `newElements` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(moving:at:)`. /// /// Likewise, if you pass a zero-length buffer as the `newElements` /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. /// /// - Parameters /// - subrange: The subrange of the array to replace. The bounds of @@ -202,13 +202,13 @@ extension RigidArray where Element: ~Copyable { /// elements, then this method triggers a runtime error. /// /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. + /// inserts the elements of `newElements` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(moving:at:)`. /// /// Likewise, if you pass a zero-length buffer as the `newElements` /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. /// /// - Parameters /// - subrange: The subrange of the array to replace. The bounds of @@ -221,6 +221,7 @@ extension RigidArray where Element: ~Copyable { _ subrange: Range, moving newElements: inout RigidArray, ) { + // FIXME: Remove this in favor of a generic algorithm over consumable containers unsafe newElements._unsafeEdit { buffer, count in let source = buffer._extracting(first: count) unsafe self.replaceSubrange(subrange, moving: source) @@ -244,13 +245,13 @@ extension RigidArray where Element: ~Copyable { /// elements, then this method triggers a runtime error. /// /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. + /// inserts the elements of `newElements` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(consuming:at:)`. /// /// Likewise, if you pass a zero-length buffer as the `newElements` /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. /// /// - Parameters /// - subrange: The subrange of the array to replace. The bounds of @@ -283,13 +284,13 @@ extension RigidArray { /// elements, then this method triggers a runtime error. /// /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. + /// inserts the elements of `newElements` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(copying:at:)`. /// /// Likewise, if you pass a zero-length buffer as the `newElements` /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. /// /// - Parameters: /// - subrange: The subrange of the array to replace. The bounds of @@ -321,13 +322,13 @@ extension RigidArray { /// elements, then this method triggers a runtime error. /// /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. + /// inserts the elements of `newElements` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(copying:at:)`. /// /// Likewise, if you pass a zero-length buffer as the `newElements` /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. /// /// - Parameters: /// - subrange: The subrange of the array to replace. The bounds of @@ -357,13 +358,13 @@ extension RigidArray { /// elements, then this method triggers a runtime error. /// /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. + /// inserts the elements of `newElements` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(copying:at:)`. /// /// Likewise, if you pass a zero-length span as the `newElements` /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. /// /// - Parameters: /// - subrange: The subrange of the array to replace. The bounds of @@ -441,13 +442,13 @@ extension RigidArray { /// elements, then this method triggers a runtime error. /// /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. + /// inserts the elements of `newElements` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(copying:at:)`. /// /// Likewise, if you pass a zero-length container as the `newElements` /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. /// /// - Parameters: /// - subrange: The subrange of the array to replace. The bounds of @@ -480,13 +481,13 @@ extension RigidArray { /// elements, then this method triggers a runtime error. /// /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. + /// inserts the elements of `newElements` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(copying:at:)`. /// /// Likewise, if you pass a zero-length collection as the `newElements` /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. /// /// - Parameters: /// - subrange: The subrange of the array to replace. The bounds of @@ -517,13 +518,13 @@ extension RigidArray { /// elements, then this method triggers a runtime error. /// /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. + /// inserts the elements of `newElements` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(copying:at:)`. /// /// Likewise, if you pass a zero-length container as the `newElements` /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. /// /// - Parameters: /// - subrange: The subrange of the array to replace. The bounds of diff --git a/Sources/ContainersPreview/BorrowIteratorProtocol.swift b/Sources/ContainersPreview/BorrowIteratorProtocol.swift index f3452512..ffac1f98 100644 --- a/Sources/ContainersPreview/BorrowIteratorProtocol.swift +++ b/Sources/ContainersPreview/BorrowIteratorProtocol.swift @@ -10,6 +10,11 @@ //===----------------------------------------------------------------------===// #if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +#endif + @available(SwiftStdlib 5.0, *) public protocol BorrowIteratorProtocol: ~Copyable, ~Escapable { associatedtype Element: ~Copyable /*& ~Escapable*/ @@ -90,6 +95,26 @@ extension BorrowIteratorProtocol where Self: ~Copyable & ~Escapable { } } +@available(SwiftStdlib 5.0, *) +extension BorrowIteratorProtocol +where Self: ~Copyable & ~Escapable, Element: Copyable +{ + @_lifetime(copy self) + @_lifetime(self: copy self) + @_transparent + public mutating func copyContents(into target: inout OutputSpan) { + target.withUnsafeMutableBufferPointer { dst, dstCount in + var tail = dst._extracting(droppingFirst: dstCount) + while !tail.isEmpty { + let src = nextSpan(maximumCount: tail.count) + if src.isEmpty { break } + tail._initializeAndDropPrefix(copying: src) + dstCount += src.count + } + } + } +} + @available(SwiftStdlib 5.0, *) extension Span: BorrowIteratorProtocol where Element: ~Copyable { @_lifetime(copy self) diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift index 2149398d..3ab94810 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift @@ -49,7 +49,7 @@ extension RigidDeque where Element: ~Copyable { 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. + /// populating a series of output spans. /// /// Existing elements in the deque's storage are moved as needed to make room /// for the new items. (The direction of the move depends on the location of @@ -75,8 +75,8 @@ extension RigidDeque where Element: ~Copyable { /// 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 + /// (Partial insertions create a gap in ring buffer 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.) /// @@ -85,7 +85,8 @@ extension RigidDeque where Element: ~Copyable { /// - 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. + /// populate newly reserved storage within the deque. The function + /// is always called with an empty output span. /// /// - Complexity: O(`self.count` + `count`) @inlinable @@ -127,6 +128,7 @@ extension RigidDeque where Element: ~Copyable { moving items: UnsafeMutableBufferPointer, at index: Int ) { + guard !items.isEmpty else { return } var remainder = items insert(count: items.count, at: index) { target in target.withUnsafeMutableBufferPointer { buffer, count in @@ -296,12 +298,16 @@ extension RigidDeque /* where Element: Copyable */ { copying newElements: UnsafeBufferPointer, at index: Int ) { guard newElements.count > 0 else { return } - self.insert(count: newElements.count, at: index) { target in + var remainder = newElements + insert(count: remainder.count, at: index) { target in target.withUnsafeMutableBufferPointer { buffer, count in - buffer.initializeAll(fromContentsOf: newElements) - count = newElements.count + buffer.initializeAll( + fromContentsOf: remainder._extracting(first: buffer.count)) + remainder = remainder._extracting(droppingFirst: buffer.count) + count = buffer.count } } + assert(remainder.isEmpty) } /// Copies the elements of a fully initialized buffer pointer into this @@ -370,15 +376,14 @@ extension RigidDeque /* where Element: Copyable */ { copying items: borrowing C, newCount: Int ) { + let expectedCount = self.count - subrange.count + newCount + var it = newElements.startBorrowIteration() 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 - } + it.copyContents(into: &target) } + precondition( + it.nextSpan().isEmpty && count == expectedCount, + "Broken Container: count doesn't match contents") } #endif @@ -388,8 +393,8 @@ extension RigidDeque /* where Element: Copyable */ { copying items: some Collection, newCount: Int ) { - let done: Void? = items.withContiguousStorageIfAvailable { buffer in - self.insert(copying: buffer, at: index) + let done: Void? = items.withContiguousStorageIfAvailable { src in + self.insert(copying: src, at: index) } if done != nil { return } @@ -397,8 +402,10 @@ extension RigidDeque /* where Element: Copyable */ { 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) + while !target.isFull { + target.append(items[i]) + items.formIndex(after: &i) + } } precondition(i == items.endIndex, "Broken Collection: count doesn't match contents") diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift new file mode 100644 index 00000000..b5352b54 --- /dev/null +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift @@ -0,0 +1,574 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 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 +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: ~Copyable { + /// Replaces the specified range of elements by a given count of new items, + /// using a callback to directly initialize deque storage by populating + /// a series of output spans. + /// + /// This method has the effect of removing the specified range of elements + /// from the deque and inserting room for the new elements starting at the + /// same location. The number of new elements need not match the number + /// of elements being removed. + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, then + /// this method is equivalent to calling + /// `insert(count: newCount, at: subrange.lowerBound, initializingWith: body)`. + /// + /// Likewise, if you pass a zero for `newCount`, then this method + /// removes the elements in the given subrange without any replacement. + /// This case is more directly expressed by `removeSubrange(subrange)`. + /// + /// 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 insertions create a gap in ring buffer 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. + /// - newCount: the number of items to replace the old subrange. + /// - body: A callback that gets called at most twice to directly + /// populate newly reserved storage within the deque. The function + /// is always called with an empty output span. + /// + /// - Complexity: O(`self.count` + `newCount`) + @inlinable + public mutating func replaceSubrange( + _ subrange: Range, + newCount: Int, + initializingWith body: (inout OutputSpan) throws(E) -> Void + ) throws(E) -> Void { + // FIXME: Should we have a version of this with two closures, to allow custom-consuming the old items? + precondition( + subrange.lowerBound >= 0 && subrange.upperBound <= count, + "Subrange out of bounds") + precondition(newCount >= 0, "Negative count") + precondition( + count - subrange.count + newCount <= capacity, + "RigidDeque capacity overflow") + try _handle.uncheckedReplaceSubrange( + subrange, + newCount: newCount, + initializingWith: body) + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: ~Copyable { + /// Replaces the specified range of elements by moving the elements of a + /// fully initialized buffer into their place. On return, the buffer is left + /// in an uninitialized state. + /// + /// This method has the effect of removing the specified range of elements + /// from the deque and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(moving:at:)`. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - newElements: A fully initialized buffer whose contents to move into + /// the deque. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + moving newElements: UnsafeMutableBufferPointer, + ) { + var remainder = newElements + replaceSubrange(subrange, newCount: remainder.count) { 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 + /// Replaces the specified range of elements by moving the contents of an + /// input span into their place. On return, the span is left empty. + /// + /// This method has the effect of removing the specified range of elements + /// from the deque and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(moving:at:)`. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - items: An input span whose contents are to be moved into the deque. + /// + /// - Complexity: O(`self.count` + `items.count`) + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + moving items: inout InputSpan + ) { + items.withUnsafeMutableBufferPointer { buffer, count in + let source = buffer._extracting(last: count) + unsafe self.replaceSubrange(subrange, moving: source) + count = 0 + } + } +#endif + + /// Replaces the specified range of elements by moving the contents of an + /// output span into their place. On return, the span is left empty. + /// + /// This method has the effect of removing the specified range of elements + /// from the deque and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(moving:at:)`. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the deque. + /// - items: An output span whose contents are to be moved into the deque. + /// + /// - Complexity: O(`self.count` + `items.count`) + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + moving items: inout OutputSpan + ) { + items.withUnsafeMutableBufferPointer { buffer, count in + let source = buffer._extracting(first: count) + unsafe self.replaceSubrange(subrange, moving: source) + count = 0 + } + } + + /// Replaces the specified range of elements by moving the elements of a + /// another deque into their place. On return, the source deque + /// becomes empty, but it is not destroyed, and it preserves its original + /// storage capacity. + /// + /// This method has the effect of removing the specified range of elements + /// from the deque and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(moving:at:)`. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - newElements: A deque whose contents to move into `self`. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + moving newElements: inout RigidDeque, + ) { + // FIXME: Remove this in favor of a generic algorithm over consumable containers + replaceSubrange(subrange, newCount: newElements.count) { target in + target.withUnsafeMutableBufferPointer { dst, dstCount in + var remainder = dst + newElements._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 + /// Replaces the specified range of elements by moving the elements of a + /// given deque into their place, consuming it in the process. + /// + /// This method has the effect of removing the specified range of elements + /// from the deque and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(consuming:at:)`. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - newElements: A deque whose contents to move into `self`. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + consuming newElements: consuming RigidDeque, + ) { + // FIXME: Remove this in favor of a generic algorithm over consumable containers + replaceSubrange(subrange, moving: &newElements) + } +#endif +} + +@available(SwiftStdlib 5.0, *) +extension RigidDeque /* where Element: Copyable */ { + /// Replaces the specified subrange of elements by copying the elements of + /// the given buffer pointer, which must be fully initialized. + /// + /// This method has the effect of removing the specified range of elements + /// from the deque and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(copying:at:)`. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - newElements: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @inlinable + public mutating func replaceSubrange( + _ subrange: Range, + copying newElements: UnsafeBufferPointer + ) { + var remainder = newElements + replaceSubrange(subrange, newCount: remainder.count) { target in + target.withUnsafeMutableBufferPointer { dst, dstCount in + dst.initializeAll(fromContentsOf: remainder._extracting(first: dst.count)) + dstCount += dst.count + remainder = remainder._extracting(droppingFirst: dst.count) + } + } + assert(remainder.isEmpty) + } + + /// Replaces the specified subrange of elements by copying the elements of + /// the given buffer pointer, which must be fully initialized. + /// + /// This method has the effect of removing the specified range of elements + /// from the deque and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(copying:at:)`. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - newElements: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @inlinable + public mutating func replaceSubrange( + _ subrange: Range, + copying newElements: UnsafeMutableBufferPointer + ) { + unsafe self.replaceSubrange( + subrange, + copying: UnsafeBufferPointer(newElements)) + } + + /// Replaces the specified subrange of elements by copying the elements of + /// the given span. + /// + /// This method has the effect of removing the specified range of elements + /// from the deque and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(copying:at:)`. + /// + /// Likewise, if you pass a zero-length span as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - newElements: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @inlinable + public mutating func replaceSubrange( + _ subrange: Range, + copying newElements: Span + ) { + unsafe newElements.withUnsafeBufferPointer { buffer in + unsafe self.replaceSubrange(subrange, copying: buffer) + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @inlinable + internal mutating func _replaceSubrange< + C: Container & ~Copyable & ~Escapable + >( + _ subrange: Range, + copyingContainer newElements: borrowing C, + newCount: Int + ) { + + let expectedCount = self.count - subrange.count + newCount + var it = newElements.startBorrowIteration() + self.replaceSubrange(subrange, newCount: newCount) { target in + it.copyContents(into: &target) + } + precondition( + it.nextSpan().isEmpty && count == expectedCount, + "Broken Container: count doesn't match contents") + } +#endif + + @inlinable + internal mutating func _replaceSubrange( + _ subrange: Range, + copyingCollection newElements: __owned some Collection, + newCount: Int + ) { + let done: Void? = newElements.withContiguousStorageIfAvailable { src in + precondition( + src.count == newCount, + "Broken Collection: count doesn't match contents") + self.replaceSubrange(subrange, copying: src) + } + if done != nil { return } + + var i = newElements.startIndex + self.replaceSubrange(subrange, newCount: newCount) { target in + while !target.isFull { + target.append(newElements[i]) + newElements.formIndex(after: &i) + } + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Replaces the specified subrange of elements by copying the elements of + /// the given container. + /// + /// This method has the effect of removing the specified range of elements + /// from the deque and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(copying:at:)`. + /// + /// Likewise, if you pass a zero-length container as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @inlinable + @inline(__always) + public mutating func replaceSubrange< + C: Container & ~Copyable & ~Escapable + >( + _ subrange: Range, + copying newElements: borrowing C + ) { + _replaceSubrange( + subrange, copyingContainer: newElements, newCount: newElements.count) + } +#endif + + /// Replaces the specified subrange of elements by copying the elements of + /// the given collection. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(copying:at:)`. + /// + /// Likewise, if you pass a zero-length collection as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - newElements: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @inlinable + @inline(__always) + public mutating func replaceSubrange( + _ subrange: Range, + copying newElements: __owned some Collection + ) { + _replaceSubrange( + subrange, copyingCollection: newElements, newCount: newElements.count) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Replaces the specified subrange of elements by copying the elements of + /// the given container. + /// + /// This method has the effect of removing the specified range of elements + /// from the deque and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(copying:at:)`. + /// + /// Likewise, if you pass a zero-length container as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: The new elements to copy into the collection. + /// + /// - Complexity: O(*n* + *m*), where *n* is count of this deque and + /// *m* is the count of `newElements`. + @inlinable + @inline(__always) + public mutating func replaceSubrange< + C: Container & Collection + >( + _ subrange: Range, + copying newElements: C + ) { + _replaceSubrange( + subrange, copyingContainer: newElements, newCount: newElements.count) + } +#endif +} + +#endif diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Testing.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Testing.swift index a1706ab0..a4db2f82 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Testing.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Testing.swift @@ -25,7 +25,7 @@ extension RigidDeque where Element: ~Copyable { /// (Or would hold it after an insertion in case the deque is currently /// empty.) /// - /// This property isn't intended to be used outside of `Deque`'s own test + /// This property isn't intended to be used outside of `DequeModule`'s own test /// target. @_spi(Testing) public var _startSlot: Int { @@ -36,8 +36,10 @@ extension RigidDeque where Element: ~Copyable { @available(SwiftStdlib 5.0, *) extension RigidDeque { /// Constructs a deque instance of the specified contents and layout. Exposed - /// as public to allow exhaustive input/output tests for `Deque`'s members. - /// This isn't intended to be used outside of `Deque`'s own test target. + /// as public to allow exhaustive input/output tests for `RigidDeque` members. + /// + /// This initializer isn't intended to be used outside of `DequeModule`'s + /// own test target. @_spi(Testing) public init( _capacity capacity: Int, diff --git a/Sources/DequeModule/_UnsafeDequeHandle.swift b/Sources/DequeModule/_UnsafeDequeHandle.swift index 01461c98..f4975721 100644 --- a/Sources/DequeModule/_UnsafeDequeHandle.swift +++ b/Sources/DequeModule/_UnsafeDequeHandle.swift @@ -734,27 +734,6 @@ 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, *) @@ -887,6 +866,18 @@ extension _UnsafeDequeHandle where Element: ~Copyable { return (slot(source, offsetBy: count), slot(target, offsetBy: count)) } + @_alwaysEmitIntoClient + @_transparent + func isLeftLeaning(_ offset: Int) -> Bool { + offset < count - offset + } + + @_alwaysEmitIntoClient + @_transparent + func isLeftLeaning(_ subrange: Range) -> Bool { + subrange.lowerBound < count - subrange.upperBound + } + /// Slide elements around so that there is a gap of uninitialized slots of /// size `gapSize` starting at `offset`, and return a (potentially wrapped) /// buffer holding the newly inserted slots. @@ -1197,6 +1188,30 @@ extension _UnsafeDequeHandle where Element: ~Copyable { } } +@available(SwiftStdlib 5.0, *) +extension _UnsafeDequeHandle where Element: ~Copyable { + @_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) + } + } +} + extension _UnsafeDequeHandle { /// Insert all elements from `newElements` into this deque, starting at /// `offset`. @@ -1235,7 +1250,7 @@ extension _UnsafeDequeHandle where Element: ~Copyable { closeGap(offsets: Range(uncheckedBounds: (offset, offset + 1))) return result } - + @_alwaysEmitIntoClient @_transparent internal mutating func uncheckedRemoveFirst() -> Element { @@ -1245,7 +1260,7 @@ extension _UnsafeDequeHandle where Element: ~Copyable { count -= 1 return result } - + @_alwaysEmitIntoClient @_transparent internal mutating func uncheckedRemoveLast() -> Element { @@ -1255,7 +1270,7 @@ extension _UnsafeDequeHandle where Element: ~Copyable { count -= 1 return result } - + @_alwaysEmitIntoClient @_transparent internal mutating func uncheckedRemoveFirst(_ n: Int) { @@ -1266,7 +1281,7 @@ extension _UnsafeDequeHandle where Element: ~Copyable { startSlot = slot(startSlot, offsetBy: n) count -= n } - + @_alwaysEmitIntoClient @_transparent internal mutating func uncheckedRemoveLast(_ n: Int) { @@ -1276,7 +1291,7 @@ extension _UnsafeDequeHandle where Element: ~Copyable { target.deinitialize() count -= n } - + /// Remove all elements stored in this instance, deinitializing their storage. /// /// This method does not ensure that the storage buffer is uniquely @@ -1290,7 +1305,7 @@ extension _UnsafeDequeHandle where Element: ~Copyable { count = 0 startSlot = .zero } - + /// Remove all elements in `bounds`, deinitializing their storage and sliding /// remaining elements to close the resulting gap. /// @@ -1300,9 +1315,53 @@ extension _UnsafeDequeHandle where Element: ~Copyable { @_transparent internal mutating func uncheckedRemove(offsets bounds: Range) { assert(bounds.lowerBound >= 0 && bounds.upperBound <= self.count) - + // Deinitialize elements in `bounds`. mutableSegments(forOffsets: bounds).deinitialize() closeGap(offsets: bounds) } } + +// MARK: Replacement + +@available(SwiftStdlib 5.0, *) +extension _UnsafeDequeHandle where Element: ~Copyable { + @_alwaysEmitIntoClient + internal mutating func uncheckedReplaceSubrange( + _ subrange: Range, + newCount: Int, + initializingWith body: (inout OutputSpan) throws(E) -> Void + ) throws(E) -> Void { + assert( + subrange.lowerBound >= 0 && subrange.upperBound <= count, + "Subrange out of bounds") + assert(newCount >= 0, "Negative count") + let delta = newCount - subrange.count + assert(count + delta <= capacity, "RigidDeque capacity overflow") + self.mutableSegments(forOffsets: subrange).deinitialize() + // Note: we're careful to open/close the gap in a direction that does not + // lead to trying to move slots we deinitialized above. + let left = isLeftLeaning(subrange) + if delta > 0 { + _ = self.openGap( + ofSize: delta, + atOffset: (left ? subrange.lowerBound : subrange.upperBound)) + } else { + self.closeGap( + offsets: (left ? subrange.prefix(-delta) : subrange.suffix(-delta))) + } + let newRange = Range(uncheckedBounds: (subrange.lowerBound, newCount)) + let gap = self.mutableSegments(forOffsets: newRange) + + var c = 0 + defer { + if c < newCount { + closeGap(offsets: newRange.dropFirst(c)) + } + } + try gap.first._initialize(initializedCount: &c, initializingWith: body) + if c == gap.first.count, let second = gap.second { + try second._initialize(initializedCount: &c, initializingWith: body) + } + } +} diff --git a/Sources/InternalCollectionsUtilities/UnsafeBufferPointer+Extras.swift b/Sources/InternalCollectionsUtilities/UnsafeBufferPointer+Extras.swift index ba05e636..f1d1aa1a 100644 --- a/Sources/InternalCollectionsUtilities/UnsafeBufferPointer+Extras.swift +++ b/Sources/InternalCollectionsUtilities/UnsafeBufferPointer+Extras.swift @@ -57,6 +57,29 @@ extension UnsafeBufferPointer where Element: ~Copyable { 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. /// @@ -79,4 +102,28 @@ extension UnsafeBufferPointer 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) + } + }