From 8a73c1be08069b9aba3712bc38e2539c4d2aa47a Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 17 Apr 2025 00:41:05 -0700 Subject: [PATCH] Revive DequeModule Lots to do still, but the thing passes tests now --- Sources/DequeModule/Deque+Collection.swift | 44 ++------- Sources/DequeModule/Deque+Container.swift | 37 ++------ Sources/DequeModule/Deque+Equatable.swift | 2 +- Sources/DequeModule/Deque+Testing.swift | 2 +- Sources/DequeModule/Deque.swift | 20 ++-- Sources/DequeModule/DynamicDeque.swift | 36 +++---- Sources/DequeModule/RigidDeque.swift | 94 ++++++++----------- Sources/DequeModule/_UnsafeDequeHandle.swift | 25 +++-- .../DequeModule/_UnsafeDequeSegments.swift | 6 +- 9 files changed, 102 insertions(+), 164 deletions(-) diff --git a/Sources/DequeModule/Deque+Collection.swift b/Sources/DequeModule/Deque+Collection.swift index 0e308724..f8198a5d 100644 --- a/Sources/DequeModule/Deque+Collection.swift +++ b/Sources/DequeModule/Deque+Collection.swift @@ -11,10 +11,9 @@ #if !COLLECTIONS_SINGLE_MODULE import InternalCollectionsUtilities +import Future #endif -import Span - extension Deque { // Implementation note: we could also use the default `IndexingIterator` here. // This custom implementation performs direct storage access to eliminate any @@ -183,7 +182,7 @@ extension Deque: RandomAccessCollection { /// - Complexity: O(1) @inlinable @inline(__always) - public var count: Int { _storage.read { $0.count } } + public var count: Int { _storage.value.count } /// The position of the first element in a nonempty deque. /// @@ -360,39 +359,14 @@ extension Deque: RandomAccessCollection { /// writing is O(`count`). @inlinable public subscript(index: Int) -> Element { - get { - return _storage.read { $0[index] } + @lifetime(borrow self) + unsafeAddress { + _storage.value.borrowElement(at: index)._pointer } - set { - _storage.update { $0[index] = newValue } - } - @inline(__always) // https://github.com/apple/swift-collections/issues/164 - _modify { - precondition(index >= 0 && index < count, "Index out of bounds") - var (slot, value) = _prepareForModify(at: index) - defer { - _finalizeModify(slot, value) - } - yield &value - } - } - - @inlinable - internal mutating func _prepareForModify(at index: Int) -> (_Slot, Element) { - _ensureUnique() - // We technically aren't supposed to escape storage pointers out of a - // managed buffer, so we escape a `(slot, value)` pair instead, leaving - // the corresponding slot temporarily uninitialized. - return _update { handle in - let slot = handle.slot(forOffset: index) - return (slot, handle.mutablePtr(at: slot).move()) - } - } - - @inlinable - internal mutating func _finalizeModify(_ slot: _Slot, _ value: __owned Element) { - _update { handle in - handle.mutablePtr(at: slot).initialize(to: value) + @lifetime(&self) + unsafeMutableAddress { + _ensureUnique() + return _storage.value.mutateElement(at: index)._pointer } } diff --git a/Sources/DequeModule/Deque+Container.swift b/Sources/DequeModule/Deque+Container.swift index 0b714a24..e28e265b 100644 --- a/Sources/DequeModule/Deque+Container.swift +++ b/Sources/DequeModule/Deque+Container.swift @@ -10,39 +10,18 @@ //===----------------------------------------------------------------------===// #if !COLLECTIONS_SINGLE_MODULE -import Span +import Future #endif extension Deque: RandomAccessContainer { - public typealias BorrowingIterator = RigidDeque.BorrowingIterator - - @inlinable - public func startBorrowingIteration() -> BorrowingIterator { - self.startBorrowingIteration(from: 0) + @lifetime(borrow self) + public func borrowElement(at index: Int) -> Borrow { + _storage.value.borrowElement(at: index) } - @inlinable - public func startBorrowingIteration(from start: Int) -> BorrowingIterator { - // FIXME: This is unacceptably unsafe. We want to access `_storage.value` - // FIXME: as if it was a structural part of `self`, but there is no way - // FIXME: to express this in Swift. - BorrowingIterator( - _unsafeSegments: _storage.value._handle.segments(), - startOffset: start, - owner: self) - } - - @inlinable - public func index(at position: borrowing BorrowingIterator) -> Int { - precondition(_read { $0.segments().isIdentical(to: position._segments) }) - return position._offset - } - - @inlinable - public func formIndex( - _ index: inout Index, offsetBy distance: inout Index.Stride, limitedBy limit: Index - ) { - // Note: Range checks are deferred until element access. - index.advance(by: &distance, limitedBy: limit) + @available(SwiftCompatibilitySpan 5.0, *) + @lifetime(borrow self) + public func span(following index: inout Int, maximumCount: Int) -> Span { + _storage.value.span(following: &index, maximumCount: maximumCount) } } diff --git a/Sources/DequeModule/Deque+Equatable.swift b/Sources/DequeModule/Deque+Equatable.swift index 0c64445e..eb0f4709 100644 --- a/Sources/DequeModule/Deque+Equatable.swift +++ b/Sources/DequeModule/Deque+Equatable.swift @@ -9,7 +9,7 @@ // //===----------------------------------------------------------------------===// -import Span +import Future extension Deque: Equatable where Element: Equatable { /// Returns a Boolean value indicating whether two values are equal. Two diff --git a/Sources/DequeModule/Deque+Testing.swift b/Sources/DequeModule/Deque+Testing.swift index ce4dbea6..0d8a1d7f 100644 --- a/Sources/DequeModule/Deque+Testing.swift +++ b/Sources/DequeModule/Deque+Testing.swift @@ -49,7 +49,7 @@ extension Deque { /// target. @_spi(Testing) public var _unstableStartSlot: Int { - _storage.read { $0._handle.startSlot.position } + _storage.value._handle.startSlot.position } /// Constructs a deque instance of the specified contents and layout. Exposed diff --git a/Sources/DequeModule/Deque.swift b/Sources/DequeModule/Deque.swift index c52bbc0a..f3b8fd1d 100644 --- a/Sources/DequeModule/Deque.swift +++ b/Sources/DequeModule/Deque.swift @@ -9,7 +9,7 @@ // //===----------------------------------------------------------------------===// -import Span +import Future /// A collection implementing a double-ended queue. `Deque` (pronounced "deck") /// implements an ordered random-access collection that supports efficient @@ -117,9 +117,7 @@ extension Deque { internal func _read( _ body: (borrowing _UnsafeHandle) throws(E) -> R ) throws(E) -> R { - try _storage.read { rigid throws(E) in - try body(rigid._handle) - } + return try body(_storage.value._handle) } @inlinable @@ -128,9 +126,9 @@ extension Deque { _ body: (inout _UnsafeHandle) throws(E) -> R ) throws(E) -> R { _ensureUnique() - return try _storage.update { v throws(E) in - try body(&v._handle) - } + var rigid = _storage.mutate() + defer { extendLifetime(rigid) } + return try body(&rigid[]._handle) } } @@ -156,18 +154,18 @@ extension Deque { @inlinable @inline(never) internal func _makeUniqueCopy() -> Self { - Deque(_storage: _storage.read { $0._copy() }) + Deque(_storage: _storage.value._copy()) } @inlinable @inline(never) internal func _makeUniqueCopy(capacity: Int) -> Self { - Deque(_storage: _storage.read { $0._copy(capacity: capacity) }) + Deque(_storage: _storage.value._copy(capacity: capacity)) } @inlinable internal var _capacity: Int { - _storage.read { $0.capacity } + _storage.value.capacity } @usableFromInline @@ -221,7 +219,7 @@ extension Deque { let c = _growCapacity(to: minimumCapacity, linearly: linearGrowth) if isUnique { - self._storage.update { $0.resize(to: c) } + self._storage.value.resize(to: c) } else { self = self._makeUniqueCopy(capacity: c) } diff --git a/Sources/DequeModule/DynamicDeque.swift b/Sources/DequeModule/DynamicDeque.swift index 58eb4303..ab361388 100644 --- a/Sources/DequeModule/DynamicDeque.swift +++ b/Sources/DequeModule/DynamicDeque.swift @@ -11,7 +11,7 @@ #if !COLLECTIONS_SINGLE_MODULE import InternalCollectionsUtilities -import Span +import Future #endif @frozen @@ -33,17 +33,16 @@ public struct DynamicDeque: ~Copyable { extension DynamicDeque: @unchecked Sendable where Element: Sendable & ~Copyable {} extension DynamicDeque: RandomAccessContainer where Element: ~Copyable { - public typealias BorrowingIterator = RigidDeque.BorrowingIterator + @available(SwiftCompatibilitySpan 5.0, *) + @lifetime(borrow self) + public func span(following index: inout Int, maximumCount: Int) -> Span { + _storage.span(following: &index, maximumCount: maximumCount) + } +} + +extension DynamicDeque where Element: ~Copyable { public typealias Index = Int - public func startBorrowingIteration() -> BorrowingIterator { - _storage.startBorrowingIteration() - } - - public func startBorrowingIteration(from start: Int) -> BorrowingIterator { - _storage.startBorrowingIteration(from: start) - } - @inlinable public var isEmpty: Bool { _storage.isEmpty } @@ -56,20 +55,9 @@ extension DynamicDeque: RandomAccessContainer where Element: ~Copyable { @inlinable public var endIndex: Int { _storage.endIndex } - @inlinable - public subscript(position: Int) -> Element { - @inline(__always) - _read { - yield _storage[position] - } - @inline(__always) - _modify { - yield &_storage[position] - } - } - - public func index(at position: borrowing BorrowingIterator) -> Int { - _storage.index(at: position) + @lifetime(borrow self) + public func borrowElement(at index: Int) -> Future.Borrow { + _storage.borrowElement(at: index) } } diff --git a/Sources/DequeModule/RigidDeque.swift b/Sources/DequeModule/RigidDeque.swift index cdf3f3f4..83a0b5d5 100644 --- a/Sources/DequeModule/RigidDeque.swift +++ b/Sources/DequeModule/RigidDeque.swift @@ -11,7 +11,7 @@ #if !COLLECTIONS_SINGLE_MODULE import InternalCollectionsUtilities -import Span +import Future #endif @frozen @@ -61,64 +61,43 @@ extension RigidDeque where Element: ~Copyable { } } -public struct _DequeBorrowingIterator: BorrowingIteratorProtocol, ~Escapable { - @usableFromInline - internal typealias _UnsafeHandle = _UnsafeDequeHandle - - @usableFromInline - internal let _segments: _UnsafeDequeSegments - - @usableFromInline - internal var _offset: Int - +@available(SwiftCompatibilitySpan 5.0, *) +extension RigidDeque where Element: ~Copyable { @inlinable - internal init( - _unsafeSegments segments: _UnsafeDequeSegments, - startOffset: Int, - owner: borrowing T - ) { - self._segments = segments - self._offset = startOffset + @lifetime(borrow self) + internal func _span(over slots: Range<_DequeSlot>) -> Span { + let span = Span(_unsafeElements: _handle.buffer(for: slots)) + return _overrideLifetime(span, borrowing: self) } @inlinable - internal init(_for handle: borrowing _UnsafeHandle, startOffset: Int) { - self.init(_unsafeSegments: handle.segments(), startOffset: startOffset, owner: handle) - } - - @inlinable - public mutating func nextChunk( - maximumCount: Int - ) -> dependsOn(scoped self) Span { - precondition(maximumCount > 0) - if _offset < _segments.first.count { - let d = Swift.min(maximumCount, _segments.first.count - _offset) - let slice = _segments.first.extracting(_offset ..< _offset + d) - _offset += d - return Span(_unsafeElements: slice) - } - guard let second = _segments.second else { - return Span(_unsafeElements: UnsafeBufferPointer._empty) - } - let o = _offset - _segments.first.count - let d = Swift.min(maximumCount, second.count - o) - let slice = second.extracting(o ..< o + d) - _offset += d - return Span(_unsafeElements: slice) + @lifetime(&self) + internal mutating func _mutableSpan(over slots: Range<_DequeSlot>) -> MutableSpan { + let span = MutableSpan(_unsafeElements: _handle.mutableBuffer(for: slots)) + return _overrideLifetime(span, mutating: &self) } } -extension RigidDeque: RandomAccessContainer where Element: ~Copyable { - public typealias BorrowingIterator = _DequeBorrowingIterator - - public func startBorrowingIteration() -> BorrowingIterator { - _handle.startBorrowingIteration() +@available(SwiftCompatibilitySpan 5.0, *) +extension RigidDeque: RandomAccessContainer, MutableContainer where Element: ~Copyable { + @inlinable + @lifetime(borrow self) + public func span(following index: inout Int, maximumCount: Int) -> Span { + let slots = _handle.slotRange(following: &index, maximumCount: maximumCount) + return _span(over: slots) } - public func startBorrowingIteration(from start: Int) -> BorrowingIterator { - _handle.startBorrowingIteration(from: start) + @inlinable + @lifetime(&self) + public mutating func mutableSpan( + following index: inout Int, maximumCount: Int + ) -> MutableSpan { + let slots = _handle.slotRange(following: &index, maximumCount: maximumCount) + return _mutableSpan(over: slots) } +} +extension RigidDeque where Element: ~Copyable { public typealias Index = Int @inlinable @@ -133,6 +112,20 @@ extension RigidDeque: RandomAccessContainer where Element: ~Copyable { @inlinable public var endIndex: Int { _handle.count } + @lifetime(borrow self) + public func borrowElement(at index: Int) -> Borrow { + precondition(index >= 0 && index < count, "Index out of bounds") + let slot = _handle.slot(forOffset: index) + return Borrow(unsafeAddress: _handle.ptr(at: slot), borrowing: self) + } + + @lifetime(&self) + public mutating func mutateElement(at index: Int) -> Inout { + precondition(index >= 0 && index < count, "Index out of bounds") + let slot = _handle.slot(forOffset: index) + return Inout(unsafeAddress: _handle.mutablePtr(at: slot), mutating: &self) + } + @inlinable public subscript(position: Int) -> Element { @inline(__always) @@ -144,11 +137,6 @@ extension RigidDeque: RandomAccessContainer where Element: ~Copyable { yield &_handle[offset: position] } } - - public func index(at position: borrowing BorrowingIterator) -> Int { - precondition(_handle.segments().isIdentical(to: position._segments)) - return position._offset - } } extension RigidDeque where Element: ~Copyable { diff --git a/Sources/DequeModule/_UnsafeDequeHandle.swift b/Sources/DequeModule/_UnsafeDequeHandle.swift index 25d5b1bf..b6e2d2b1 100644 --- a/Sources/DequeModule/_UnsafeDequeHandle.swift +++ b/Sources/DequeModule/_UnsafeDequeHandle.swift @@ -386,14 +386,25 @@ extension _UnsafeDequeHandle where Element: ~Copyable { extension _UnsafeDequeHandle where Element: ~Copyable { @inlinable - internal func startBorrowingIteration() -> _DequeBorrowingIterator { - .init(_for: self, startOffset: 0) - } + internal func slotRange(following offset: inout Int, maximumCount: Int) -> Range { + precondition(offset >= 0 && offset <= count, "Invalid index") + precondition(maximumCount > 0, "maximumCount must be positive") + guard _buffer.baseAddress != nil else { + return Range(uncheckedBounds: (Slot.zero, Slot.zero)) + } + let wrapOffset = Swift.min(capacity - startSlot.position, count) - @inlinable - internal func startBorrowingIteration(from start: Int) -> _DequeBorrowingIterator { - precondition(start >= 0 && start <= count) - return .init(_for: self, startOffset: start) + if offset < wrapOffset { + let endOffset = offset + Swift.min(wrapOffset - offset, maximumCount) + defer { offset += endOffset - offset } + return Range( + uncheckedBounds: (startSlot.advanced(by: offset), startSlot.advanced(by: endOffset))) + } + let endOffset = offset + Swift.min(count - offset, maximumCount) + let lowerSlot = Slot.zero.advanced(by: offset - wrapOffset) + let upperSlot = lowerSlot.advanced(by: endOffset - wrapOffset) + defer { offset += endOffset - offset } + return Range(uncheckedBounds: (lower: lowerSlot, upper: upperSlot)) } } diff --git a/Sources/DequeModule/_UnsafeDequeSegments.swift b/Sources/DequeModule/_UnsafeDequeSegments.swift index 49d5592f..4e5b8eb6 100644 --- a/Sources/DequeModule/_UnsafeDequeSegments.swift +++ b/Sources/DequeModule/_UnsafeDequeSegments.swift @@ -11,7 +11,7 @@ #if !COLLECTIONS_SINGLE_MODULE import InternalCollectionsUtilities -import Span +import Future #endif @frozen @@ -58,10 +58,10 @@ internal struct _UnsafeDequeSegments { @inlinable internal func isIdentical(to other: Self) -> Bool { - guard self.first === other.first else { return false } + guard self.first.isIdentical(to: other.first) else { return false } switch (self.second, other.second) { case (nil, nil): return true - case let (a?, b?): return a === b + case let (a?, b?): return a.isIdentical(to: b) default: return false } }