From a7f6b90c991ef334c7f142035d124c8a1522937b Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 17 Jul 2026 16:57:26 -0700 Subject: [PATCH] Make the limit optional in Container.nextSpan(after:limitedBy:). Review and update default implementations - Make `nextSpan(after:limitedBy:)` the core iteration interface - Review default algorithms and update them to use it, speeding them up - Spin off `Span._nextSpan(after:maxCount)` and `Span._nextSpan(after:limitedBy:)` with copying lifetime semantics. This allows forwarding to these without having to override lifetimes. --- .../RigidArray/RigidArray+Container.swift | 14 +- .../UniqueArray/UniqueArray+Container.swift | 8 + .../Conformances/InputSpan+Container.swift | 17 +- .../Conformances/MutableSpan+Container.swift | 18 +- .../Conformances/OutputSpan+Container.swift | 15 +- .../Conformances/Span+Container.swift | 41 ++++- .../Protocols/Container/Container.swift | 158 +++++++----------- .../RigidDeque/RigidDeque+Container.swift | 18 ++ .../UniqueDeque/UniqueDeque+Container.swift | 6 + .../MinimalTypes/StaccatoContainer.swift | 29 +++- 10 files changed, 193 insertions(+), 131 deletions(-) diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Container.swift b/Sources/BasicContainers/RigidArray/RigidArray+Container.swift index ec7900f3..0d647255 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Container.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Container.swift @@ -439,11 +439,15 @@ extension RigidArray where Element: ~Copyable { public func nextSpan( after index: inout Int, maxCount: Int ) -> Span { - _checkValidIndex(index) - precondition(maxCount > 0, "maxCount must be positive") - let start = index - index = start &+ Swift.min(maxCount, _count &- start) - return _span(in: Range(uncheckedBounds: (start, index))) + self.span._nextSpan(after: &index, maxCount: maxCount) + } + + @_alwaysEmitIntoClient + @_lifetime(borrow self) + public func nextSpan( + after index: inout Index, limitedBy limit: Index? + ) -> Span { + self.span._nextSpan(after: &index, limitedBy: limit) } @inlinable diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift index 564f2e68..c674c81c 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift @@ -392,6 +392,14 @@ extension UniqueArray where Element: ~Copyable { _storage.nextSpan(after: &index, maxCount: maxCount) } + @_alwaysEmitIntoClient + @_lifetime(borrow self) + public func nextSpan( + after index: inout Int, limitedBy limit: Int? + ) -> Span { + _storage.nextSpan(after: &index, limitedBy: limit) + } + @inlinable @_lifetime(&self) public mutating func nextMutableSpan( diff --git a/Sources/ContainersPreview/Conformances/InputSpan+Container.swift b/Sources/ContainersPreview/Conformances/InputSpan+Container.swift index 0a9285bf..b9fed89a 100644 --- a/Sources/ContainersPreview/Conformances/InputSpan+Container.swift +++ b/Sources/ContainersPreview/Conformances/InputSpan+Container.swift @@ -45,7 +45,7 @@ where Element: ~Copyable @inline(__always) public var endIndex: Index { count } - @inlinable + @_alwaysEmitIntoClient @_lifetime(borrow self) public func nextSpan(after index: inout Index, maxCount: Int) -> Span { precondition(index >= 0 && index <= count, "Index out of bounds") @@ -55,7 +55,20 @@ where Element: ~Copyable return _uncheckedSpan(in: Range(uncheckedBounds: (start, start &+ c))) } - @inlinable + @_alwaysEmitIntoClient + @_lifetime(borrow self) + public func nextSpan( + after index: inout Index, limitedBy limit: Index? + ) -> Span { + precondition(index >= 0 && index <= count, "Index out of bounds") + let end = Swift.min(limit ?? count, count) + let base = capacity &- count + let range = Range(uncheckedBounds: (base &+ index, base &+ end)) + index = end + return _uncheckedSpan(in: range) + } + + @_alwaysEmitIntoClient @_lifetime(&self) public mutating func nextMutableSpan( after index: inout Index, maxCount: Int diff --git a/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift b/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift index d0d52af5..8ec1ae2b 100644 --- a/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift +++ b/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift @@ -59,18 +59,20 @@ extension MutableSpan: RandomAccessContainer where Element: ~Copyable { public func nextSpan( after index: inout Int, maxCount: Int ) -> Span { - precondition(index >= 0 && index <= count, "Index out of bounds") - precondition(maxCount > 0, "maxCount must be positive") - let limit = index &+ Swift.min(maxCount, count &- index) - return self.span.extracting(unchecked: Range(uncheckedBounds: (index, limit))) + self.span._nextSpan(after: &index, maxCount: maxCount) + } + + @_alwaysEmitIntoClient + @_lifetime(borrow self) + public func nextSpan( + after index: inout Index, limitedBy limit: Index? + ) -> Span { + self.span._nextSpan(after: &index, limitedBy: limit) } @_alwaysEmitIntoClient public func spanBoundary(before index: Index, maxDistance: Int) -> Index? { - precondition(index >= 0 && index <= count, "Index out of bounds") - precondition(maxDistance > 0, "maxDistance must be positive") - guard index > 0 else { return nil } - return Swift.max(0, index &- maxDistance) + self.span.spanBoundary(before: index, maxDistance: maxDistance) } } diff --git a/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift b/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift index 4d57fe50..0909be7a 100644 --- a/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift +++ b/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift @@ -44,16 +44,19 @@ where Element: ~Copyable @inline(__always) public var endIndex: Index { count } - @inlinable + @_alwaysEmitIntoClient @_lifetime(borrow self) public func nextSpan(after index: inout Index, maxCount: Int) -> Span { - precondition(index >= 0 && index <= count, "Index out of bounds") - precondition(maxCount > 0, "maxCount must be positive") - let limit = Swift.min(count &- index, maxCount) - return self.span.extracting(unchecked: Range(uncheckedBounds: (index, limit))) + self.span._nextSpan(after: &index, maxCount: maxCount) } - @inlinable + @_alwaysEmitIntoClient + @_lifetime(borrow self) + public func nextSpan(after index: inout Index, limitedBy limit: Int?) -> Span { + self.span._nextSpan(after: &index, limitedBy: limit) + } + + @_alwaysEmitIntoClient @_lifetime(&self) public mutating func nextMutableSpan( after index: inout Index, maxCount: Int diff --git a/Sources/ContainersPreview/Conformances/Span+Container.swift b/Sources/ContainersPreview/Conformances/Span+Container.swift index cdc7649f..4a6f2fd5 100644 --- a/Sources/ContainersPreview/Conformances/Span+Container.swift +++ b/Sources/ContainersPreview/Conformances/Span+Container.swift @@ -38,7 +38,10 @@ extension Span: RandomAccessContainer where Element: ~Copyable { "Invalid iterator") return iterator._start } +} +@available(SwiftStdlib 5.0, *) +extension Span where Element: ~Copyable { @_alwaysEmitIntoClient public var startIndex: Int { 0 @@ -49,15 +52,49 @@ extension Span: RandomAccessContainer where Element: ~Copyable { count } + // FIXME: This has the proper lifetime declaration but can't fulfill the Container requirement. @_alwaysEmitIntoClient - @_lifetime(borrow self) - public func nextSpan(after index: inout Int, maxCount: Int) -> Span { + @_lifetime(copy self) + public func _nextSpan(after index: inout Int, maxCount: Int) -> Self { precondition(index >= 0 && index <= count, "Index out of bounds") precondition(maxCount > 0, "maxCount must be positive") let limit = index &+ Swift.min(maxCount, count &- index) return self.extracting(unchecked: Range(uncheckedBounds: (index, limit))) } + @_alwaysEmitIntoClient + @_lifetime(borrow self) + public func nextSpan(after index: inout Int, maxCount: Int) -> Self { + _nextSpan(after: &index, maxCount: maxCount) + } + + // FIXME: This has the proper lifetime declaration but can't fulfill the Container requirement. + @_alwaysEmitIntoClient + @_lifetime(copy self) + public func _nextSpan( + after index: inout Index, limitedBy limit: Index? + ) -> Self { + precondition(index >= 0 && index <= count, "Index out of bounds") + let end: Index + if let limit { + precondition(limit >= 0 && limit <= count, "Index out of bounds") + end = Swift.min(limit, count) + } else { + end = count + } + let range = Range(uncheckedBounds: (index, end)) + index = end + return self.extracting(unchecked: range) + } + + @_alwaysEmitIntoClient + @_lifetime(borrow self) + public func nextSpan( + after index: inout Index, limitedBy limit: Index? + ) -> Self { + _nextSpan(after: &index, limitedBy: limit) + } + @_alwaysEmitIntoClient public func spanBoundary(before index: Index, maxDistance: Int) -> Index? { precondition(index >= 0 && index <= count, "Index out of bounds") diff --git a/Sources/ContainersPreview/Protocols/Container/Container.swift b/Sources/ContainersPreview/Protocols/Container/Container.swift index d2fb3928..c4107a8d 100644 --- a/Sources/ContainersPreview/Protocols/Container/Container.swift +++ b/Sources/ContainersPreview/Protocols/Container/Container.swift @@ -219,18 +219,23 @@ public protocol Container: @_lifetime(borrow self) func nextSpan(after index: inout Index, maxCount: Int) -> Span - // This allows faster default implementations for algorithms like - // `distance(from:to:)` or `formIndex(_:offsetBy:limitedBy:)`. @_lifetime(borrow self) func nextSpan( after index: inout Index, - limitedBy limit: Index + limitedBy limit: Index? ) -> Span func _customIndexOfEquatableElement(_ element: borrowing Element) -> Index?? func _customLastIndexOfEquatableElement(_ element: borrowing Element) -> Index?? } +@available(SwiftStdlib 6.4, *) +extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { + @_alwaysEmitIntoClient + @_transparent + public var underestimatedCount_: Int { count } +} + @available(SwiftStdlib 6.4, *) extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { /// Return a span over the container's storage that begins with the element at @@ -270,7 +275,7 @@ extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(borrow self) public func nextSpan(after index: inout Index) -> Span { - nextSpan(after: &index, maxCount: Int.max) + nextSpan(after: &index, limitedBy: nil) } } @@ -281,10 +286,12 @@ extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { count == 0 } +#if false // count is required to be O(1), so it cannot have a default implementation @_alwaysEmitIntoClient public var count: Int { distance(from: startIndex, to: endIndex) } +#endif @_alwaysEmitIntoClient public func formIndex(after index: inout Index) { @@ -297,10 +304,11 @@ extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { n >= 0, "Only BidirectionalContainers can be advanced by a negative amount") +#if false + // This is tempting, but it would lead to mutual recursion with the + // default implementation of `nextSpan(after:maxCount:)`. var index = index var n = n - -#if true // with nextSpan(after:maxCount:) while n > 0 { let span = self.nextSpan(after: &index, maxCount: n) precondition( @@ -308,29 +316,15 @@ extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { "Cannot advance index beyond the end of the container") n &-= span.count } - return index -#else // without nextSpan(after:maxCount:) - // FIXME: This implementation can be wasteful for piecewise contiguous - // containers, as iterating over spans will tend to overshoot the target. - - // Skip forward until we find the span that contains our target. - while distance > 0 { - var j = i - let span = self.nextSpan(after: &j) - precondition( - !span.isEmpty, - "Cannot advance index beyond the end of the container") - guard span.count <= distance else { break } - i = j - distance &-= span.count +#else + var index = index + var n = n + while n > 0 { + self.formIndex(after: &index) + n &-= 1 } - // Step through to find the precise target. - while distance > 0 { - self.formIndex(after: &i) - distance &-= 1 - } - return i #endif + return index } @_alwaysEmitIntoClient @@ -340,12 +334,16 @@ extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { precondition( n >= 0, "Only BidirectionalContainers can be advanced by a negative amount") - - // Note: with Index not conforming to `Comparable`, we cannot do bulk - // iteration here, as we have no way to decide if we stepped over `limit`. - while n > 0, index != limit { - self.formIndex(after: &index) - n &-= 1 + while n > 0 { + var j = index + let span = self.nextSpan(after: &j, limitedBy: limit) + if span.count > n { + index = self.index(index, offsetBy: n) + n = 0 + break + } + index = j + n &-= span.count } } @@ -362,66 +360,31 @@ extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { @_alwaysEmitIntoClient public func distance(from start: Index, to end: Index) -> Int { -#if true - // This variant does not require that `start` precede `end`, but it's - // slower/larger. - // FIXME: Linked lists may require an even slower implementation - // to avoid looping (turtle/hare cycle detection). - let limit = self.endIndex - var a = start - var b = end - var d = 0 - while true { - if a == end { return d } - if b == start { return -d } - if a == limit { - while b != end { - self.formIndex(after: &b) - d += 1 - } - return -d - } - if b == limit { - while a != end { - self.formIndex(after: &a) - d += 1 - } - return d - } - self.formIndex(after: &a) - self.formIndex(after: &b) - d += 1 - } -#else - // This variant requires that `start` precede `end`, but we cannot ensure - // that with a quick check, so we need to compare against the `endIndex` to - // avoid looping indefinitely. - // FIXME: Certain linked lists may require an even slower implementation - // to avoid looping indefinitely (turtle/hare cycle detection). + // This variant allows bulk iteration, but as we can't decide if + // start <= end, we have to measure distances from both ends. + var d1 = 0 + var d2 = 0 var i = start - let target = end - let limit = self.endIndex - var count = 0 - while i != target { - self.formIndex(after: &i) - // We cannot rely on `formIndex(after:)` catching the end in a resonable - // time, as container implementations often delay index validation until - // an element is actually accessed. - precondition(i != limit, "Only BidirectionalContainers can have end come before start") - count += 1 + var j = end + while true { + d1 += self.nextSpan(after: &i, limitedBy: end).count + if i == end { return d1 } + d2 += self.nextSpan(after: &j, limitedBy: start).count + if j == start { return d2 } } - return count -#endif } @_alwaysEmitIntoClient @_lifetime(borrow self) - public func nextSpan( - after index: inout Index, - limitedBy limit: Index - ) -> Span { - let d = self.distance(from: index, to: limit) - return self.nextSpan(after: &index, maxCount: d) + public func nextSpan(after index: inout Index, maxCount: Int) -> Span { + var j = index + let span = self.nextSpan(after: &j) + if span.count <= maxCount { + index = j + return span + } + index = self.index(index, offsetBy: maxCount) + return span.extracting(first: maxCount) } @_alwaysEmitIntoClient @@ -446,27 +409,18 @@ where { @_alwaysEmitIntoClient public func distance(from start: Index, to end: Index) -> Int { - var (i, j, step): (Index, Index, Int) = (start <= end - ? (start, end, 1) - : (end, start, -1)) + var (i, j, forward): (Index, Index, Bool) = (start <= end + ? (start, end, true) + : (end, start, false)) var d = 0 while i < j { - // FIXME: Consider using bulk iteration here, with binary search within the final chunk. - // (The code size complexity may not be worth the effort.) - self.formIndex(after: &i) - d += step + let span = self.nextSpan(after: &i, limitedBy: j) + d += span.count } - return d + return forward ? d : -d } } -@available(SwiftStdlib 6.4, *) -extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { - @_alwaysEmitIntoClient - @_transparent - public var underestimatedCount_: Int { count } -} - // FIXME: Add ambiguity resolvers against Collection's algorithms. #endif diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift index 81ca02fc..3a7dd349 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift @@ -164,6 +164,24 @@ extension RigidDeque where Element: ~Copyable { return _overrideLifetime(Span(_unsafeElements: segment), borrowing: self) } + @_alwaysEmitIntoClient + @_lifetime(borrow self) + public func nextSpan( + after index: inout Int, limitedBy limit: Int? + ) -> Span { + _checkValidIndex(index) + let segment = self._handle.nextSegment(after: index) + var span = _overrideLifetime(Span(_unsafeElements: segment), borrowing: self) + if let limit { + _checkValidIndex(limit) + if limit >= index, span.count > limit - index { + span = span.extracting(first: limit - index) + } + } + index += span.count + return span + } + @_lifetime(&self) public mutating func nextMutableSpan( after index: inout Int, maxCount: Int diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift index 14fe9ebb..1a420242 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift @@ -104,6 +104,12 @@ extension UniqueDeque where Element: ~Copyable { _storage.nextSpan(after: &index, maxCount: maxCount) } + @_alwaysEmitIntoClient + @_lifetime(borrow self) + public func nextSpan(after index: inout Int, limitedBy limit: Int?) -> Span { + _storage.nextSpan(after: &index, limitedBy: limit) + } + @_alwaysEmitIntoClient @_lifetime(&self) public mutating func nextMutableSpan( diff --git a/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift b/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift index 223e6194..94c1c702 100644 --- a/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift +++ b/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift @@ -142,7 +142,7 @@ extension StaccatoContainer: Iterable_ where Element: ~Copyable { @available(SwiftStdlib 5.0, *) extension StaccatoContainer: Container where Element: ~Copyable { public typealias Index = _StaccatoIndex - + public var isEmpty: Bool { count == 0 } public var count: Int { _params._count } @@ -164,29 +164,29 @@ extension StaccatoContainer: Container where Element: ~Copyable { public var startIndex: Index { Index(_offset: 0) } public var endIndex: Index { Index(_offset: _contents.count) } - + public func index(after index: Index) -> Index { precondition(index._offset >= 0 && index._offset < count) return Index(_offset: index._offset + 1) } - + public func index(before index: Index) -> Index { precondition(index._offset > 0 && index._offset <= count) return Index(_offset: index._offset - 1) } - + public func index(_ index: Index, offsetBy n: Int) -> Index { precondition(index._offset >= 0 && index._offset <= count) let j = index._offset + n precondition(j >= 0 && j <= count) return Index(_offset: j) } - + public func distance(from start: Index, to end: Index) -> Int { precondition(_isValid(start) && _isValid(end)) return end._offset - start._offset } - + public func formIndex( _ index: inout Index, offsetBy n: inout Int, limitedBy limit: Index ) { @@ -212,5 +212,22 @@ extension StaccatoContainer: Container where Element: ~Copyable { index._offset = endOffset return _contents.span.extracting(startOffset ..< endOffset) } + + @_lifetime(borrow self) + public func nextSpan( + after index: inout Index, limitedBy limit: Index? + ) -> Span { + precondition(_isValid(index)) + + var limit = limit ?? endIndex + if limit < index { limit = endIndex } + + let startOffset = index._offset + let endOffset = _params.endOffset( + fromOffset: index._offset, + maxCount: limit._offset - index._offset) + index._offset = endOffset + return _contents.span.extracting(startOffset ..< endOffset) + } } #endif