From 73ec3d341611e0167e478b1b015413a060d4f97b Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 28 May 2026 17:52:43 -0700 Subject: [PATCH 01/50] [BasicContainers, DequeModule] Clean up Equatable/Hashable conformances Make sure all types conditionally conform to Equatable/Hashable, even if their contents happen to be noncopyable. --- .../RigidArray/RigidArray+Equatable.swift | 8 +++-- .../RigidArray/RigidArray+Hashable.swift | 17 +++++++++- .../RigidDictionary+Equatable.swift | 9 +++-- .../RigidDictionary+Hashable.swift | 6 +++- .../RigidSet/RigidSet+Equatable.swift | 9 ++--- .../RigidSet/RigidSet+Hashable.swift | 6 ++-- .../UniqueArray/UniqueArray+Equatable.swift | 8 +++-- .../UniqueArray/UniqueArray+Hashable.swift | 34 +++++++++++++------ .../UniqueSet/UniqueSet+Equatable.swift | 6 ++-- .../UniqueSet/UniqueSet+Hashable.swift | 4 +-- .../RigidDeque/RigidDeque+Equatable.swift | 8 +++-- .../RigidDeque/RigidDeque+Hashable.swift | 6 +++- .../UniqueDeque/UniqueDeque+Equatable.swift | 6 +++- .../UniqueDeque/UniqueDeque+Hashable.swift | 6 +++- 14 files changed, 95 insertions(+), 38 deletions(-) diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Equatable.swift b/Sources/BasicContainers/RigidArray/RigidArray+Equatable.swift index e32a8c49..fcb8a698 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Equatable.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Equatable.swift @@ -25,9 +25,13 @@ extension RigidArray where Element: ~Copyable { } } -#if compiler(>=6.4) && UnstableContainersPreview -@available(SwiftStdlib 5.0, *) +#if compiler(>=6.4) +@available(SwiftStdlib 6.4, *) extension RigidArray: Equatable where Element: Equatable & ~Copyable { +} + +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: Equatable & ~Copyable { @inlinable public static func ==( left: borrowing Self, diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Hashable.swift b/Sources/BasicContainers/RigidArray/RigidArray+Hashable.swift index 3b0e264f..7cab7841 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Hashable.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Hashable.swift @@ -17,13 +17,28 @@ import InternalCollectionsUtilities #endif +#if compiler(>=6.4) +@available(SwiftStdlib 6.4, *) +extension RigidArray: Hashable where Element: Hashable & ~Copyable { +} + @available(SwiftStdlib 5.0, *) -extension RigidArray /*: Hashable */ where Element: Hashable /* & ~Copyable */ { +extension RigidArray where Element: Hashable & ~Copyable { @inlinable public func hash(into hasher: inout Hasher) { hasher.combine(self.count) self.span._hashContents(into: &hasher) } } +#else +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: Hashable { + @inlinable + public func hash(into hasher: inout Hasher) { + hasher.combine(self.count) + self.span._hashContents(into: &hasher) + } +} +#endif #endif diff --git a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Equatable.swift b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Equatable.swift index 23b8383a..7eaba400 100644 --- a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Equatable.swift +++ b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Equatable.swift @@ -20,7 +20,7 @@ import ContainersPreview #if compiler(>=6.4) && UnstableHashedContainers @available(SwiftStdlib 5.0, *) -extension RigidDictionary { +extension RigidDictionary where Key: ~Copyable, Value: ~Copyable { @inlinable public func isTriviallyIdentical(to other: borrowing Self) -> Bool { self._keys.isTriviallyIdentical(to: other._keys) @@ -29,7 +29,7 @@ extension RigidDictionary { } @available(SwiftStdlib 5.0, *) -extension RigidDictionary { +extension RigidDictionary where Key: ~Copyable, Value: ~Copyable { @inlinable public func isEqual( to other: borrowing Self, @@ -56,8 +56,11 @@ extension RigidDictionary { } } +@available(SwiftStdlib 6.4, *) +extension RigidDictionary: Equatable where Key: ~Copyable, Value: Equatable & ~Copyable {} + @available(SwiftStdlib 5.0, *) -extension RigidDictionary: Equatable where Value: Equatable { +extension RigidDictionary where Key: ~Copyable, Value: Equatable & ~Copyable { @inlinable public static func ==(left: borrowing Self, right: borrowing Self) -> Bool { left.isEqual(to: right, by: ==) diff --git a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Hashable.swift b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Hashable.swift index 398785cd..5b49ff4d 100644 --- a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Hashable.swift +++ b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Hashable.swift @@ -18,8 +18,12 @@ import ContainersPreview #if compiler(>=6.4) && UnstableHashedContainers +@available(SwiftStdlib 6.4, *) +extension RigidDictionary: Hashable where Value: Hashable & ~Copyable { +} + @available(SwiftStdlib 5.0, *) -extension RigidDictionary: Hashable where Value: Hashable { // Should be Hashable +extension RigidDictionary where Value: Hashable & ~Copyable { @inlinable public func hash(into hasher: inout Hasher) { var commutativeHash = 0 diff --git a/Sources/BasicContainers/RigidSet/RigidSet+Equatable.swift b/Sources/BasicContainers/RigidSet/RigidSet+Equatable.swift index d5796880..c23b84bf 100644 --- a/Sources/BasicContainers/RigidSet/RigidSet+Equatable.swift +++ b/Sources/BasicContainers/RigidSet/RigidSet+Equatable.swift @@ -20,7 +20,7 @@ import ContainersPreview #if compiler(>=6.4) && UnstableHashedContainers @available(SwiftStdlib 5.0, *) -extension RigidSet { +extension RigidSet where Element: ~Copyable { @inlinable public func isTriviallyIdentical(to other: borrowing Self) -> Bool { self._members == other._members @@ -28,12 +28,11 @@ extension RigidSet { } } -#if UnstableContainersPreview @available(SwiftStdlib 6.4, *) -extension RigidSet: Equatable {} +extension RigidSet: Equatable where Element: ~Copyable {} @available(SwiftStdlib 5.0, *) -extension RigidSet { +extension RigidSet where Element: ~Copyable { @inlinable public static func ==(left: borrowing Self, right: borrowing Self) -> Bool { if left.isTriviallyIdentical(to: right) { return true } @@ -54,5 +53,3 @@ extension RigidSet { } } #endif - -#endif diff --git a/Sources/BasicContainers/RigidSet/RigidSet+Hashable.swift b/Sources/BasicContainers/RigidSet/RigidSet+Hashable.swift index cc028880..f711eb3a 100644 --- a/Sources/BasicContainers/RigidSet/RigidSet+Hashable.swift +++ b/Sources/BasicContainers/RigidSet/RigidSet+Hashable.swift @@ -19,10 +19,10 @@ import ContainersPreview #if compiler(>=6.4) && UnstableHashedContainers && UnstableContainersPreview @available(SwiftStdlib 6.4, *) -extension RigidSet: Hashable {} +extension RigidSet: Hashable where Element: ~Copyable {} @available(SwiftStdlib 5.0, *) -extension RigidSet { +extension RigidSet where Element: ~Copyable { @inlinable public func hash(into hasher: inout Hasher) { // Generate a seed from a snapshot of the hasher. This makes members' hash @@ -42,7 +42,7 @@ extension RigidSet { let next = it.nextSpan_() var i = 0 while i < next.count { - hash ^= next[i]._rawHashValue(seed: seed) + hash ^= next[unchecked: i]._rawHashValue(seed: seed) i &+= 1 } } diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Equatable.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Equatable.swift index a87f386d..c61d4f85 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Equatable.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Equatable.swift @@ -24,9 +24,13 @@ extension UniqueArray where Element: ~Copyable { } } -#if compiler(>=6.4) && UnstableContainersPreview -@available(SwiftStdlib 5.0, *) +#if compiler(>=6.4) +@available(SwiftStdlib 6.4, *) extension UniqueArray: Equatable where Element: Equatable & ~Copyable { +} + +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: Equatable & ~Copyable { @inlinable public static func ==( left: borrowing Self, diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Hashable.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Hashable.swift index c2584c07..646cbc12 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Hashable.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Hashable.swift @@ -13,16 +13,30 @@ #if compiler(>=6.2) -@available(SwiftStdlib 5.0, *) -extension UniqueArray /*: Hashable */ where Element: Hashable /* & ~Copyable */ { - @inlinable - public func hash(into hasher: inout Hasher) { - hasher.combine(self.count) - let span = self.span - for i in 0 ..< count { - hasher.combine(span[unchecked: i]) - } - } +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +#endif + +#if compiler(>=6.4) +@available(SwiftStdlib 6.4, *) +extension UniqueArray: Hashable where Element: Hashable & ~Copyable { } +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: Hashable & ~Copyable { + @inlinable + public func hash(into hasher: inout Hasher) { + self._storage.hash(into: &hasher) + } +} +#else +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: Hashable { + @inlinable + public func hash(into hasher: inout Hasher) { + self._storage.hash(into: &hasher) + } +} +#endif + #endif diff --git a/Sources/BasicContainers/UniqueSet/UniqueSet+Equatable.swift b/Sources/BasicContainers/UniqueSet/UniqueSet+Equatable.swift index 3bd9e660..6dcd462a 100644 --- a/Sources/BasicContainers/UniqueSet/UniqueSet+Equatable.swift +++ b/Sources/BasicContainers/UniqueSet/UniqueSet+Equatable.swift @@ -20,7 +20,7 @@ import ContainersPreview #if compiler(>=6.4) && UnstableHashedContainers && UnstableContainersPreview @available(SwiftStdlib 5.0, *) -extension UniqueSet { +extension UniqueSet where Element: ~Copyable { @inlinable @inline(__always) public func isTriviallyIdentical(to other: borrowing Self) -> Bool { @@ -29,10 +29,10 @@ extension UniqueSet { } @available(SwiftStdlib 6.4, *) -extension UniqueSet: Equatable {} +extension UniqueSet: Equatable where Element: ~Copyable {} @available(SwiftStdlib 5.0, *) -extension UniqueSet { +extension UniqueSet where Element: ~Copyable { @inlinable @inline(__always) public static func ==(left: borrowing Self, right: borrowing Self) -> Bool { diff --git a/Sources/BasicContainers/UniqueSet/UniqueSet+Hashable.swift b/Sources/BasicContainers/UniqueSet/UniqueSet+Hashable.swift index 61468f5a..62a1f956 100644 --- a/Sources/BasicContainers/UniqueSet/UniqueSet+Hashable.swift +++ b/Sources/BasicContainers/UniqueSet/UniqueSet+Hashable.swift @@ -19,10 +19,10 @@ import ContainersPreview #if compiler(>=6.4) && UnstableHashedContainers && UnstableContainersPreview @available(SwiftStdlib 6.4, *) -extension UniqueSet: Hashable {} +extension UniqueSet: Hashable where Element: ~Copyable {} @available(SwiftStdlib 5.0, *) -extension UniqueSet { +extension UniqueSet where Element: ~Copyable { @inlinable public func hash(into hasher: inout Hasher) { _storage.hash(into: &hasher) diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Equatable.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Equatable.swift index c506ba5c..6b82a90b 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Equatable.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Equatable.swift @@ -19,14 +19,18 @@ import ContainersPreview #endif @available(SwiftStdlib 5.0, *) -extension RigidDeque /*: Equatable */ where Element: Equatable /* & ~Copyable */ { +extension RigidDeque: Equatable where Element: Equatable & ~Copyable { public func isTriviallyIdentical(to other: borrowing Self) -> Bool { self._handle.isIdentical(to: other._handle) } } +@available(SwiftStdlib 6.4, *) +extension RigidDeque: Equatable where Element: Equatable & ~Copyable { +} + @available(SwiftStdlib 5.0, *) -extension RigidDeque /*: Equatable */ where Element: Equatable /* & ~Copyable */ { +extension RigidDeque where Element: Equatable & ~Copyable { @inlinable public static func ==( left: borrowing Self, diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Hashable.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Hashable.swift index 1eea2934..acec6cd3 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Hashable.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Hashable.swift @@ -17,8 +17,12 @@ import InternalCollectionsUtilities #endif +@available(SwiftStdlib 6.4, *) +extension RigidDeque: Hashable where Element: Hashable & ~Copyable { +} + @available(SwiftStdlib 5.0, *) -extension RigidDeque /*: Hashable */ where Element: Hashable /* & ~Copyable */ { +extension RigidDeque where Element: Hashable & ~Copyable { @inlinable public func hash(into hasher: inout Hasher) { hasher.combine(self.count) diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Equatable.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Equatable.swift index 5de7bd43..aac7237a 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Equatable.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Equatable.swift @@ -17,8 +17,12 @@ import InternalCollectionsUtilities #endif +@available(SwiftStdlib 6.4, *) +extension UniqueDeque: Equatable where Element: Equatable & ~Copyable { +} + @available(SwiftStdlib 5.0, *) -extension UniqueDeque /*: Equatable */ where Element: Equatable /* & ~Copyable */ { +extension UniqueDeque where Element: Equatable & ~Copyable { @inlinable public static func ==( left: borrowing Self, diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Hashable.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Hashable.swift index 0a4f8b4a..32c19298 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Hashable.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Hashable.swift @@ -13,8 +13,12 @@ #if compiler(>=6.2) +@available(SwiftStdlib 6.4, *) +extension UniqueDeque: Hashable where Element: Hashable & ~Copyable { +} + @available(SwiftStdlib 5.0, *) -extension UniqueDeque /*: Hashable */ where Element: Hashable /* & ~Copyable */ { +extension UniqueDeque where Element: Hashable & ~Copyable { @inlinable public func hash(into hasher: inout Hasher) { self._storage.hash(into: &hasher) From de3b9b67beb6f43706e3128245c4535ffb05884b Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 2 Jun 2026 18:39:07 -0700 Subject: [PATCH 02/50] [ContainersPreview] Move helpers to InternalCollectionsUtilities --- .../CMakeLists.txt | 3 ++ .../Optional+Extras.swift | 0 .../OutputSpan+Extras.swift | 29 +++++++++++++++---- .../TemporaryAllocation.swift | 0 4 files changed, 26 insertions(+), 6 deletions(-) rename Sources/{ContainersPreview/Extensions => InternalCollectionsUtilities}/Optional+Extras.swift (100%) rename Sources/{ContainersPreview/Extensions => InternalCollectionsUtilities}/OutputSpan+Extras.swift (90%) rename Sources/{ContainersPreview/Extensions => InternalCollectionsUtilities}/TemporaryAllocation.swift (100%) diff --git a/Sources/InternalCollectionsUtilities/CMakeLists.txt b/Sources/InternalCollectionsUtilities/CMakeLists.txt index e52b1c50..73f92a23 100644 --- a/Sources/InternalCollectionsUtilities/CMakeLists.txt +++ b/Sources/InternalCollectionsUtilities/CMakeLists.txt @@ -35,9 +35,12 @@ target_sources(${module_name} PRIVATE "Debugging.swift" "Descriptions.swift" "LifetimeOverride.swift" + "Optional+Extras.swift" + "OutputSpan+Extras.swift" "RandomAccessCollection+Offsets.swift" "Span+Extras.swift" "String+Padding.swift" + "TemporaryAllocation.swift" "UnsafeBufferPointer+Extras.swift" "UnsafeMutableBufferPointer+Extras.swift" "UnsafeMutableRawBufferPointer+Extras.swift" diff --git a/Sources/ContainersPreview/Extensions/Optional+Extras.swift b/Sources/InternalCollectionsUtilities/Optional+Extras.swift similarity index 100% rename from Sources/ContainersPreview/Extensions/Optional+Extras.swift rename to Sources/InternalCollectionsUtilities/Optional+Extras.swift diff --git a/Sources/ContainersPreview/Extensions/OutputSpan+Extras.swift b/Sources/InternalCollectionsUtilities/OutputSpan+Extras.swift similarity index 90% rename from Sources/ContainersPreview/Extensions/OutputSpan+Extras.swift rename to Sources/InternalCollectionsUtilities/OutputSpan+Extras.swift index d0df65f4..2c2e403c 100644 --- a/Sources/ContainersPreview/Extensions/OutputSpan+Extras.swift +++ b/Sources/InternalCollectionsUtilities/OutputSpan+Extras.swift @@ -13,10 +13,6 @@ #if compiler(>=6.2) -#if !COLLECTIONS_SINGLE_MODULE -import InternalCollectionsUtilities -#endif - @available(SwiftStdlib 5.0, *) @_alwaysEmitIntoClient package func withTemporaryOutputSpan( @@ -70,7 +66,7 @@ extension OutputSpan where Element: ~Copyable { dstCount &+= source.count } } - + #if UnstableContainersPreview @_lifetime(source: copy source) @inlinable @@ -117,7 +113,7 @@ extension OutputSpan /*where Element: Copyable*/ { dstCount &+= source.count } } - + @inlinable @_lifetime(self: copy self) package mutating func _append(copying source: Span) { @@ -158,4 +154,25 @@ extension OutputSpan where Element: ~Copyable { } } +#if UnstableContainersPreview +@available(SwiftStdlib 5.0, *) +extension OutputSpan where Element: ~Copyable { + @_alwaysEmitIntoClient + @_lifetime(self: copy self) + package mutating func _consumeAll( + consumingWith consumer: (inout InputSpan) -> Void + ) { + self.withUnsafeMutableBufferPointer { buffer, count in + var span = InputSpan( + buffer: buffer._extracting(first: count), + initializedCount: count) + consumer(&span) + _ = consume span + count = 0 + } + } +} #endif + +#endif + diff --git a/Sources/ContainersPreview/Extensions/TemporaryAllocation.swift b/Sources/InternalCollectionsUtilities/TemporaryAllocation.swift similarity index 100% rename from Sources/ContainersPreview/Extensions/TemporaryAllocation.swift rename to Sources/InternalCollectionsUtilities/TemporaryAllocation.swift From 1f5d0ab3437a0eba6a5d2082e171c0220080c183 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 3 Jun 2026 12:58:37 -0700 Subject: [PATCH 03/50] [BasicContainers, DequeModule] Resolve warnings in 6.4 --- Sources/BasicContainers/RigidArray/RigidArray+Append.swift | 2 +- .../BasicContainers/RigidArray/RigidArray+Replacements.swift | 2 +- Sources/DequeModule/RigidDeque/RigidDeque+Append.swift | 2 +- Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift | 2 +- Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift | 2 +- Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift | 2 +- Sources/DequeModule/UniqueDeque/UniqueDeque+Insertions.swift | 2 +- Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift | 2 +- .../DequeModule/UniqueDeque/UniqueDeque+Replacements.swift | 2 +- Tests/BasicContainersTests/UniqueArrayTests.swift | 4 ++-- Tests/ContainersTests/MutableRefTests.swift | 4 ++-- Tests/ContainersTests/RefTests.swift | 2 +- 12 files changed, 14 insertions(+), 14 deletions(-) diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Append.swift b/Sources/BasicContainers/RigidArray/RigidArray+Append.swift index 0099c261..39fef60f 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Append.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Append.swift @@ -331,7 +331,7 @@ extension RigidArray { /// - Complexity: O(`newElements.count`) @_alwaysEmitIntoClient public mutating func append(copying items: Span) { - unsafe items.withUnsafeBufferPointer { source in + items.withUnsafeBufferPointer { source in unsafe self.append(copying: source) } } diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Replacements.swift b/Sources/BasicContainers/RigidArray/RigidArray+Replacements.swift index 0d332c7a..c62bd142 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Replacements.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Replacements.swift @@ -577,7 +577,7 @@ extension RigidArray { removing subrange: Range, copying newElements: Span ) { - unsafe newElements.withUnsafeBufferPointer { buffer in + newElements.withUnsafeBufferPointer { buffer in unsafe self.replace(removing: subrange, copying: buffer) } } diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Append.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Append.swift index 942cd4ed..535f0b92 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Append.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Append.swift @@ -305,7 +305,7 @@ extension RigidDeque /*where Element: Copyable*/ { /// - Complexity: O(`items.count`) @_alwaysEmitIntoClient public mutating func append(copying items: Span) { - unsafe items.withUnsafeBufferPointer { source in + items.withUnsafeBufferPointer { source in unsafe self.append(copying: source) } } diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift index 046e1766..484cec12 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift @@ -350,7 +350,7 @@ extension RigidDeque /* where Element: Copyable */ { public mutating func insert( copying items: Span, at index: Int ) { - unsafe items.withUnsafeBufferPointer { + items.withUnsafeBufferPointer { unsafe self.insert(copying: $0, at: index) } } diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift index bd67fa8e..931cba4d 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift @@ -282,7 +282,7 @@ extension RigidDeque /*where Element: Copyable*/ { @inlinable @_alwaysEmitIntoClient public mutating func prepend(copying items: Span) { - unsafe items.withUnsafeBufferPointer { source in + items.withUnsafeBufferPointer { source in unsafe self.prepend(copying: source) } } diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift index e9d592a4..9fde6108 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift @@ -450,7 +450,7 @@ extension RigidDeque /* where Element: Copyable */ { removing subrange: Range, copying items: Span ) { - unsafe items.withUnsafeBufferPointer { buffer in + items.withUnsafeBufferPointer { buffer in unsafe self.replace(removing: subrange, copying: buffer) } } diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Insertions.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Insertions.swift index f7785077..a4bf1781 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Insertions.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Insertions.swift @@ -368,7 +368,7 @@ extension UniqueDeque /* where Element: Copyable */ { public mutating func insert( copying items: Span, at index: Int ) { - unsafe items.withUnsafeBufferPointer { + items.withUnsafeBufferPointer { unsafe self.insert(copying: $0, at: index) } } diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift index 53fb9bbc..274454f7 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift @@ -314,7 +314,7 @@ extension UniqueDeque /*where Element: Copyable*/ { @inlinable @_alwaysEmitIntoClient public mutating func prepend(copying items: Span) { - unsafe items.withUnsafeBufferPointer { source in + items.withUnsafeBufferPointer { source in unsafe self.prepend(copying: source) } } diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Replacements.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Replacements.swift index 3546a7df..b66e2feb 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Replacements.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Replacements.swift @@ -459,7 +459,7 @@ extension UniqueDeque /* where Element: Copyable */ { removing subrange: Range, copying items: Span ) { - unsafe items.withUnsafeBufferPointer { buffer in + items.withUnsafeBufferPointer { buffer in unsafe self.replace(removing: subrange, copying: buffer) } } diff --git a/Tests/BasicContainersTests/UniqueArrayTests.swift b/Tests/BasicContainersTests/UniqueArrayTests.swift index d47a48fd..a1af5e0f 100644 --- a/Tests/BasicContainersTests/UniqueArrayTests.swift +++ b/Tests/BasicContainersTests/UniqueArrayTests.swift @@ -130,7 +130,7 @@ class UniqueArrayTests: CollectionTestCase { func test_init_capacity() { do { - let a = UniqueArray(capacity: 0) + let a = UniqueArray(minimumCapacity: 0) expectEqual(a.capacity, 0) expectEqual(a.count, 0) expectEqual(a.freeCapacity, 0) @@ -138,7 +138,7 @@ class UniqueArrayTests: CollectionTestCase { } do { - let a = UniqueArray(capacity: 10) + let a = UniqueArray(minimumCapacity: 10) expectEqual(a.capacity, 10) expectEqual(a.count, 0) expectEqual(a.freeCapacity, 10) diff --git a/Tests/ContainersTests/MutableRefTests.swift b/Tests/ContainersTests/MutableRefTests.swift index 435c23c1..d6792ffd 100644 --- a/Tests/ContainersTests/MutableRefTests.swift +++ b/Tests/ContainersTests/MutableRefTests.swift @@ -108,7 +108,7 @@ final class MutableRefTests: CollectionTestCase { func test_init_unsafeAddress_mutating() { var x = 789 - let pointer = unsafe withUnsafeMutablePointer(to: &x) { $0 } + let pointer = withUnsafeMutablePointer(to: &x) { $0 } var ref = unsafe _MutableRef(unsafeAddress: pointer, mutating: &x) expectEqual(ref.value, 789) ref.value = 111 @@ -119,7 +119,7 @@ final class MutableRefTests: CollectionTestCase { func test_init_unsafeImmortalAddress() { var x = 555 - let pointer = unsafe withUnsafeMutablePointer(to: &x) { $0 } + let pointer = withUnsafeMutablePointer(to: &x) { $0 } var ref = unsafe _MutableRef(unsafeImmortalAddress: pointer) expectEqual(ref.value, 555) ref.value = 666 diff --git a/Tests/ContainersTests/RefTests.swift b/Tests/ContainersTests/RefTests.swift index b83376d6..2e096946 100644 --- a/Tests/ContainersTests/RefTests.swift +++ b/Tests/ContainersTests/RefTests.swift @@ -71,7 +71,7 @@ final class RefTests: CollectionTestCase { @available(SwiftStdlib 6.4, *) func test_init_unsafeAddress_borrowing() { let x = 123 - unsafe withUnsafePointer(to: x) { pointer in + withUnsafePointer(to: x) { pointer in let ref = Ref(unsafeAddress: pointer, borrowing: x) expectEqual(ref.value, 123) } From eabf5141d11d391fe86658074bd693d4b1fadd40 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 3 Jun 2026 13:01:38 -0700 Subject: [PATCH 04/50] [ContainersPreview] Add CountedProducer protocol --- Sources/ContainersPreview/CMakeLists.txt | 1 + .../Protocols/CountedProducer.swift | 32 +++++++++++++++++++ Xcode/Collections.xcodeproj/project.pbxproj | 4 +++ 3 files changed, 37 insertions(+) create mode 100644 Sources/ContainersPreview/Protocols/CountedProducer.swift diff --git a/Sources/ContainersPreview/CMakeLists.txt b/Sources/ContainersPreview/CMakeLists.txt index f703ddb1..fc0d2f8c 100644 --- a/Sources/ContainersPreview/CMakeLists.txt +++ b/Sources/ContainersPreview/CMakeLists.txt @@ -52,6 +52,7 @@ target_sources(${module_name} PRIVATE "Protocols/Iterable+Algorithms.swift" "Protocols/Iterable+Standard Conformances.swift" "Protocols/Iterable+Utilities.swift" + "Protocols/CountedProducer.swift" "Protocols/Drain.swift" "Protocols/Drain+Map.swift" "Protocols/Drain+Reduce.swift" diff --git a/Sources/ContainersPreview/Protocols/CountedProducer.swift b/Sources/ContainersPreview/Protocols/CountedProducer.swift new file mode 100644 index 00000000..26d9601f --- /dev/null +++ b/Sources/ContainersPreview/Protocols/CountedProducer.swift @@ -0,0 +1,32 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.4) && UnstableContainersPreview + +/// A producer with an exact count. +@available(SwiftStdlib 5.0, *) +public protocol CountedProducer: ~Copyable, ~Escapable, Producer +where Element: ~Copyable +{ + var count: Int { get } +} + +@available(SwiftStdlib 5.0, *) +extension CountedProducer where Self: ~Copyable & ~Escapable, Element: ~Copyable { + @_alwaysEmitIntoClient + @inline(__always) + public var underestimatedCount: Int { + count + } +} +#endif diff --git a/Xcode/Collections.xcodeproj/project.pbxproj b/Xcode/Collections.xcodeproj/project.pbxproj index de63f9df..7abbd21a 100644 --- a/Xcode/Collections.xcodeproj/project.pbxproj +++ b/Xcode/Collections.xcodeproj/project.pbxproj @@ -145,6 +145,7 @@ 7D72F5982F75E5E6004AB792 /* BorrowingSequenceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D72F5972F75E5E6004AB792 /* BorrowingSequenceTests.swift */; }; 7D7646062FAAA2B9008639E5 /* UniqueBoxTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D7646052FAAA2B9008639E5 /* UniqueBoxTests.swift */; }; 7D7646082FAAABE3008639E5 /* UniqueDeque+Deprecated.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D7646072FAAABDF008639E5 /* UniqueDeque+Deprecated.swift */; }; + 7D77E6122FCF810E003FA63B /* CountedProducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D77E6112FCF810E003FA63B /* CountedProducer.swift */; }; 7D9748D42E9748930098631A /* BigString+Chunk+UTF16.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9748D32E9748930098631A /* BigString+Chunk+UTF16.swift */; }; 7D9748D52E9748930098631A /* BigString+Chunk+UnicodeScalar.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9748D12E9748930098631A /* BigString+Chunk+UnicodeScalar.swift */; }; 7D9748D62E9748930098631A /* BigString+Chunk+Character.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9748CF2E9748930098631A /* BigString+Chunk+Character.swift */; }; @@ -760,6 +761,7 @@ 7D72F5972F75E5E6004AB792 /* BorrowingSequenceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BorrowingSequenceTests.swift; sourceTree = ""; }; 7D7646052FAAA2B9008639E5 /* UniqueBoxTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UniqueBoxTests.swift; sourceTree = ""; }; 7D7646072FAAABDF008639E5 /* UniqueDeque+Deprecated.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueDeque+Deprecated.swift"; sourceTree = ""; }; + 7D77E6112FCF810E003FA63B /* CountedProducer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CountedProducer.swift; sourceTree = ""; }; 7D9748CF2E9748930098631A /* BigString+Chunk+Character.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BigString+Chunk+Character.swift"; sourceTree = ""; }; 7D9748D02E9748930098631A /* BigString+Chunk+Index.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BigString+Chunk+Index.swift"; sourceTree = ""; }; 7D9748D12E9748930098631A /* BigString+Chunk+UnicodeScalar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BigString+Chunk+UnicodeScalar.swift"; sourceTree = ""; }; @@ -1330,6 +1332,7 @@ 7DC037B52FE3492D00CF0CB8 /* IterableIteratorProtocol+Reduce.swift */, 7DC037B62FE3492D00CF0CB8 /* IterableIteratorProtocol+SpanwiseZip.swift */, 7D57EDCE2F647DB10029D5E3 /* Container */, + 7D77E6112FCF810E003FA63B /* CountedProducer.swift */, 7D2A772F2F27F1E4005780C7 /* Drain.swift */, 7D57EDCF2F647DB10029D5E3 /* Drain+Map.swift */, 7D57EDD02F647DB10029D5E3 /* Drain+Reduce.swift */, @@ -3098,6 +3101,7 @@ 7DE9208E29CA70F4004483EB /* _RopeVersion.swift in Sources */, 7DE9212629CA70F4004483EB /* TreeSet+Sendable.swift in Sources */, 7DE9209C29CA70F4004483EB /* Rope+Find.swift in Sources */, + 7D77E6122FCF810E003FA63B /* CountedProducer.swift in Sources */, 7DE920E829CA70F4004483EB /* BitArray+BitwiseOperations.swift in Sources */, 7DE9207829CA70F4004483EB /* BigString+Append.swift in Sources */, 7DE9217F29CA70F4004483EB /* _HeapNode.swift in Sources */, From 12b1cf8020af30f5e2256a4dd1a62d7bb4865cd4 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 3 Jun 2026 13:49:35 -0700 Subject: [PATCH 05/50] [ContainersPreview] Make Drain refine CountedProducer This lets us avoid having to pass an explicit count when using a drain to populate a container. --- .../RigidArray/RigidArray+Consumption.swift | 5 +++++ .../ContainersPreview/Protocols/Drain.swift | 2 +- .../RigidDeque/RigidDeque+Consumption.swift | 5 +++++ .../BasicContainersTests/RigidSetTests.swift | 19 ++++++------------- .../MinimalTypes/CustomDrain.swift | 16 ++++++++++------ 5 files changed, 27 insertions(+), 20 deletions(-) diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Consumption.swift b/Sources/BasicContainers/RigidArray/RigidArray+Consumption.swift index d1a607c6..d17a84e7 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Consumption.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Consumption.swift @@ -197,6 +197,11 @@ extension RigidArray.SubrangeConsumer: Drain where Element: ~Copyable { @available(SwiftStdlib 6.4, *) extension RigidArray.SubrangeConsumer where Element: ~Copyable { + @inlinable + public var count: Int { + _remainder.count + } + @inlinable @_lifetime(&self) @_lifetime(self: copy self) diff --git a/Sources/ContainersPreview/Protocols/Drain.swift b/Sources/ContainersPreview/Protocols/Drain.swift index 79ec964a..039fa984 100644 --- a/Sources/ContainersPreview/Protocols/Drain.swift +++ b/Sources/ContainersPreview/Protocols/Drain.swift @@ -22,7 +22,7 @@ /// moving their consumable contents to the client-supplied series of /// output spans. @available(SwiftStdlib 5.0, *) -public protocol Drain: Producer, ~Copyable, ~Escapable +public protocol Drain: CountedProducer, ~Copyable, ~Escapable where Element: ~Copyable, Failure == Never { /// Returns the next span of consumable items in the sequence underlying this diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Consumption.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Consumption.swift index d7185855..92de4c9c 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Consumption.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Consumption.swift @@ -227,6 +227,11 @@ extension RigidDeque.SubrangeConsumer: Drain where Element: ~Copyable { @available(SwiftStdlib 6.4, *) extension RigidDeque.SubrangeConsumer where Element: ~Copyable { + @inlinable + public var count: Int { + _buffer1.count + _buffer2.count + } + @inlinable @_lifetime(&self) @_lifetime(self: copy self) diff --git a/Tests/BasicContainersTests/RigidSetTests.swift b/Tests/BasicContainersTests/RigidSetTests.swift index 566cf684..b8536df6 100644 --- a/Tests/BasicContainersTests/RigidSetTests.swift +++ b/Tests/BasicContainersTests/RigidSetTests.swift @@ -401,14 +401,11 @@ class RigidSetTests: CollectionTestCase { withLifetimeTracking { tracker in var s = RigidSet>(capacity: capacity) - var i = 0 var drain = CustomDrain>( - underestimatedCount: 0, + count: count, chunkSize: chunkSize - ) { - guard i < count else { return nil } - defer { i += 1 } - return tracker.instance(for: i) + ) { i in + tracker.instance(for: i) } s.insert(from: &drain) expectConsistentSet(s) @@ -437,21 +434,17 @@ class RigidSetTests: CollectionTestCase { withLifetimeTracking { tracker in var s = RigidSet>(capacity: capacity) - var i = 0 var drain = CustomDrain>( - underestimatedCount: 0, + count: drainLength, chunkSize: chunkSize - ) { - guard i < drainLength else { return nil } - defer { i += 1 } - return tracker.instance(for: i) + ) { i in + tracker.instance(for: i) } s.insert(maximumCount: maxCount, from: &drain) expectConsistentSet(s) let expectedCount = Swift.min(maxCount, drainLength) expectEqual(s.count, expectedCount) - expectEqual(i, expectedCount) } } } diff --git a/Tests/_CollectionsTestSupport/MinimalTypes/CustomDrain.swift b/Tests/_CollectionsTestSupport/MinimalTypes/CustomDrain.swift index 8fcbd62b..7eb616ed 100644 --- a/Tests/_CollectionsTestSupport/MinimalTypes/CustomDrain.swift +++ b/Tests/_CollectionsTestSupport/MinimalTypes/CustomDrain.swift @@ -23,22 +23,24 @@ import ContainersPreview @available(SwiftStdlib 5.0, *) package struct CustomDrain: ~Copyable { - package let underestimatedCount: Int + package let count: Int package let _chunkSize: Int - package let _generator: () -> Element? + package let _generator: (Int) -> Element package var _buffer: RigidArray package var _remainder: Int + package var _position: Int package init( - underestimatedCount: Int = 0, + count: Int = 0, chunkSize: Int, - generatingWith generator: @escaping () -> Element? + generatingWith generator: @escaping (Int) -> Element ) { - self.underestimatedCount = underestimatedCount + self.count = count self._chunkSize = chunkSize self._generator = generator self._buffer = .init(capacity: _chunkSize) self._remainder = _chunkSize + self._position = 0 } } @@ -53,7 +55,9 @@ extension CustomDrain: Drain where Element: ~Copyable { let c = Swift.min(maximumCount, _remainder) _remainder -= c for _ in 0 ..< c { - guard let next = _generator() else { break } + guard _position < count else { break } + let next = _generator(_position) + _position += 1 _buffer.append(next) } return _buffer._consumeAll() From 130d235b28e8f03c005b45a0fc85ba42c23af412 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 18 Jun 2026 13:27:08 -0700 Subject: [PATCH 06/50] Resolve issues after rebase --- .../ContainersPreview/Types/InputSpan.swift | 18 --------- .../OutputSpan+Extras.swift | 1 + .../Span+Extras.swift | 17 +++++++++ Xcode/Collections.xcodeproj/project.pbxproj | 38 +++++++++---------- 4 files changed, 35 insertions(+), 39 deletions(-) diff --git a/Sources/ContainersPreview/Types/InputSpan.swift b/Sources/ContainersPreview/Types/InputSpan.swift index 2f4b6c48..5209b852 100644 --- a/Sources/ContainersPreview/Types/InputSpan.swift +++ b/Sources/ContainersPreview/Types/InputSpan.swift @@ -560,22 +560,4 @@ internal func withTemporaryInputSpan } } -@available(SwiftStdlib 5.0, *) -extension OutputSpan where Element: ~Copyable { - @_alwaysEmitIntoClient - @_lifetime(self: copy self) - package mutating func _consumeAll( - consumingWith consumer: (inout InputSpan) -> Void - ) { - self.withUnsafeMutableBufferPointer { buffer, count in - var span = InputSpan( - buffer: buffer._extracting(first: count), - initializedCount: count) - consumer(&span) - _ = consume span - count = 0 - } - } -} - #endif diff --git a/Sources/InternalCollectionsUtilities/OutputSpan+Extras.swift b/Sources/InternalCollectionsUtilities/OutputSpan+Extras.swift index 2c2e403c..dd2396d9 100644 --- a/Sources/InternalCollectionsUtilities/OutputSpan+Extras.swift +++ b/Sources/InternalCollectionsUtilities/OutputSpan+Extras.swift @@ -155,6 +155,7 @@ extension OutputSpan where Element: ~Copyable { } #if UnstableContainersPreview + @available(SwiftStdlib 5.0, *) extension OutputSpan where Element: ~Copyable { @_alwaysEmitIntoClient diff --git a/Sources/InternalCollectionsUtilities/Span+Extras.swift b/Sources/InternalCollectionsUtilities/Span+Extras.swift index c10b26e8..a7742688 100644 --- a/Sources/InternalCollectionsUtilities/Span+Extras.swift +++ b/Sources/InternalCollectionsUtilities/Span+Extras.swift @@ -78,6 +78,22 @@ extension Span where Element: Equatable /* & ~Copyable */ { } #endif +#if compiler(>=6.4) && UnstableContainersPreview +@available(SwiftStdlib 5.0, *) +extension Span where Element: Hashable & ~Copyable { + @_alwaysEmitIntoClient + package func _hashContents(into hasher: inout Hasher) { + // Note: no discriminating combine call -- caller is expected to do that + // separately when needed. + var i = 0 + while i < self.count { + hasher.combine(self[unchecked: i]) + i &+= 1 + } + + } +} +#else @available(SwiftStdlib 5.0, *) extension Span where Element: Hashable /* & ~Copyable */ { @_alwaysEmitIntoClient @@ -92,5 +108,6 @@ extension Span where Element: Hashable /* & ~Copyable */ { } } +#endif #endif diff --git a/Xcode/Collections.xcodeproj/project.pbxproj b/Xcode/Collections.xcodeproj/project.pbxproj index 7abbd21a..0b2d55c4 100644 --- a/Xcode/Collections.xcodeproj/project.pbxproj +++ b/Xcode/Collections.xcodeproj/project.pbxproj @@ -11,8 +11,6 @@ 7D2A77262F27F1D1005780C7 /* Span+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77252F27F1D1005780C7 /* Span+Extras.swift */; }; 7D2A77392F27F1E4005780C7 /* UniqueBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77332F27F1E4005780C7 /* UniqueBox.swift */; }; 7D2A773A2F27F1E4005780C7 /* Drain.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A772F2F27F1E4005780C7 /* Drain.swift */; }; - 7D2A773C2F27F1E4005780C7 /* TemporaryAllocation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77282F27F1E4005780C7 /* TemporaryAllocation.swift */; }; - 7D2A77422F27F1E4005780C7 /* OutputSpan+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77272F27F1E4005780C7 /* OutputSpan+Extras.swift */; }; 7D2A77432F27F1E4005780C7 /* Shared.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77362F27F1E4005780C7 /* Shared.swift */; }; 7D2A77442F27F1E4005780C7 /* InputSpan.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77352F27F1E4005780C7 /* InputSpan.swift */; }; 7D2A77452F27F1E4005780C7 /* Producer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77302F27F1E4005780C7 /* Producer.swift */; }; @@ -132,6 +130,9 @@ 7D57EDE72F6491400029D5E3 /* Producer+Filter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D57EDE62F64913C0029D5E3 /* Producer+Filter.swift */; }; 7D57EDEB2F649CF40029D5E3 /* Container+Filter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D57EDEA2F649CEF0029D5E3 /* Container+Filter.swift */; }; 7D57EDED2F649F0F0029D5E3 /* ContainerIterator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D57EDEC2F649F0C0029D5E3 /* ContainerIterator.swift */; }; + 7D59D05C2FE48B89005B5097 /* Optional+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D59D0592FE48B89005B5097 /* Optional+Extras.swift */; }; + 7D59D05D2FE48B89005B5097 /* OutputSpan+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D59D05A2FE48B89005B5097 /* OutputSpan+Extras.swift */; }; + 7D59D05E2FE48B89005B5097 /* TemporaryAllocation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D59D05B2FE48B89005B5097 /* TemporaryAllocation.swift */; }; 7D7246872F3D9DDB00112FD0 /* _HTable+Iteration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D7246802F3D9DDB00112FD0 /* _HTable+Iteration.swift */; }; 7D7246882F3D9DDB00112FD0 /* RigidDictionary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D7246832F3D9DDB00112FD0 /* RigidDictionary.swift */; }; 7D7246892F3D9DDB00112FD0 /* _HTable+Find.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D72467E2F3D9DDB00112FD0 /* _HTable+Find.swift */; }; @@ -209,7 +210,6 @@ 7DC037C12FE3492D00CF0CB8 /* IterableIteratorProtocol+Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037B42FE3492D00CF0CB8 /* IterableIteratorProtocol+Map.swift */; }; 7DC037C32FE34B2800CF0CB8 /* Heap+Testing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037C22FE34B2800CF0CB8 /* Heap+Testing.swift */; }; 7DC037C52FE3717A00CF0CB8 /* IterableIteratorProtocol+MapError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037C42FE3717200CF0CB8 /* IterableIteratorProtocol+MapError.swift */; }; - 7DC037C72FE378B300CF0CB8 /* Optional+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037C62FE378B300CF0CB8 /* Optional+Extras.swift */; }; 7DC037C92FE3792300CF0CB8 /* MutableRef.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037C82FE3792300CF0CB8 /* MutableRef.swift */; }; 7DC85F8D2F3FDC91004A4E3D /* String+Padding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC85F8C2F3FDC82004A4E3D /* String+Padding.swift */; }; 7DC85F8F2F43D065004A4E3D /* RigidDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC85F8E2F43D05F004A4E3D /* RigidDictionaryTests.swift */; }; @@ -618,8 +618,6 @@ 7D24E98E2FAD53E1005A55EB /* HEADER.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HEADER.swift; sourceTree = ""; }; 7D24E98F2FAD53E1005A55EB /* test_formatters.py */ = {isa = PBXFileReference; lastKnownFileType = text.script.python; path = test_formatters.py; sourceTree = ""; }; 7D2A77252F27F1D1005780C7 /* Span+Extras.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Span+Extras.swift"; sourceTree = ""; }; - 7D2A77272F27F1E4005780C7 /* OutputSpan+Extras.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "OutputSpan+Extras.swift"; sourceTree = ""; }; - 7D2A77282F27F1E4005780C7 /* TemporaryAllocation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TemporaryAllocation.swift; sourceTree = ""; }; 7D2A772F2F27F1E4005780C7 /* Drain.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Drain.swift; sourceTree = ""; }; 7D2A77302F27F1E4005780C7 /* Producer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Producer.swift; sourceTree = ""; }; 7D2A77332F27F1E4005780C7 /* UniqueBox.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UniqueBox.swift; sourceTree = ""; }; @@ -743,6 +741,9 @@ 7D57EDE62F64913C0029D5E3 /* Producer+Filter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Producer+Filter.swift"; sourceTree = ""; }; 7D57EDEA2F649CEF0029D5E3 /* Container+Filter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Container+Filter.swift"; sourceTree = ""; }; 7D57EDEC2F649F0C0029D5E3 /* ContainerIterator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContainerIterator.swift; sourceTree = ""; }; + 7D59D0592FE48B89005B5097 /* Optional+Extras.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Optional+Extras.swift"; sourceTree = ""; }; + 7D59D05A2FE48B89005B5097 /* OutputSpan+Extras.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "OutputSpan+Extras.swift"; sourceTree = ""; }; + 7D59D05B2FE48B89005B5097 /* TemporaryAllocation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TemporaryAllocation.swift; sourceTree = ""; }; 7D5A64D229CCE8CC00CB2595 /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; 7D5A64D329CCEE9A00CB2595 /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; 7D5A64D829CCF0FE00CB2595 /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; @@ -826,7 +827,6 @@ 7DC037B62FE3492D00CF0CB8 /* IterableIteratorProtocol+SpanwiseZip.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "IterableIteratorProtocol+SpanwiseZip.swift"; sourceTree = ""; }; 7DC037C22FE34B2800CF0CB8 /* Heap+Testing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Heap+Testing.swift"; sourceTree = ""; }; 7DC037C42FE3717200CF0CB8 /* IterableIteratorProtocol+MapError.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "IterableIteratorProtocol+MapError.swift"; sourceTree = ""; }; - 7DC037C62FE378B300CF0CB8 /* Optional+Extras.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Optional+Extras.swift"; sourceTree = ""; }; 7DC037C82FE3792300CF0CB8 /* MutableRef.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MutableRef.swift; sourceTree = ""; }; 7DC85F8C2F3FDC82004A4E3D /* String+Padding.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "String+Padding.swift"; sourceTree = ""; }; 7DC85F8E2F43D05F004A4E3D /* RigidDictionaryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RigidDictionaryTests.swift; sourceTree = ""; }; @@ -1306,16 +1306,6 @@ path = Debugger; sourceTree = ""; }; - 7D2A77292F27F1E4005780C7 /* Extensions */ = { - isa = PBXGroup; - children = ( - 7DC037C62FE378B300CF0CB8 /* Optional+Extras.swift */, - 7D2A77272F27F1E4005780C7 /* OutputSpan+Extras.swift */, - 7D2A77282F27F1E4005780C7 /* TemporaryAllocation.swift */, - ); - path = Extensions; - sourceTree = ""; - }; 7D2A77312F27F1E4005780C7 /* Protocols */ = { isa = PBXGroup; children = ( @@ -1462,7 +1452,6 @@ 7D48BCCE2E51524200D7F6F7 /* ContainersPreview */ = { isa = PBXGroup; children = ( - 7D2A77292F27F1E4005780C7 /* Extensions */, 7D2A77312F27F1E4005780C7 /* Protocols */, 7D2A77372F27F1E4005780C7 /* Types */, 7D48BCC92E51524200D7F6F7 /* CMakeLists.txt */, @@ -1952,19 +1941,22 @@ children = ( 7DEBDAE229CBEE5300ADC226 /* IntegerTricks */, 7DEBDADA29CBEE5300ADC226 /* UnsafeBitSet */, - 7DE91F2E29CA70F3004483EB /* CMakeLists.txt */, 7DE91F3029CA70F3004483EB /* _SortedCollection.swift */, 7DE91F3829CA70F3004483EB /* _UniqueCollection.swift */, 7DAD89A82E8B09EC00DD5786 /* Debugging.swift */, 7DAD89A92E8B09EC00DD5786 /* Descriptions.swift */, 7DAD89AA2E8B09EC00DD5786 /* LifetimeOverride.swift */, + 7D59D0592FE48B89005B5097 /* Optional+Extras.swift */, + 7D59D05A2FE48B89005B5097 /* OutputSpan+Extras.swift */, 7DAD89AB2E8B09EC00DD5786 /* RandomAccessCollection+Offsets.swift */, 7D2A77252F27F1D1005780C7 /* Span+Extras.swift */, 7DC85F8C2F3FDC82004A4E3D /* String+Padding.swift */, + 7D59D05B2FE48B89005B5097 /* TemporaryAllocation.swift */, 7DAD89AC2E8B09EC00DD5786 /* UnsafeBufferPointer+Extras.swift */, 7DAD89AD2E8B09EC00DD5786 /* UnsafeMutableBufferPointer+Extras.swift */, 7DAD89AE2E8B09EC00DD5786 /* UnsafeMutableRawBufferPointer+Extras.swift */, 7DAD89AF2E8B09EC00DD5786 /* UnsafeRawBufferPointer+Extras.swift */, + 7DE91F2E29CA70F3004483EB /* CMakeLists.txt */, ); path = InternalCollectionsUtilities; sourceTree = ""; @@ -2695,7 +2687,6 @@ 7D2A77972F27F2BF005780C7 /* Deque+Testing.swift in Sources */, 7D2A77982F27F2BF005780C7 /* RigidDeque+Replacements.swift in Sources */, 7D7246872F3D9DDB00112FD0 /* _HTable+Iteration.swift in Sources */, - 7DC037C72FE378B300CF0CB8 /* Optional+Extras.swift in Sources */, 7D7246882F3D9DDB00112FD0 /* RigidDictionary.swift in Sources */, 7D7246892F3D9DDB00112FD0 /* _HTable+Find.swift in Sources */, 7D72468A2F3D9DDB00112FD0 /* _HTable.swift in Sources */, @@ -2955,6 +2946,9 @@ 7DE9214729CA70F4004483EB /* _HashNode+Primitive Replacement.swift in Sources */, 7DE9201229CA70F3004483EB /* OrderedDictionary+Elements.SubSequence.swift in Sources */, 7DE9204429CA70F3004483EB /* _HashTable.swift in Sources */, + 7D59D05C2FE48B89005B5097 /* Optional+Extras.swift in Sources */, + 7D59D05D2FE48B89005B5097 /* OutputSpan+Extras.swift in Sources */, + 7D59D05E2FE48B89005B5097 /* TemporaryAllocation.swift in Sources */, 7DE9206529CA70F4004483EB /* BigString+Ingester.swift in Sources */, 7DE9209129CA70F4004483EB /* Rope+_UnsafeHandle.swift in Sources */, 7DC037C32FE34B2800CF0CB8 /* Heap+Testing.swift in Sources */, @@ -2971,9 +2965,7 @@ 7D2A77392F27F1E4005780C7 /* UniqueBox.swift in Sources */, 7D2A773A2F27F1E4005780C7 /* Drain.swift in Sources */, 7D479CC32F46D19600A8CB59 /* RigidSet+Resizing.swift in Sources */, - 7D2A773C2F27F1E4005780C7 /* TemporaryAllocation.swift in Sources */, 7D57A2D02F353946002543BD /* RigidArray+Deprecated.swift in Sources */, - 7D2A77422F27F1E4005780C7 /* OutputSpan+Extras.swift in Sources */, 7D2A77432F27F1E4005780C7 /* Shared.swift in Sources */, 7D2A77442F27F1E4005780C7 /* InputSpan.swift in Sources */, 7D2A77452F27F1E4005780C7 /* Producer.swift in Sources */, @@ -3258,6 +3250,8 @@ isa = XCBuildConfiguration; baseConfigurationReference = 7DEBDB9929CCE4A600ADC226 /* Collections.xcconfig */; buildSettings = { + MACOSX_DEPLOYMENT_TARGET = "$(RECOMMENDED_MACOSX_DEPLOYMENT_TARGET)"; + WATCHOS_DEPLOYMENT_TARGET = "$(RECOMMENDED_WATCHOS_DEPLOYMENT_TARGET)"; }; name = Debug; }; @@ -3265,6 +3259,8 @@ isa = XCBuildConfiguration; baseConfigurationReference = 7DEBDB9929CCE4A600ADC226 /* Collections.xcconfig */; buildSettings = { + MACOSX_DEPLOYMENT_TARGET = "$(RECOMMENDED_MACOSX_DEPLOYMENT_TARGET)"; + WATCHOS_DEPLOYMENT_TARGET = "$(RECOMMENDED_WATCHOS_DEPLOYMENT_TARGET)"; }; name = Release; }; From 5df2bf9ec346a607e0dd5a677e475a998b9aac96 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 18 Jun 2026 14:27:04 -0700 Subject: [PATCH 07/50] [Xcode] Clean up supported platforms & deployment configurations --- Xcode/Collections.xcconfig | 18 ++++++++++++------ Xcode/Collections.xcodeproj/project.pbxproj | 4 ---- Xcode/CollectionsTests.xcconfig | 16 +++++++++++----- 3 files changed, 23 insertions(+), 15 deletions(-) diff --git a/Xcode/Collections.xcconfig b/Xcode/Collections.xcconfig index 0a17e877..a5d03d3a 100644 --- a/Xcode/Collections.xcconfig +++ b/Xcode/Collections.xcconfig @@ -12,15 +12,21 @@ PRODUCT_NAME = Collections PRODUCT_BUNDLE_IDENTIFIER = org.swift.Collections -SUPPORTED_PLATFORMS = macosx iphoneos iphonesimulator watchos watchsimulator appletvos appletvsimulator +SUPPORTED_PLATFORMS = $(AVAILABLE_PLATFORMS) ARCHS = $(ARCHS_STANDARD) -MACOSX_DEPLOYMENT_TARGET = 12.0 -IPHONEOS_DEPLOYMENT_TARGET = 15.0 -WATCHOS_DEPLOYMENT_TARGET = 8.0 -TVOS_DEPLOYMENT_TARGET = 15.0 +IPHONEOS_DEPLOYMENT_TARGET = $(RECOMMENDED_IPHONEOS_DEPLOYMENT_TARGET) +MACOSX_DEPLOYMENT_TARGET = $(RECOMMENDED_MACOSX_DEPLOYMENT_TARGET) +TVOS_DEPLOYMENT_TARGET = $(RECOMMENDED_TVOS_DEPLOYMENT_TARGET) +WATCHOS_DEPLOYMENT_TARGET = $(RECOMMENDED_WATCHOS_DEPLOYMENT_TARGET) +XROS_DEPLOYMENT_TARGET = $(RECOMMENDED_XROS_DEPLOYMENT_TARGET) +TARGETED_DEVICE_FAMILY = 1,2,3,4,5,6,7 -MARKETING_VERSION = 1.1 +SUPPORTS_MACCATALYST = YES +SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = YES +SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = YES + +MARKETING_VERSION = 1.7 CURRENT_PROJECT_VERSION = 1 VERSIONING_SYSTEM = apple-generic diff --git a/Xcode/Collections.xcodeproj/project.pbxproj b/Xcode/Collections.xcodeproj/project.pbxproj index 0b2d55c4..58a30903 100644 --- a/Xcode/Collections.xcodeproj/project.pbxproj +++ b/Xcode/Collections.xcodeproj/project.pbxproj @@ -3250,8 +3250,6 @@ isa = XCBuildConfiguration; baseConfigurationReference = 7DEBDB9929CCE4A600ADC226 /* Collections.xcconfig */; buildSettings = { - MACOSX_DEPLOYMENT_TARGET = "$(RECOMMENDED_MACOSX_DEPLOYMENT_TARGET)"; - WATCHOS_DEPLOYMENT_TARGET = "$(RECOMMENDED_WATCHOS_DEPLOYMENT_TARGET)"; }; name = Debug; }; @@ -3259,8 +3257,6 @@ isa = XCBuildConfiguration; baseConfigurationReference = 7DEBDB9929CCE4A600ADC226 /* Collections.xcconfig */; buildSettings = { - MACOSX_DEPLOYMENT_TARGET = "$(RECOMMENDED_MACOSX_DEPLOYMENT_TARGET)"; - WATCHOS_DEPLOYMENT_TARGET = "$(RECOMMENDED_WATCHOS_DEPLOYMENT_TARGET)"; }; name = Release; }; diff --git a/Xcode/CollectionsTests.xcconfig b/Xcode/CollectionsTests.xcconfig index 704c2efa..de6a94d7 100644 --- a/Xcode/CollectionsTests.xcconfig +++ b/Xcode/CollectionsTests.xcconfig @@ -12,13 +12,19 @@ PRODUCT_NAME = CollectionsTests PRODUCT_BUNDLE_IDENTIFIER = org.swift.CollectionsTests -SUPPORTED_PLATFORMS = macosx iphoneos iphonesimulator watchos watchsimulator appletvos appletvsimulator +SUPPORTED_PLATFORMS = $(AVAILABLE_PLATFORMS) ARCHS = $(ARCHS_STANDARD) -MACOSX_DEPLOYMENT_TARGET = 12.0 -IPHONEOS_DEPLOYMENT_TARGET = 15.0 -WATCHOS_DEPLOYMENT_TARGET = 8.0 -TVOS_DEPLOYMENT_TARGET = 15.0 +IPHONEOS_DEPLOYMENT_TARGET = $(RECOMMENDED_IPHONEOS_DEPLOYMENT_TARGET) +MACOSX_DEPLOYMENT_TARGET = $(RECOMMENDED_MACOSX_DEPLOYMENT_TARGET) +TVOS_DEPLOYMENT_TARGET = $(RECOMMENDED_TVOS_DEPLOYMENT_TARGET) +WATCHOS_DEPLOYMENT_TARGET = $(RECOMMENDED_WATCHOS_DEPLOYMENT_TARGET) +XROS_DEPLOYMENT_TARGET = $(RECOMMENDED_XROS_DEPLOYMENT_TARGET) +TARGETED_DEVICE_FAMILY = 1,2,3,4,5,6,7 + +SUPPORTS_MACCATALYST = YES +SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = YES +SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = YES CURRENT_PROJECT_VERSION = 1 MARKETING_VERSION = 1.0 From 1fc82e2bc9a672f75ed27f18d229dc722ec0b225 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 18 Jun 2026 14:38:52 -0700 Subject: [PATCH 08/50] [Xcode] Clean up supported platforms & deployment configurations --- Xcode/Collections.xcodeproj/project.pbxproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Xcode/Collections.xcodeproj/project.pbxproj b/Xcode/Collections.xcodeproj/project.pbxproj index 58a30903..ae8ff6ec 100644 --- a/Xcode/Collections.xcodeproj/project.pbxproj +++ b/Xcode/Collections.xcodeproj/project.pbxproj @@ -2572,7 +2572,7 @@ attributes = { BuildIndependentTargetsInParallel = 1; LastSwiftUpdateCheck = 1430; - LastUpgradeCheck = 2640; + LastUpgradeCheck = 2700; TargetAttributes = { 7DE91B2529CA6721004483EB = { CreatedOnToolsVersion = 14.3; From 22a94a9756b248753f0efad2a8380de450c486c4 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 18 Jun 2026 15:31:37 -0700 Subject: [PATCH 09/50] [ContainersPreview] Have RangeExpression2 refine RangeExpression --- .../Protocols/Container/RangeExpression2.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Sources/ContainersPreview/Protocols/Container/RangeExpression2.swift b/Sources/ContainersPreview/Protocols/Container/RangeExpression2.swift index 2814339b..c847d61d 100644 --- a/Sources/ContainersPreview/Protocols/Container/RangeExpression2.swift +++ b/Sources/ContainersPreview/Protocols/Container/RangeExpression2.swift @@ -16,14 +16,14 @@ // FIXME: Figure out if it would be possible to add the container-based // `relative(to:)` to the existing `RangeExpression`. @available(SwiftStdlib 5.0, *) -public protocol RangeExpression2 { - associatedtype Bound: Comparable +public protocol RangeExpression2: RangeExpression { + override associatedtype Bound: Comparable func relative( to container: borrowing C ) -> Range where C.Index == Bound, C.Element: ~Copyable - func contains(_ element: Bound) -> Bool + override func contains(_ element: Bound) -> Bool } @available(SwiftStdlib 5.0, *) From e8b09ade2519e4fb9bbaff1798c146c9348fb90f Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 22 Jun 2026 20:10:22 -0700 Subject: [PATCH 10/50] Add subscript requirements to [Mutable]Container with borrow/mutate accessors --- Package.swift | 2 +- .../RigidArray/RigidArray+Container.swift | 12 +++++++----- .../RigidSet/RigidSet+Index.swift | 6 +++--- .../UniqueArray/UniqueArray+Container.swift | 9 +++++---- .../UniqueSet/UniqueSet+Index.swift | 6 ++---- .../Protocols/Container/Container.swift | 14 ++++++++++++-- .../Protocols/Container/MutableContainer.swift | 8 +++++++- .../ContainersPreview/Types/InputSpan.swift | 18 ++++++++++-------- .../DequeModule/RigidDeque/RigidDeque.swift | 11 ++++++----- .../DequeModule/UniqueDeque/UniqueDeque.swift | 13 +++++-------- Xcode/Shared.xcconfig | 1 + 11 files changed, 59 insertions(+), 41 deletions(-) diff --git a/Package.swift b/Package.swift index 263a4918..44656da0 100644 --- a/Package.swift +++ b/Package.swift @@ -116,7 +116,7 @@ let extraSettings: [SwiftSetting] = [ .enableExperimentalFeature("AddressableParameters"), .enableExperimentalFeature("AddressableTypes"), .enableExperimentalFeature("SuppressedAssociatedTypesWithDefaults"), // Requires Swift 6.4 - + .enableExperimentalFeature("BorrowAndMutateAccessors"), // Note: if you touch these, please make sure to also update the similar lists in // CMakeLists.txt and Xcode/Shared.xcconfig. ] diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Container.swift b/Sources/BasicContainers/RigidArray/RigidArray+Container.swift index 3ae8cc59..c46aa70e 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Container.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Container.swift @@ -41,7 +41,7 @@ extension RigidArray: BidirectionalContainer where Element: ~Copyable {} extension RigidArray: RandomAccessContainer where Element: ~Copyable {} #if compiler(>=6.4) -@available(SwiftStdlib 6.4, *) +@available(SwiftStdlib 5.0, *) extension RigidArray: MutableContainer where Element: ~Copyable {} @available(SwiftStdlib 6.4, *) @@ -153,12 +153,14 @@ extension RigidArray where Element: ~Copyable { @inlinable public subscript(position: Int) -> Element { @inline(__always) - unsafeAddress { - _ptr(to: position) + @_unsafeSelfDependentResult + borrow { + _ptr(to: position).pointee } @inline(__always) - unsafeMutableAddress { - _mutablePtr(to: position) + @_unsafeSelfDependentResult + mutate { + &_mutablePtr(to: position).pointee } } } diff --git a/Sources/BasicContainers/RigidSet/RigidSet+Index.swift b/Sources/BasicContainers/RigidSet/RigidSet+Index.swift index 5fe511f1..2ee7675a 100644 --- a/Sources/BasicContainers/RigidSet/RigidSet+Index.swift +++ b/Sources/BasicContainers/RigidSet/RigidSet+Index.swift @@ -100,10 +100,10 @@ extension RigidSet where Element: ~Copyable { @inlinable public subscript(index: Index) -> Element { - // FIXME: Use borrow accessor here - unsafeAddress { + @_unsafeSelfDependentResult + borrow { _checkItemIndex(index) - return .init(_memberPtr(at: index._bucket)) + return _memberPtr(at: index._bucket).pointee } } } diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift index c314324e..0483039b 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift @@ -114,12 +114,13 @@ extension UniqueArray where Element: ~Copyable { @inlinable public subscript(position: Int) -> Element { @inline(__always) - unsafeAddress { - _storage._ptr(to: position) + borrow { + _storage[position] } @inline(__always) - unsafeMutableAddress { - _storage._mutablePtr(to: position) + @_unsafeSelfDependentResult // FIXME: Why is this necessary? + mutate { + &_storage[position] } } } diff --git a/Sources/BasicContainers/UniqueSet/UniqueSet+Index.swift b/Sources/BasicContainers/UniqueSet/UniqueSet+Index.swift index 4dc1f451..2d48fb6d 100644 --- a/Sources/BasicContainers/UniqueSet/UniqueSet+Index.swift +++ b/Sources/BasicContainers/UniqueSet/UniqueSet+Index.swift @@ -59,10 +59,8 @@ extension UniqueSet where Element: ~Copyable { @inlinable public subscript(index: Index) -> Element { - // FIXME: Use borrow accessor here - unsafeAddress { - _checkItemIndex(index) - return .init(_storage._memberPtr(at: index._bucket)) + borrow { + _storage[index] } } } diff --git a/Sources/ContainersPreview/Protocols/Container/Container.swift b/Sources/ContainersPreview/Protocols/Container/Container.swift index 199aa591..e4d0e772 100644 --- a/Sources/ContainersPreview/Protocols/Container/Container.swift +++ b/Sources/ContainersPreview/Protocols/Container/Container.swift @@ -95,6 +95,18 @@ public protocol Container: /// - Returns: The distance between `start` and `end`. func distance(from start: Index, to end: Index) -> Int + /// Accesses the element at the specified position. + /// + /// You can subscript a collection with any valid index other than the + /// collection’s end index. The end index refers to the position one past the + /// last element of a collection, so it doesn’t correspond with an element. + /// + /// - Parameter position: The position of the element to access. + /// `position` must be a valid index of the container that is not equal + /// to the `endIndex` property. + /// - Complexity: O(1) + subscript(index: Index) -> Element { borrow } + /// Return a span over the container's storage that begins with the element at /// the given index, and extends to the end of the contiguous storage chunk /// that contains it, but no more than `maximumCount` items. @@ -165,8 +177,6 @@ public protocol Container: @_lifetime(borrow self) func nextSpan(after index: inout Index, maximumCount: Int) -> Span - // subscript(index: Index) -> Element { borrow } - /// Return the nearest valid index in this container less than or equal to /// the given index value, which must be valid in at least one view of self. /// diff --git a/Sources/ContainersPreview/Protocols/Container/MutableContainer.swift b/Sources/ContainersPreview/Protocols/Container/MutableContainer.swift index 06516f54..33bbc89c 100644 --- a/Sources/ContainersPreview/Protocols/Container/MutableContainer.swift +++ b/Sources/ContainersPreview/Protocols/Container/MutableContainer.swift @@ -19,7 +19,13 @@ public protocol MutableContainer: where Element: ~Copyable { - // subscript(index: Index) -> Element { borrow mutate } + /// Accesses the element at the specified position. + /// + /// - Parameter position: The position of the element to access. + /// `position` must be a valid index of the container that is not equal + /// to the `endIndex` property. + /// - Complexity: O(1) + subscript(index: Index) -> Element { borrow mutate } @_lifetime(&self) mutating func nextMutableSpan( diff --git a/Sources/ContainersPreview/Types/InputSpan.swift b/Sources/ContainersPreview/Types/InputSpan.swift index 5209b852..74afceb6 100644 --- a/Sources/ContainersPreview/Types/InputSpan.swift +++ b/Sources/ContainersPreview/Types/InputSpan.swift @@ -62,7 +62,7 @@ extension InputSpan where Element: ~Copyable { internal func _start() -> UnsafeMutableRawPointer { unsafe _pointer.unsafelyUnwrapped } - + @unsafe @_alwaysEmitIntoClient @_transparent @@ -177,7 +177,7 @@ extension InputSpan where Element: ~Copyable { capacity = buffer.count _count = initializedCount } - + @unsafe @_alwaysEmitIntoClient @_lifetime(borrow buffer) @@ -244,15 +244,17 @@ extension InputSpan where Element: ~Copyable { /// - Complexity: O(1) @_alwaysEmitIntoClient public subscript(_ index: Index) -> Element { - unsafeAddress { + @_unsafeSelfDependentResult + borrow { precondition(indices.contains(index), "Index out of bounds") - return unsafe UnsafePointer(_unsafeAddressOfElement(uncheckedOffset: index)) + return unsafe _unsafeAddressOfElement(uncheckedOffset: index).pointee } + @_unsafeSelfDependentResult @_lifetime(self: copy self) - unsafeMutableAddress { + mutate { precondition(indices.contains(index), "Index out of bounds") - return unsafe _unsafeAddressOfElement(uncheckedOffset: index) + return unsafe &_unsafeAddressOfElement(uncheckedOffset: index).pointee } } @@ -346,7 +348,7 @@ extension InputSpan where Element: ~Copyable { } _count &-= k } - + /// Removes and returns the first element of this input span, if it exists. /// /// - Returns: The first element of the original span if it wasn't empty; @@ -533,7 +535,7 @@ extension InputSpan where Element: ~Copyable { public mutating func consumePrefix(upTo n: Int) -> InputSpan { precondition(n >= 0, "Cannot consume a negative number of elements") let c = Swift.min(n, self.count) - + let buffer = unsafe _unsafeRawAddressOfSlot( uncheckedOffset: 0 ).withMemoryRebound(to: Element.self, capacity: c) { start in diff --git a/Sources/DequeModule/RigidDeque/RigidDeque.swift b/Sources/DequeModule/RigidDeque/RigidDeque.swift index 16c81eb3..a7e90e53 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque.swift @@ -262,20 +262,21 @@ extension RigidDeque where Element: ~Copyable { @_alwaysEmitIntoClient public subscript(position: Int) -> Element { - // FIXME: Replace with borrow/mutate accessors @inline(__always) @_transparent - unsafeAddress { + @_unsafeSelfDependentResult + borrow { _checkItemIndex(position) let slot = _handle.slot(forOffset: position) - return _handle.ptr(at: slot) + return _handle.ptr(at: slot).pointee } @inline(__always) @_transparent - unsafeMutableAddress { + @_unsafeSelfDependentResult + mutate { _checkItemIndex(position) let slot = _handle.slot(forOffset: position) - return _handle.mutablePtr(at: slot) + return &_handle.mutablePtr(at: slot).pointee } } } diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque.swift index 9f5d8c19..5d26bc64 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque.swift @@ -198,17 +198,14 @@ extension UniqueDeque where Element: ~Copyable { public subscript(position: Int) -> Element { @inline(__always) @_transparent - unsafeAddress { - precondition(position >= 0 && position < count, "Index out of bounds") - let slot = _storage._handle.slot(forOffset: position) - return _storage._handle.ptr(at: slot) + borrow { + _storage[position] } @inline(__always) @_transparent - unsafeMutableAddress { - precondition(position >= 0 && position < count, "Index out of bounds") - let slot = _storage._handle.slot(forOffset: position) - return _storage._handle.mutablePtr(at: slot) + @_unsafeSelfDependentResult // FIXME: Why is this necessary? + mutate { + &_storage[position] } } } diff --git a/Xcode/Shared.xcconfig b/Xcode/Shared.xcconfig index 51643e43..dd340ff7 100644 --- a/Xcode/Shared.xcconfig +++ b/Xcode/Shared.xcconfig @@ -22,6 +22,7 @@ OTHER_SWIFT_FLAGS = $(inherited) \ -enable-experimental-feature AddressableParameters \ -enable-experimental-feature AddressableTypes \ -enable-experimental-feature SuppressedAssociatedTypesWithDefaults \ + -enable-experimental-feature BorrowAndMutateAccessors \ -enable-experimental-feature "AvailabilityMacro=SwiftStdlib 5.0: macOS 10.14.4, iOS 12.2, watchOS 5.2, tvOS 12.2" \ -enable-experimental-feature "AvailabilityMacro=SwiftStdlib 5.1: macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0" \ -enable-experimental-feature "AvailabilityMacro=SwiftStdlib 5.6: macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4" \ From 250af8730811076965e6879b0d6de31ae2369223 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 23 Jun 2026 16:55:53 -0700 Subject: [PATCH 11/50] [ContainersPreview] Redeclare Container requirements in refining protocols Use `override`/`@_nonoverride` to help associated type inference and to allow diverging implementations of select requirements in BidirectionalContainer, RandomAccessContainer, and MutableContainer. --- .../Container/BidirectionalContainer.swift | 42 +++++++++++++ .../Container/MutableContainer.swift | 63 +++++++++++++++++++ .../Container/RandomAccessContainer.swift | 38 ++++++++++- 3 files changed, 142 insertions(+), 1 deletion(-) diff --git a/Sources/ContainersPreview/Protocols/Container/BidirectionalContainer.swift b/Sources/ContainersPreview/Protocols/Container/BidirectionalContainer.swift index 332c97ff..0a4b54bc 100644 --- a/Sources/ContainersPreview/Protocols/Container/BidirectionalContainer.swift +++ b/Sources/ContainersPreview/Protocols/Container/BidirectionalContainer.swift @@ -17,11 +17,53 @@ public protocol BidirectionalContainer: Container, ~Copyable, ~Escapable where Element: ~Copyable, Index: Comparable { + override associatedtype Element: ~Copyable + override associatedtype Index + + // Note: Some `Container` requirements are redeclared as `override`s to help + // associated type inference; others are kept separate with `@_nonoverride`. + // + // @_nonoverride creates separate witness table entries, allowing divergent + // implementations in conditional conformances. This enables conforming types + // to provide distinct implementations depending on whether the caller is + // generic over `Container` or `BidirectionalContainer`. + // + // (Unfortunately, neither `override` nor `@_nonoverride` allows callers + // that are generic over `Container` to automatically dispatch + // to a more constrained bidirectional implementation variant. Still, at least + // `@_nonoverride` enables more refined implementations to take effect + // when the caller is explicitly generic over `BidirectionalContainer`.) + // + // `@_nonoverride` should be used on requirements with new semantic + // constraints in refining protocols. + // + // Collection types usually do not come with conditional conformances to + // refining collection protocols (as the resulting behavior can be quite + // confusing), so the separate witness entries rarely if ever get exercised + // in practice. I don't expect things would be different with Container. + // + // FIXME: Consider avoiding using `@_nonoverride`, reducing witness sizes. + + func index(before i: Index) -> Index + func formIndex(before i: inout Index) @_lifetime(borrow self) func previousSpan(before index: inout Index, maximumCount: Int) -> Span + + override func index(after index: Index) -> Index + + override func formIndex(after index: inout Index) + + @_nonoverride func index(_ index: Index, offsetBy n: Int) -> Index + + @_nonoverride func formIndex( + _ index: inout Index, offsetBy n: inout Int, limitedBy limit: Index + ) + + @_nonoverride func distance(from start: Index, to end: Index) -> Int + } @available(SwiftStdlib 5.0, *) diff --git a/Sources/ContainersPreview/Protocols/Container/MutableContainer.swift b/Sources/ContainersPreview/Protocols/Container/MutableContainer.swift index 33bbc89c..3b748578 100644 --- a/Sources/ContainersPreview/Protocols/Container/MutableContainer.swift +++ b/Sources/ContainersPreview/Protocols/Container/MutableContainer.swift @@ -27,6 +27,69 @@ where /// - Complexity: O(1) subscript(index: Index) -> Element { borrow mutate } + /// Return a mutable span over the container's storage that begins with the + /// element at the given index, and extends to the end of the contiguous + /// storage chunk that contains it, but no more than `maximumCount` items. + /// + /// On return, the index is updated to address the next item following the + /// end of the returned span. + /// + /// This method can be used to efficiently process the items of a container in + /// bulk, by directly iterating over its piecewise contiguous pieces of + /// storage: + /// + /// var index = items.startIndex + /// while true { + /// var span = items.nextMutableSpan(after: &index, maximumCount: 4) + /// if span.isEmpty { break } + /// // Process items in `span` + /// } + /// + /// The `maximumCount` argument gives the caller control over the number of + /// items it receives from the iterator. This lets the caller avoid getting + /// more elements than it would be able to immediately process, which would + /// significantly complicate container use. + /// + /// If the caller is able to process any number available items, it can signal + /// that by passing `Int.max` as the `maximumCount`, or simply by calling the + /// `nexSpan(after:)` method, which does precisely that. This is frequently + /// the case when the caller simply wants to iterate over the entire + /// container in a single loop. + /// + /// `maximumCount` sets an upper bound. To read a specific number of items, + /// the caller usually needs to invoke `nextSpan` in a loop: + /// + /// var items: some MutableContainer + /// var index = items.startIndex + /// var remainder = numberOfItemsToRead + /// while remainder > 0 { + /// let next = items.nextMutableSpan(after: &index, maximumCount: remainder) + /// guard !next.isEmpty else { + /// // Container does not have enough items + /// break + /// } + /// remainder -= next.count + /// // Process items in `next` + /// } + /// + /// - Note: Repeated invocations of `nextSpan` on the same container and index + /// are not guaranteed to return identical results. (This is particularly + /// the case with containers that can store contents in their "inline" + /// representation. Such containers may not always have a unique address + /// in memory; the locations of the spans exposed by this method may vary + /// between different borrows of the same container.) + /// + /// - Parameter index: A valid index in the container, including the end + /// index. On return, this index is advanced by the count of the resulting + /// span, to simplify iteration. + /// - Parameter maximumCount: The maximum number of items the caller is able + /// to process immediately. `maximumCount` must be greater than zero. + /// If you are able to process an arbitrary number of items, set + /// `maximumCount` to `Int.max`, or call the `nextSpan(after:)` method. + /// - Returns: A mutable span over contiguous storage that starts at the given + /// index. If the input index is the end index, then this returns an empty + /// span. Otherwise the result is non-empty, with its first element + /// matching the element at the input index. @_lifetime(&self) mutating func nextMutableSpan( after index: inout Index, diff --git a/Sources/ContainersPreview/Protocols/Container/RandomAccessContainer.swift b/Sources/ContainersPreview/Protocols/Container/RandomAccessContainer.swift index 08acb559..e578da1c 100644 --- a/Sources/ContainersPreview/Protocols/Container/RandomAccessContainer.swift +++ b/Sources/ContainersPreview/Protocols/Container/RandomAccessContainer.swift @@ -16,8 +16,44 @@ @available(SwiftStdlib 5.0, *) public protocol RandomAccessContainer : BidirectionalContainer, ~Copyable, ~Escapable -where Element: ~Copyable {} +where Element: ~Copyable { + // Note: Some requirements are redeclared to help associated type inference; + // others are kept separate with `@_nonoverride`. + // + // See more detailed discussion on `BidirectionalContainer`. + // + // `RandomAccessContainer` should technically redeclare single-steppers + // like `index(after:)` as `@_nonoverride`, as the protocol adds a semantic + // requirement for O(1) complexity. However, we emulate + // `RandomAccessCollection`'s (not necessarily well-justified) decision to + // leave these marked as overrides, forcing all types to have a single + // implementation that fulfills the (unique) requirement. (I haven't seen a + // case where these steppers would need to vary their implementation, while + // offsetting/distance calculations do sometimes want that, at least in + // theory. Not so much in practice though -- see e.g. `ZipSequence`'s lack of + // a conditional (random-access) collection conformance.) + // + // FIXME: Consider avoiding using `@_nonoverride`, reducing witness sizes. + override associatedtype Element: ~Copyable + override associatedtype Index + + override func index(after index: Index) -> Index + override func index(before index: Index) -> Index + + override func formIndex(after index: inout Index) + override func formIndex(before index: inout Index) + + @_nonoverride func index(_ index: Index, offsetBy n: Int) -> Index + + @_nonoverride func formIndex( + _ index: inout Index, offsetBy n: inout Int, limitedBy limit: Index + ) + + @_nonoverride func distance(from start: Index, to end: Index) -> Int +} + +@available(SwiftStdlib 5.0, *) extension RandomAccessCollection { @inlinable public func formIndex( From b2c1669aa7a8329ce1d43450c61c6f98c721ac1b Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 23 Jun 2026 17:07:25 -0700 Subject: [PATCH 12/50] [ContainersPreview] RandomAccessContainer: Add a separate set of default implementations for Index == Int This avoids going through Strideable, likely assisting the inliner. Also mark default implementations @_aeic, to avoid ABI headaches --- .../Container/RandomAccessContainer.swift | 107 +++++++++++++++--- 1 file changed, 89 insertions(+), 18 deletions(-) diff --git a/Sources/ContainersPreview/Protocols/Container/RandomAccessContainer.swift b/Sources/ContainersPreview/Protocols/Container/RandomAccessContainer.swift index e578da1c..c77801ad 100644 --- a/Sources/ContainersPreview/Protocols/Container/RandomAccessContainer.swift +++ b/Sources/ContainersPreview/Protocols/Container/RandomAccessContainer.swift @@ -72,51 +72,122 @@ extension RandomAccessCollection { @available(SwiftStdlib 5.0, *) extension RandomAccessContainer -where Self: ~Copyable & ~Escapable, Index: Strideable, Index.Stride == Int +where + Self: ~Copyable & ~Escapable, + Element: ~Copyable, + Index: Strideable, + Index.Stride == Int { - @inlinable + @_alwaysEmitIntoClient public var isEmpty: Bool { startIndex == endIndex } - @inlinable + @_alwaysEmitIntoClient public var count: Int { startIndex.distance(to: endIndex) } - @inlinable + @_alwaysEmitIntoClient public func index(after index: Index) -> Index { // Note: Range checks are deferred until element access. index.advanced(by: 1) } - @inlinable + @_alwaysEmitIntoClient public func index(before index: Index) -> Index { // Note: Range checks are deferred until element access. index.advanced(by: -1) } - @inlinable + @_alwaysEmitIntoClient public func formIndex(after index: inout Index) { // Note: Range checks are deferred until element access. index = index.advanced(by: 1) } - @inlinable + @_alwaysEmitIntoClient public func formIndex(before index: inout Index) { // Note: Range checks are deferred until element access. index = index.advanced(by: -1) } - @inlinable + @_alwaysEmitIntoClient public func distance(from start: Index, to end: Index) -> Int { // Note: Range checks are deferred until element access. start.distance(to: end) } - @inlinable + @_alwaysEmitIntoClient public func index(_ index: Index, offsetBy n: Int) -> Index { // Note: Range checks are deferred until element access. index.advanced(by: n) } - @inlinable + @_alwaysEmitIntoClient + 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(SwiftStdlib 5.0, *) +extension RandomAccessContainer +where + Self: ~Copyable & ~Escapable, + Element: ~Copyable, + Index == Int +{ + @_alwaysEmitIntoClient + @inline(__always) + public var isEmpty: Bool { startIndex == endIndex } + + @_alwaysEmitIntoClient + @inline(__always) + public var count: Int { endIndex - startIndex } + + @_alwaysEmitIntoClient + @inline(__always) + public func index(after index: Index) -> Index { + // Note: Range checks are deferred until element access. + index + 1 + } + + @_alwaysEmitIntoClient + @inline(__always) + public func index(before index: Index) -> Index { + // Note: Range checks are deferred until element access. + index - 1 + } + + @_alwaysEmitIntoClient + @inline(__always) + public func formIndex(after index: inout Index) { + // Note: Range checks are deferred until element access. + index += 1 + } + + @_alwaysEmitIntoClient + @inline(__always) + public func formIndex(before index: inout Index) { + // Note: Range checks are deferred until element access. + index -= 1 + } + + @_alwaysEmitIntoClient + @inline(__always) + public func distance(from start: Index, to end: Index) -> Int { + // Note: Range checks are deferred until element access. + end - start + } + + @_alwaysEmitIntoClient + @inline(__always) + public func index(_ index: Index, offsetBy n: Int) -> Index { + // Note: Range checks are deferred until element access. + index + n + } + + @_alwaysEmitIntoClient + @inline(__always) public func formIndex( _ index: inout Index, offsetBy distance: inout Index.Stride, limitedBy limit: Index ) { @@ -135,43 +206,43 @@ where Index.Stride == Int, Indices == Range { - @inlinable + @_alwaysEmitIntoClient public var isEmpty: Bool { startIndex == endIndex } - @inlinable + @_alwaysEmitIntoClient public var count: Int { endIndex - startIndex } - @inlinable + @_alwaysEmitIntoClient public func index(after index: Index) -> Index { // Note: Range checks are deferred until element access. index.advanced(by: 1) } - @inlinable + @_alwaysEmitIntoClient public func index(before index: Index) -> Index { // Note: Range checks are deferred until element access. index.advanced(by: -1) } - @inlinable + @_alwaysEmitIntoClient public func formIndex(after index: inout Index) { // Note: Range checks are deferred until element access. index = index.advanced(by: 1) } - @inlinable + @_alwaysEmitIntoClient public func formIndex(before index: inout Index) { // Note: Range checks are deferred until element access. index = index.advanced(by: -1) } - @inlinable + @_alwaysEmitIntoClient public func distance(from start: Index, to end: Index) -> Int { // Note: Range checks are deferred until element access. start.distance(to: end) } - @inlinable + @_alwaysEmitIntoClient public func index(_ index: Index, offsetBy n: Int) -> Index { // Note: Range checks are deferred until element access. index.advanced(by: n) From 8a1438c2b2c77ef280e53e553b28a4f252f9a040 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 23 Jun 2026 17:30:24 -0700 Subject: [PATCH 13/50] [ContainersPreview] Update/fix RangeReplaceableContainer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Introduce easy-to-use `replace(removing:addingFrom:)`, `insert(from:at:)`, and `append(from:)` algorithms that take `CountedProducer` instances, avoiding having to pass explicit counts separately - Avoid RangeExpression2 helpers from satisfying core protocol requirements, leading to broken conformances - Add `replace(removing:moving:)`, `replace(removing:consuming:)`, `insert(moving:at:)`, `insert(consuming:at:)`, `append(moving:)`, `append(consuming:)` operations that take range-replaceable containers. - Reorder some parameters for consistency/readability: - `insert(addingCount:at:from:)` → `insert(addingCount:from:at:)` - `insert(at:moving:from:)` → `insert(moving:from:at:)` --- .../Container/RangeReplaceableContainer.swift | 411 +++++++++++++++++- 1 file changed, 388 insertions(+), 23 deletions(-) diff --git a/Sources/ContainersPreview/Protocols/Container/RangeReplaceableContainer.swift b/Sources/ContainersPreview/Protocols/Container/RangeReplaceableContainer.swift index 10ba9f42..22c3db74 100644 --- a/Sources/ContainersPreview/Protocols/Container/RangeReplaceableContainer.swift +++ b/Sources/ContainersPreview/Protocols/Container/RangeReplaceableContainer.swift @@ -26,7 +26,7 @@ where Element: ~Copyable, Index: Comparable // For `Range` { - // Core requirements + // MARK: Core requirements var freeCapacity: Int { get } @@ -42,7 +42,7 @@ where @_lifetime(&self) mutating func consume(_ subrange: Range) -> SubrangeConsumer - // Requirements with default implementations + // MARK: Requirements with default implementations mutating func remove(at index: Index) -> Element mutating func removeSubrange(_ bounds: Range) @@ -164,6 +164,25 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable }) } + @inlinable + public mutating func replace< + E: Error, + P: CountedProducer & ~Copyable & ~Escapable + >( + removing subrange: some RangeExpression2, + addingFrom producer: consuming P + ) throws(P.Failure) + where P.Element: ~Copyable + { + try replace( + removing: subrange, + addingCount: producer.count, + from: &producer) + if try !producer._isAtEnd() { + preconditionFailure("Invalid Container") + } + } + @inlinable public mutating func replace( removing subrange: some RangeExpression2, @@ -178,6 +197,20 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable initializingWith: initializer) } + // This unavailable default implementation of the protocol requirement + // prevents incomplete RangeReplaceableContainer implementations from + // satisfying the protocol through the use of the generic algorithm above. + @available(*, unavailable) + @_alwaysEmitIntoClient + public mutating func replace( + removing subrange: Range, + consumingWith consumer: (inout InputSpan) -> Void, + addingCount newItemCount: Int, + initializingWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) { + fatalError() + } + @inlinable public mutating func replace( removing subrange: some RangeExpression2, @@ -191,6 +224,16 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable initializingWith: initializer) } + @inlinable + public mutating func replace< + C: RangeReplaceableContainer & ~Copyable & ~Escapable + >( + removing targetSubrange: some RangeExpression2, + moving source: inout C + ) where C.Element: ~Copyable { + replace(removing: targetSubrange, addingFrom: source.consumeAll()) + } + @inlinable public mutating func replace< C: RangeReplaceableContainer & ~Copyable & ~Escapable @@ -198,7 +241,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable removing targetSubrange: some RangeExpression2, moving sourceSubrange: some RangeExpression2, from source: inout C - ) { + ) where C.Element: ~Copyable { let sourceSubrange = sourceSubrange.relative(to: source) let c = source.distance(from: sourceSubrange.lowerBound, to: sourceSubrange.upperBound) var producer = source.consume(sourceSubrange) @@ -208,6 +251,17 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable preconditionFailure("Invalid Container") } } + + @inlinable + public mutating func replace< + C: RangeReplaceableContainer & ~Copyable & ~Escapable + >( + removing targetSubrange: some RangeExpression2, + consuming source: consuming C + ) where C.Element: ~Copyable { + replace(removing: targetSubrange, addingFrom: source.consumeAll()) + } + } @available(SwiftStdlib 5.0, *) @@ -241,6 +295,16 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { consume(subrange.relative(to: self)) } + // This unavailable default implementation of the protocol requirement + // prevents incomplete RangeReplaceableContainer implementations from + // satisfying the protocol through the use of the generic algorithm above. + @available(*, unavailable) + @_alwaysEmitIntoClient + @_lifetime(&self) + public mutating func consume(_ subrange: Range) -> SubrangeConsumer { + fatalError() + } + @inlinable @_lifetime(&self) public mutating func consume( @@ -305,44 +369,141 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable extension RangeReplaceableContainer where Self: ~Copyable & ~Escapable, Element: ~Copyable { + /// Inserts at most `newItemCount` items generated by a producer into this + /// container, starting at the given index. + /// + /// The target container must be able to accommodate the specified number + /// of new items. + /// + /// This operation inserts as many items as the producer can generate before + /// either reaching `newItemCount`, or the producer hitting its end, or + /// throwing an error. If the producer has more than `newItemCount` items + /// left in it, then extra items remain available after this method returns. + /// + /// If the operation ends up inserting fewer than `newItemCount` items, then + /// it may leave a gap that needs to be closed (e.g., by compacting storage) + /// to restore invariants before the function returns. This may add some + /// overhead compared to adding exactly as many items as promised. + /// + /// - Parameters: + /// - newItemCount: The maximum number of items to insert into the container. + /// - index: The position at which to insert the new items. + /// `index` must be a valid index in the container. + /// - producer: A producer that generates the items to append. @inlinable public mutating func insert< E: Error, P: Producer & ~Copyable & ~Escapable >( addingCount newItemCount: Int, - at index: Index, - from producer: inout P + from producer: inout P, + at index: Index ) throws(E) where P.Element: ~Copyable { try self.insert(addingCount: newItemCount, at: index) { target throws(E) in while !target.isFull, try producer.generate(into: &target) { + // Do nothing } } } + /// Inserts all items generated by a producer into this container, + /// starting at the given index. + /// + /// The target container must be able to accommodate every item that the + /// producer generates. + /// + /// This operation inserts as many items as the producer can generate before + /// hitting its end, or throwing an error. + /// + /// If the producer throws an error, then the operation preserves all items + /// that it previously managed to insert before rethrowing the error. + /// If this happens, then the failed insertions may leave a gap that needs to + /// be carefully closed (e.g., by compacting storage) to restore invariants + /// before the function returns. This may add some overhead compared to adding + /// exactly as many items as promised. + /// + /// - Parameters: + /// - index: The position at which to insert the new items. + /// `index` must be a valid index in the container. + /// - producer: A producer that generates the items to append. + @inlinable + public mutating func insert< + E: Error, + P: CountedProducer & ~Copyable & ~Escapable + >( + from producer: consuming P, + at index: Index + ) throws(E) + where P.Element: ~Copyable + { + let c = producer.count + try self.insert(addingCount: c, at: index) { target throws(E) in + while !target.isFull, try producer.generate(into: &target) { + } + } + if try !producer._isAtEnd() { + preconditionFailure("Invalid Container") + } + } + + @inlinable + public mutating func insert< + C: RangeReplaceableContainer & ~Copyable & ~Escapable + >( + moving source: inout C, + at index: Index + ) where C.Element: ~Copyable { + self.insert(from: source.consumeAll(), at: index) + } + @inlinable public mutating func insert< C: RangeReplaceableContainer & ~Copyable & ~Escapable >( - at index: Index, moving sourceSubrange: some RangeExpression2, - from source: inout C - ) { + from source: inout C, + at index: Index + ) where C.Element: ~Copyable { let sourceSubrange = sourceSubrange.relative(to: source) let c = source.distance(from: sourceSubrange.lowerBound, to: sourceSubrange.upperBound) var producer = source.consume(sourceSubrange) - self.insert(addingCount: c, at: index, from: &producer) + self.insert(addingCount: c, from: &producer, at: index) if !producer._isAtEnd() { preconditionFailure("Invalid Container") } } + + @inlinable + public mutating func insert< + C: RangeReplaceableContainer & ~Copyable & ~Escapable + >( + consuming source: consuming C, + at index: Index + ) where C.Element: ~Copyable { + self.insert(from: source.consumeAll(), at: index) + } } @available(SwiftStdlib 5.0, *) extension RangeReplaceableContainer where Self: ~Copyable & ~Escapable, Element: ~Copyable { + /// Appends at most `newItemCount` items generated by a producer to the end of + /// this container. + /// + /// The container must be able to accommodate the specified number of new + /// items. + /// + /// This operation appends as many items as the producer can generate before + /// either reaching its end, throwing an error, or filling the specified + /// capacity. This operation only consumes the first `newItemCount` items in the + /// producer; if the producer has more, then they remain available after this + /// method returns. + /// + /// - Parameters: + /// - newItemCount: The number of items to append to the container. + /// - producer: A producer that generates the items to append. @inlinable public mutating func append< E: Error, @@ -353,7 +514,51 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { ) throws(E) where P.Element: ~Copyable { - try insert(addingCount: newItemCount, at: endIndex, from: &producer) + try insert(addingCount: newItemCount, from: &producer, at: endIndex) + } + + /// Appends all items generated by the given producer to the end of + /// this container. + /// + /// The container must be able to accommodate all items. + /// + /// This operation appends all items the producer generates before reaching + /// its end or throwing an error. If the producer throws an error, the + /// operation preserves all previously appended items before rethrowing the + /// error. + /// + /// - Parameters: + /// - producer: A producer that generates the items to append. + @inlinable + public mutating func append< + E: Error, + P: CountedProducer & ~Copyable & ~Escapable + >( + from producer: consuming P + ) throws(E) + where P.Element: ~Copyable + { + try append(addingCount: producer.count, from: &producer) + if try !producer._isAtEnd() { + preconditionFailure("Invalid Container") + } + } + + /// Moves the elements of a given container into the end of this one, leaving + /// the source container empty. + /// + /// The target container must be able to accommodate all items in the source + /// container. + /// + /// - Parameters: + /// - items: A container whose contents to move into this container. + @inlinable + public mutating func append< + C: RangeReplaceableContainer & ~Copyable & ~Escapable + >( + moving items: inout C + ) where C.Element: ~Copyable { + self.append(from: items.consumeAll()) } @inlinable @@ -362,7 +567,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { >( moving sourceSubrange: some RangeExpression2, from source: inout C - ) { + ) where C.Element: ~Copyable { let sourceSubrange = sourceSubrange.relative(to: source) let c = source.distance(from: sourceSubrange.lowerBound, to: sourceSubrange.upperBound) var producer = source.consume(sourceSubrange) @@ -371,6 +576,23 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { preconditionFailure("Invalid Container") } } + + /// Appends the elements of a given container to the end of this one by + /// consuming the source container. + /// + /// The target container must be able to accommodate all items in the source + /// container. + /// + /// - Parameters: + /// - items: A container whose contents to move into this container. + @inlinable + public mutating func append< + C: RangeReplaceableContainer & ~Copyable & ~Escapable + >( + consuming items: consuming C + ) where C.Element: ~Copyable { + self.append(from: items.consumeAll()) + } } //MARK: - Standard Extensions Requiring Copyability @@ -396,24 +618,122 @@ where precondition(c == 0, "Invalid RangeReplaceableContainer") } - @inlinable + @_alwaysEmitIntoClient + internal mutating func _insertContainer< + C: Container & ~Copyable & ~Escapable + >( + addingCount newCount: Int, + copying items: borrowing C, + at index: Index + ) { + var it = items.makeIterableIterator_() + insert(addingCount: newCount, at: index) { target in + while !target.isFull { + let source = it.nextSpan_(maximumCount: target.freeCapacity) + precondition(!source.isEmpty, "Broken container: mismatching count") + target._append(copying: source) + } + } + precondition(it.nextSpan_().isEmpty, "Broken container: mismatching count") + } + + @_alwaysEmitIntoClient + package mutating func _insertCollection( + addingCount newCount: Int, + copying items: some Collection, + at index: Index + ) { + let done: Void? = items.withContiguousStorageIfAvailable { buffer in + precondition(buffer.count == newCount, "Broken Collection: mismatching count") + self.insert(addingCount: buffer.count, at: index) { target in + target._append(copying: buffer) + } + } + if done != nil { return } + var it = items.makeIterator() + self.insert(addingCount: newCount, at: index) { target in + while !target.isFull { + guard let item = it.next() else { preconditionFailure() } + target.append(item) + } + } + precondition(it.next() == nil, "Broken Collection") + } + + /// Copies the elements of a source container into this container, starting + /// at the specified target position. + /// + /// The new elements are inserted before the element currently at the + /// specified index in `self`. If you pass the target's `endIndex` as + /// the `index` parameter, then the new elements are appended to the end. + /// + /// The target container must be able to accommodate all items in the source + /// container. + /// + /// - Parameters: + /// - items: The new elements to insert into the container. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of `self`. + @_alwaysEmitIntoClient + @inline(__always) public mutating func insert< C: Container & ~Copyable & ~Escapable >( copying items: borrowing C, at index: Index ) { - var c = items.count - var i = items.startIndex - insert(addingCount: c, at: index) { target in - let source = items.nextSpan(after: &i, maximumCount: target.freeCapacity) - c -= source.count - target._append(copying: source) - } - precondition(c == 0, "Invalid RangeReplaceableContainer") + _insertContainer( + addingCount: items.count, copying: items, at: index) } - @inlinable + /// Copies the elements of a collection into this container at the specified + /// position. + /// + /// The new elements are inserted before the element currently at the + /// specified index. If you pass the container's `endIndex` as the `index` + /// parameter, then the new elements are appended to the end. + /// + /// The target container must be able to accommodate all items in the source + /// container. + /// + /// - Parameters: + /// - items: The new elements to insert into the container. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of `self`. + @_alwaysEmitIntoClient + @inline(__always) + public mutating func insert( + copying items: some Collection, at index: Index + ) { + _insertCollection(addingCount: items.count, copying: items, at: index) + } + + /// Copies the elements of a source container into this container, starting + /// at the specified target position. + /// + /// The new elements are inserted before the element currently at the + /// specified index in `self`. If you pass the target's `endIndex` as + /// the `index` parameter, then the new elements are appended to the end. + /// + /// The target container must be able to accommodate all items in the source + /// container. + /// + /// - Parameters: + /// - items: The new elements to insert into the container. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of `self`. + @_alwaysEmitIntoClient + @inline(__always) + public mutating func insert< + C: Container & Collection + >( + copying items: borrowing C, at index: Index + ) { + _insertContainer( + addingCount: items.count, copying: items, at: index) + } + + @_alwaysEmitIntoClient public mutating func append( copying items: Span ) { @@ -425,8 +745,8 @@ where precondition(items.isEmpty, "Invalid RangeReplaceableContainer") } - @inlinable - public mutating func append< + @_alwaysEmitIntoClient + package mutating func _appendIterable< S: Iterable_ & ~Copyable & ~Escapable >( copying items: borrowing S @@ -439,6 +759,51 @@ where self.append(copying: span) } } + + @inlinable + public mutating func append< + S: Iterable_ & ~Copyable & ~Escapable + >( + copying items: borrowing S + ) throws(S.Failure_) + where S.Element_ == Element { + try _appendIterable(copying: items) + } + + /// Copies the elements of a sequence to the end of this container. + /// + /// The container must be able to accommodate all items in the sequence. + /// + /// - Parameters: + /// - newElements: The new elements to copy into the container. + @_alwaysEmitIntoClient + public mutating func append(copying newElements: some Sequence) { + let done: Void? = newElements.withContiguousStorageIfAvailable { buffer in + unsafe self.append(copying: buffer) + return + } + if done != nil { return } + + for item in newElements { + self.append(item) + } + } + + /// Copies the elements of an iterable to the end of this container. + /// + /// The container must be able to accommodate all items in the iterable. + /// + /// - Parameters: + /// - newElements: The new elements to copy into the container. + @_alwaysEmitIntoClient + public mutating func append< + Source: Iterable_ & Sequence + >( + copying newElements: Source + ) throws(Source.Failure_) + where Source.Element_ == Element { + try self._appendIterable(copying: newElements) + } } #endif From 00ffe8caec0ec5b211cf1c74abc6d7d95cc05088 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 23 Jun 2026 17:32:49 -0700 Subject: [PATCH 14/50] [HashTreeCollections] Avoid parsing issue with `func read` When the BorrowAndMutateAccessors feature is enabled, this code appears to be parsed as if it declared a `read` accessor, rather than a getter passing a closure to the `read` function: ```swift @inlinable internal var collisionHash: _Hash { read { $0.collisionHash } } ``` Avoid this by adding a `self` prefix, as in `self.read { $0.collisionHash }`. --- Sources/HashTreeCollections/HashNode/_HashNode.swift | 10 +++++----- .../HashTable/_HashTable+CustomStringConvertible.swift | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Sources/HashTreeCollections/HashNode/_HashNode.swift b/Sources/HashTreeCollections/HashNode/_HashNode.swift index b807aef8..f7fc74f3 100644 --- a/Sources/HashTreeCollections/HashNode/_HashNode.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode.swift @@ -103,27 +103,27 @@ extension _HashNode { extension _HashNode { @inlinable internal var isCollisionNode: Bool { - read { $0.isCollisionNode } + self.read { $0.isCollisionNode } } @inlinable internal var collisionHash: _Hash { - read { $0.collisionHash } + self.read { $0.collisionHash } } @inlinable internal var hasSingletonItem: Bool { - read { $0.hasSingletonItem } + self.read { $0.hasSingletonItem } } @inlinable internal var hasSingletonChild: Bool { - read { $0.hasSingletonChild } + self.read { $0.hasSingletonChild } } @inlinable internal var isAtrophied: Bool { - read { $0.isAtrophiedNode } + self.read { $0.isAtrophiedNode } } } diff --git a/Sources/OrderedCollections/HashTable/_HashTable+CustomStringConvertible.swift b/Sources/OrderedCollections/HashTable/_HashTable+CustomStringConvertible.swift index 2ed4c7f5..1c46ce86 100644 --- a/Sources/OrderedCollections/HashTable/_HashTable+CustomStringConvertible.swift +++ b/Sources/OrderedCollections/HashTable/_HashTable+CustomStringConvertible.swift @@ -50,7 +50,7 @@ extension _HashTable.UnsafeHandle: CustomStringConvertible { extension _HashTable: CustomStringConvertible { @usableFromInline internal var description: String { - read { $0._description(type: "_HashTable") } + self.read { $0._description(type: "_HashTable") } } } From d0a3207e3915b5edd8425e6653ba75907f2c405f Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 23 Jun 2026 17:35:04 -0700 Subject: [PATCH 15/50] [InternalCollectionsUtilities] Define `_pointee` property on pointer types with borrow/mutate accessors --- .../CMakeLists.txt | 2 ++ .../UnsafeMutablePointer+Extras.swift | 34 +++++++++++++++++++ .../UnsafePointer+Extras.swift | 29 ++++++++++++++++ 3 files changed, 65 insertions(+) create mode 100644 Sources/InternalCollectionsUtilities/UnsafeMutablePointer+Extras.swift create mode 100644 Sources/InternalCollectionsUtilities/UnsafePointer+Extras.swift diff --git a/Sources/InternalCollectionsUtilities/CMakeLists.txt b/Sources/InternalCollectionsUtilities/CMakeLists.txt index 73f92a23..5a153f94 100644 --- a/Sources/InternalCollectionsUtilities/CMakeLists.txt +++ b/Sources/InternalCollectionsUtilities/CMakeLists.txt @@ -45,4 +45,6 @@ target_sources(${module_name} PRIVATE "UnsafeMutableBufferPointer+Extras.swift" "UnsafeMutableRawBufferPointer+Extras.swift" "UnsafeRawBufferPointer+Extras.swift" + "UnsafePointer+Extras.swift" + "UnsafeMutablePointer+Extras.swift" ) diff --git a/Sources/InternalCollectionsUtilities/UnsafeMutablePointer+Extras.swift b/Sources/InternalCollectionsUtilities/UnsafeMutablePointer+Extras.swift new file mode 100644 index 00000000..cd5fee29 --- /dev/null +++ b/Sources/InternalCollectionsUtilities/UnsafeMutablePointer+Extras.swift @@ -0,0 +1,34 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.4) +import Builtin + +extension UnsafeMutablePointer where Pointee: ~Copyable { + // FIXME: Remove this once the standard `pointee` has a borrow accessor. + @_alwaysEmitIntoClient + @_transparent + @unsafe + package var _pointee: Pointee { + @_unsafeSelfDependentResult + borrow { + Builtin.borrowAt(self._rawValue) + } + @_unsafeSelfDependentResult + nonmutating mutate { + unsafe &self.pointee + } + } +} + +#endif diff --git a/Sources/InternalCollectionsUtilities/UnsafePointer+Extras.swift b/Sources/InternalCollectionsUtilities/UnsafePointer+Extras.swift new file mode 100644 index 00000000..f1fc06dc --- /dev/null +++ b/Sources/InternalCollectionsUtilities/UnsafePointer+Extras.swift @@ -0,0 +1,29 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.4) +import Builtin + +extension UnsafePointer where Pointee: ~Copyable { + // FIXME: Remove this once the standard `pointee` has a borrow accessor. + @_alwaysEmitIntoClient + @_transparent + @unsafe + package var _pointee: Pointee { + @_unsafeSelfDependentResult + borrow { + Builtin.borrowAt(self._rawValue) + } + } +} +#endif From 281d0a859d5e739a34b955c2baf7732e086519a1 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 23 Jun 2026 17:35:28 -0700 Subject: [PATCH 16/50] [InternalCollectionsUtilities] Update set of lifetime overrides --- .../LifetimeOverride.swift | 21 +++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/Sources/InternalCollectionsUtilities/LifetimeOverride.swift b/Sources/InternalCollectionsUtilities/LifetimeOverride.swift index 738ba591..51f3a6c6 100644 --- a/Sources/InternalCollectionsUtilities/LifetimeOverride.swift +++ b/Sources/InternalCollectionsUtilities/LifetimeOverride.swift @@ -22,8 +22,6 @@ package func _unsafeImmortalize( _ dependent: consuming T ) -> T { - // TODO: Remove @_unsafeNonescapableResult. Instead, the unsafe dependence - // should be expressed by a builtin that is hidden within the function body. dependent } @@ -40,8 +38,6 @@ package func _overrideLifetime< >( _ dependent: consuming T, borrowing source: borrowing U ) -> T { - // TODO: Remove @_unsafeNonescapableResult. Instead, the unsafe dependence - // should be expressed by a builtin that is hidden within the function body. dependent } @@ -58,8 +54,6 @@ package func _overrideLifetime< >( _ dependent: consuming T, copying source: borrowing U ) -> T { - // TODO: Remove @_unsafeNonescapableResult. Instead, the unsafe dependence - // should be expressed by a builtin that is hidden within the function body. dependent } @@ -82,4 +76,19 @@ package func _overrideLifetime< // should be expressed by a builtin that is hidden within the function body. dependent } + +/// Unsafely discard any lifetime dependency on the `dependent` inout +/// argument, replacing it with a lifetime dependency on the caller's borrow +/// scope of the `source` argument. +@unsafe +@_unsafeNonescapableResult +@_alwaysEmitIntoClient +@_transparent +@_lifetime(dependent: borrow source) +public func _overrideLifetime< + T: ~Copyable & ~Escapable, U: ~Copyable & ~Escapable +>( + _ dependent: inout T, borrowing source: borrowing U +) {} + #endif From 204e94cb63b63ee651170998da95283c6cc6620a Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 23 Jun 2026 17:40:35 -0700 Subject: [PATCH 17/50] [ContainersPreview] Conform span types to some of the container protocols This is currently limited to `Container`, `BidirectionalContainer`, `RandomAccessContainer` and `MutableContainer`. `OutputSpan` and `InputSpan` should also be `RangeReplaceableContainer`s, but that is proving tricky to express in current Swift. --- Sources/ContainersPreview/CMakeLists.txt | 7 +- .../Conformances/InputSpan+Container.swift | 64 ++++++++++++++++++ .../Conformances/MutableSpan+Container.swift | 67 +++++++++++++++++++ .../Conformances/OutputSpan+Container.swift | 60 +++++++++++++++++ .../Conformances/Span+Container.swift | 46 +++++++++++++ .../ContainersPreview/Types/InputSpan.swift | 52 ++++++++++---- .../MinimalTypes/StaccatoContainer.swift | 13 +++- 7 files changed, 291 insertions(+), 18 deletions(-) create mode 100644 Sources/ContainersPreview/Conformances/InputSpan+Container.swift create mode 100644 Sources/ContainersPreview/Conformances/MutableSpan+Container.swift create mode 100644 Sources/ContainersPreview/Conformances/OutputSpan+Container.swift create mode 100644 Sources/ContainersPreview/Conformances/Span+Container.swift diff --git a/Sources/ContainersPreview/CMakeLists.txt b/Sources/ContainersPreview/CMakeLists.txt index fc0d2f8c..81814b02 100644 --- a/Sources/ContainersPreview/CMakeLists.txt +++ b/Sources/ContainersPreview/CMakeLists.txt @@ -25,9 +25,10 @@ else() endif() target_sources(${module_name} PRIVATE - "Extensions/Optional+Extras.swift" - "Extensions/OutputSpan+Extras.swift" - "Extensions/TemporaryAllocation.swift" + "Conformances/InputSpan+Container.swift" + "Conformances/MutableSpan+Container.swift" + "Conformances/OutputSpan+Container.swift" + "Conformances/Span+Container.swift" "Protocols/Container/BidirectionalContainer.swift" "Protocols/Container/Container.swift" "Protocols/Container/Container+Filter.swift" diff --git a/Sources/ContainersPreview/Conformances/InputSpan+Container.swift b/Sources/ContainersPreview/Conformances/InputSpan+Container.swift new file mode 100644 index 00000000..ebc6655f --- /dev/null +++ b/Sources/ContainersPreview/Conformances/InputSpan+Container.swift @@ -0,0 +1,64 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// 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 +// +// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +#endif + +#if compiler(>=6.2) && UnstableContainersPreview + +@available(SwiftStdlib 5.0, *) +extension InputSpan: RandomAccessContainer, MutableContainer +where Element: ~Copyable +{ + @_alwaysEmitIntoClient + @inline(__always) + public var startIndex: Index { 0 } + + @_alwaysEmitIntoClient + @inline(__always) + public var endIndex: Index { count } + + @inlinable + @_lifetime(borrow self) + public func nextSpan(after index: inout Index, maximumCount: Int) -> Span { + precondition(index >= 0 && index <= count, "Index out of bounds") + precondition(maximumCount > 0, "maximumCount must be positive") + let c = Swift.min(count &- index, maximumCount) + let start = capacity &- count &+ index + return _uncheckedSpan(in: Range(uncheckedBounds: (start, start &+ c))) + } + + @inlinable + @_lifetime(&self) + public mutating func nextMutableSpan( + after index: inout Index, maximumCount: Int + ) -> MutableSpan { + precondition(index >= 0 && index <= count, "Index out of bounds") + precondition(maximumCount > 0, "maximumCount must be positive") + let c = Swift.min(count &- index, maximumCount) + let start = capacity &- count &+ index + return _uncheckedMutableSpan(in: Range(uncheckedBounds: (start, start &+ c))) + } + + @inlinable + @_lifetime(borrow self) + public func previousSpan(before index: inout Int, maximumCount: Int) -> Span { + precondition(index >= 0 && index <= count, "Index out of bounds") + precondition(maximumCount > 0, "maximumCount must be positive") + let c = Swift.min(index, maximumCount) + let end = capacity &- count &+ index + return _uncheckedSpan(in: Range(uncheckedBounds: (end &- c, end))) + } +} +#endif diff --git a/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift b/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift new file mode 100644 index 00000000..508332b7 --- /dev/null +++ b/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift @@ -0,0 +1,67 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// 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 +// +// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.4) && UnstableContainersPreview + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +#endif + +extension MutableSpan: RandomAccessContainer where Element: ~Copyable { + @_alwaysEmitIntoClient + public var startIndex: Int { + 0 + } + + @_alwaysEmitIntoClient + public var endIndex: Int { + count + } + + @_alwaysEmitIntoClient + @_lifetime(borrow self) + public func nextSpan( + after index: inout Int, maximumCount: Int + ) -> Span { + precondition(index >= 0 && index <= count, "Index out of bounds") + precondition(maximumCount > 0, "maximumCount must be positive") + let limit = index &+ Swift.min(maximumCount, count &- index) + return self.span.extracting(unchecked: Range(uncheckedBounds: (index, limit))) + } + + @_alwaysEmitIntoClient + @_lifetime(borrow self) + public func previousSpan( + before index: inout Int, maximumCount: Int + ) -> Span { + precondition(index >= 0 && index <= count, "Index out of bounds") + precondition(maximumCount > 0, "maximumCount must be positive") + let limit = index &- Swift.min(maximumCount, index) + return self.span.extracting(unchecked: Range(uncheckedBounds: (limit, index))) + } +} + +extension MutableSpan: MutableContainer where Element: ~Copyable { + @_alwaysEmitIntoClient + @_lifetime(&self) + public mutating func nextMutableSpan( + after index: inout Int, maximumCount: Int + ) -> MutableSpan { + precondition(index >= 0 && index <= count, "Index out of bounds") + precondition(maximumCount > 0, "maximumCount must be positive") + let limit = index &+ Swift.min(maximumCount, count &- index) + return self._mutatingExtracting(unchecked: Range(uncheckedBounds: (index, limit))) + } +} + +#endif diff --git a/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift b/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift new file mode 100644 index 00000000..84db9109 --- /dev/null +++ b/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift @@ -0,0 +1,60 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// 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 +// +// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +#endif + +#if compiler(>=6.2) && UnstableContainersPreview +@available(SwiftStdlib 5.0, *) +extension OutputSpan: RandomAccessContainer, MutableContainer +where Element: ~Copyable +{ + @_alwaysEmitIntoClient + @inline(__always) + public var startIndex: Index { 0 } + + @_alwaysEmitIntoClient + @inline(__always) + public var endIndex: Index { count } + + @inlinable + @_lifetime(borrow self) + public func nextSpan(after index: inout Index, maximumCount: Int) -> Span { + precondition(index >= 0 && index <= count, "Index out of bounds") + precondition(maximumCount > 0, "maximumCount must be positive") + let limit = Swift.min(count &- index, maximumCount) + return self.span.extracting(unchecked: Range(uncheckedBounds: (index, limit))) + } + + @inlinable + @_lifetime(&self) + public mutating func nextMutableSpan( + after index: inout Index, maximumCount: Int + ) -> MutableSpan { + precondition(index >= 0 && index <= count, "Index out of bounds") + precondition(maximumCount > 0, "maximumCount must be positive") + let limit = Swift.min(count &- index, maximumCount) + return self.mutableSpan._consumingExtracting(Range(uncheckedBounds: (index, limit))) + } + + @inlinable + @_lifetime(borrow self) + public func previousSpan(before index: inout Int, maximumCount: Int) -> Span { + precondition(index >= 0 && index <= count, "Index out of bounds") + precondition(maximumCount > 0, "maximumCount must be positive") + let limit = Swift.max(0, index - maximumCount) + return self.span.extracting(unchecked: Range(uncheckedBounds: (limit, index))) + } +} +#endif diff --git a/Sources/ContainersPreview/Conformances/Span+Container.swift b/Sources/ContainersPreview/Conformances/Span+Container.swift new file mode 100644 index 00000000..06397241 --- /dev/null +++ b/Sources/ContainersPreview/Conformances/Span+Container.swift @@ -0,0 +1,46 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// 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 +// +// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.4) && UnstableContainersPreview + +extension Span: RandomAccessContainer where Element: ~Copyable { + @_alwaysEmitIntoClient + public var startIndex: Int { + 0 + } + + @_alwaysEmitIntoClient + public var endIndex: Int { + count + } + + @_alwaysEmitIntoClient + @_lifetime(borrow self) + public func nextSpan(after index: inout Int, maximumCount: Int) -> Span { + precondition(index >= 0 && index <= count, "Index out of bounds") + precondition(maximumCount > 0, "maximumCount must be positive") + let limit = index &+ Swift.min(maximumCount, count &- index) + return self.extracting(unchecked: Range(uncheckedBounds: (index, limit))) + } + + @_alwaysEmitIntoClient + @_lifetime(borrow self) + public func previousSpan(before index: inout Int, maximumCount: Int) -> Span { + precondition(index >= 0 && index <= count, "Index out of bounds") + precondition(maximumCount > 0, "maximumCount must be positive") + let limit = index &- Swift.min(maximumCount, index) + return self.extracting(unchecked: Range(uncheckedBounds: (limit, index))) + } +} + +#endif diff --git a/Sources/ContainersPreview/Types/InputSpan.swift b/Sources/ContainersPreview/Types/InputSpan.swift index 74afceb6..1c09bd20 100644 --- a/Sources/ContainersPreview/Types/InputSpan.swift +++ b/Sources/ContainersPreview/Types/InputSpan.swift @@ -437,18 +437,38 @@ extension InputSpan /* where Element: Copyable */ { @available(SwiftStdlib 5.0, *) extension InputSpan where Element: ~Copyable { + @inlinable + @unsafe + @_lifetime(borrow self) + internal func _uncheckedSpan(in range: Range) -> Span { + let pointer = unsafe _pointer? + .assumingMemoryBound(to: Element.self) + .advanced(by: capacity &- _count &+ range.lowerBound) + let buffer = unsafe UnsafeBufferPointer(start: pointer, count: range.count) + let span = unsafe Span(_unsafeElements: buffer) + return unsafe _overrideLifetime(span, borrowing: self) + } + + @inlinable + @unsafe + @_lifetime(&self) + internal mutating func _uncheckedMutableSpan(in range: Range) -> MutableSpan { + let pointer = unsafe _pointer? + .assumingMemoryBound(to: Element.self) + .advanced(by: capacity &- _count &+ range.lowerBound) + let buffer = unsafe UnsafeMutableBufferPointer( + start: pointer, count: range.count) + let span = unsafe MutableSpan(_unsafeElements: buffer) + return unsafe _overrideLifetime(span, mutating: &self) + } + /// Borrow the underlying initialized memory for read-only access. @available(SwiftStdlib 5.0, *) @_alwaysEmitIntoClient public var span: Span { @_lifetime(borrow self) borrowing get { - let pointer = unsafe _pointer? - .assumingMemoryBound(to: Element.self) - .advanced(by: capacity &- _count) - let buffer = unsafe UnsafeBufferPointer(start: pointer, count: _count) - let span = unsafe Span(_unsafeElements: buffer) - return unsafe _overrideLifetime(span, borrowing: self) + _uncheckedSpan(in: 0 ..< _count) } } @@ -458,13 +478,7 @@ extension InputSpan where Element: ~Copyable { public var mutableSpan: MutableSpan { @_lifetime(&self) mutating get { - let pointer = unsafe _pointer? - .assumingMemoryBound(to: Element.self) - .advanced(by: capacity &- _count) - let buffer = unsafe UnsafeMutableBufferPointer( - start: pointer, count: _count) - let span = unsafe MutableSpan(_unsafeElements: buffer) - return unsafe _overrideLifetime(span, borrowing: self) + _uncheckedMutableSpan(in: 0 ..< _count) } } } @@ -562,4 +576,16 @@ internal func withTemporaryInputSpan } } +@available(SwiftStdlib 5.0, *) +extension InputSpan where Element: ~Copyable { + @_alwaysEmitIntoClient + @_lifetime(self: copy self) + package mutating func _consumeAll( + consumingWith consumer: (inout InputSpan) -> Void + ) { + consumer(&self) + self.removeAll() + } +} + #endif diff --git a/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift b/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift index 0c891573..74211c6c 100644 --- a/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift +++ b/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift @@ -137,6 +137,9 @@ extension StaccatoContainer: Container where Element: ~Copyable { package func _isValid(_ index: Index) -> Bool { index._offset >= 0 && index._offset <= count } + package func _isOccupied(_ index: Index) -> Bool { + index._offset >= 0 && index._offset < count + } public var startIndex: Index { Index(_offset: 0) } public var endIndex: Index { Index(_offset: _contents.count) } @@ -170,7 +173,14 @@ extension StaccatoContainer: Container where Element: ~Copyable { index._offset._advance(by: &n, limitedBy: limit._offset) precondition(_isValid(index)) } - + + public subscript(position: Index) -> Element { + borrow { + precondition(_isOccupied(position)) + return _contents[position._offset] + } + } + @_lifetime(borrow self) public func nextSpan( after index: inout Index, maximumCount: Int @@ -178,7 +188,6 @@ extension StaccatoContainer: Container where Element: ~Copyable { precondition(_isValid(index)) let startOffset = index._offset let endOffset = _params.endOffset(fromOffset: index._offset, maximumCount: maximumCount) - print("\(startOffset) .-> \(endOffset)") index._offset = endOffset return _contents.span.extracting(startOffset ..< endOffset) } From 3ba8d70ec3a7f24aa0b5ae00a2a4514ca8e8081c Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 1 Jul 2026 15:58:22 -0700 Subject: [PATCH 18/50] Review and update container protocols and conformances MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - @inlinable → @_alwaysEmitIntoClient for now, to avoid temporary ABI issues - Review RangeReplaceableContainer algorithms; add missing ones: - New requirements: `removeFirst()`, `removeFirst(_:)`, `_customRemoveLast()`, `_customRemoveLast(_:) (with default implementations) - `func removeAll()` - `func removeLast()`, `func removeLast(_:)`, `func popLast()` when self is also bidirectional - Review RigidArray, UniqueArray algorithms; remove ones needlessly duplicating functionality already provided by RRC. Try not to break source compatibility. --- Package.swift | 1 - .../RigidArray/RigidArray+Append.swift | 100 +-------- .../RigidArray/RigidArray+Consumption.swift | 10 +- .../RigidArray/RigidArray+Container.swift | 2 +- .../RigidArray/RigidArray+Insertions.swift | 212 +++--------------- .../RigidArray/RigidArray+Removals.swift | 6 +- .../UniqueArray/UniqueArray+Append.swift | 66 +----- .../UniqueArray/UniqueArray+Consumption.swift | 2 +- .../UniqueArray/UniqueArray+Container.swift | 4 +- .../UniqueArray/UniqueArray+Insertions.swift | 160 +------------ .../UniqueArray/UniqueArray+Removals.swift | 5 +- Sources/ContainersPreview/CMakeLists.txt | 1 + .../Container/Container+Filter.swift | 6 +- .../Protocols/Container/Container.swift | 47 ++-- .../Container/ContainerIterator.swift | 15 +- .../Container/DynamicContainer.swift | 47 +++- .../Container/MutableContainer.swift | 4 +- .../Container/RangeReplaceableContainer.swift | 150 ++++++++++--- .../Protocols/Producer+Filter.swift | 4 + .../Protocols/Producer+Map.swift | 4 + .../Protocols/Producer+Reduce.swift | 4 + .../Protocols/Producer.swift | 4 + .../Types/OutputSpan+Extras.swift | 51 +++++ .../RigidDeque/RigidDeque+Consumption.swift | 8 +- .../RigidDeque/RigidDeque+Container.swift | 4 +- .../RigidDeque/RigidDeque+Hashable.swift | 15 ++ .../RigidDeque/RigidDeque+Removals.swift | 20 +- .../UniqueDeque/UniqueDeque+Consumption.swift | 2 +- .../UniqueDeque/UniqueDeque+Container.swift | 4 +- .../UniqueDeque/UniqueDeque+Hashable.swift | 10 + .../UniqueDeque/UniqueDeque+Removals.swift | 2 + .../OutputSpan+Extras.swift | 38 ---- .../Span+Extras.swift | 4 +- Xcode/Collections.xcodeproj/project.pbxproj | 44 +++- .../xcschemes/Collections.xcscheme | 2 +- Xcode/Shared.xcconfig | 1 - 36 files changed, 415 insertions(+), 644 deletions(-) create mode 100644 Sources/ContainersPreview/Types/OutputSpan+Extras.swift diff --git a/Package.swift b/Package.swift index 44656da0..70c83e3c 100644 --- a/Package.swift +++ b/Package.swift @@ -116,7 +116,6 @@ let extraSettings: [SwiftSetting] = [ .enableExperimentalFeature("AddressableParameters"), .enableExperimentalFeature("AddressableTypes"), .enableExperimentalFeature("SuppressedAssociatedTypesWithDefaults"), // Requires Swift 6.4 - .enableExperimentalFeature("BorrowAndMutateAccessors"), // Note: if you touch these, please make sure to also update the similar lists in // CMakeLists.txt and Xcode/Shared.xcconfig. ] diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Append.swift b/Sources/BasicContainers/RigidArray/RigidArray+Append.swift index 39fef60f..e1a78649 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Append.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Append.swift @@ -130,6 +130,7 @@ extension RigidArray where Element: ~Copyable { public mutating func append( moving items: inout InputSpan ) { + // FIXME: Remove this when `InputSpan` starts conforming to RangeReplaceableContainer items.withUnsafeMutableBufferPointer { buffer, count in let source = buffer._extracting(last: count) unsafe self.append(moving: source) @@ -152,6 +153,7 @@ extension RigidArray where Element: ~Copyable { public mutating func append( moving items: inout OutputSpan ) { + // FIXME: Remove this when `OutputSpan` starts conforming to RangeReplaceableContainer items.withUnsafeMutableBufferPointer { buffer, count in let source = buffer._extracting(first: count) unsafe self.append(moving: source) @@ -159,6 +161,7 @@ extension RigidArray where Element: ~Copyable { } } +#if !UnstableContainersPreview /// Appends the elements of a given array to the end of this array by moving /// them between the containers. On return, the input array becomes empty, but /// it is not destroyed, and it preserves its original storage capacity. @@ -174,107 +177,10 @@ extension RigidArray where Element: ~Copyable { public mutating func append( moving items: inout RigidArray ) { - // FIXME: Remove this in favor of a generic algorithm over range-replaceable containers items.edit { span in self.append(moving: &span) } } -} - -@available(SwiftStdlib 5.0, *) -extension RigidArray where Element: ~Copyable { -#if UnstableContainersPreview - /// Appends the elements of a given container to the end of this array by - /// consuming the source container. - /// - /// If the target array does not have sufficient capacity to hold all items - /// in the source array, then this triggers a runtime error. - /// - /// - Parameters: - /// - items: A container whose contents to move into this array. - /// - /// - Complexity: O(`items.count`) - @_alwaysEmitIntoClient - public mutating func append( - consuming items: consuming RigidArray - ) { - // FIXME: Remove this in favor of a generic algorithm over consumable containers - var items = items - self.append(moving: &items) - } -#endif -} - -@available(SwiftStdlib 5.0, *) -extension RigidArray where Element: ~Copyable { -#if compiler(>=6.4) && UnstableContainersPreview - /// Appends at most `newItemCount` items generated by a producer to the end of - /// this array. - /// - /// If the array doesn't have sufficient capacity to accommodate the specified - /// number of new elements, then this method reallocates the array's storage - /// to grow it, using a geometric growth rate. - /// - /// This operation appends as many items as the producer can generate before - /// either reaching its end (or throwing an error), or filling the specified - /// capacity. This operation only consumes the first `newItemCount` items in the - /// producer; if the producer has more, then they remain available after this - /// method returns. - /// - /// - Parameters: - /// - newItemCount: The maximum number of items to append to the array. - /// - producer: A producer that generates the items to append. - /// - /// - Complexity: O(*n*) where *n* is the number of new items, when - /// amortized over many similar invocations on the same array. - @_alwaysEmitIntoClient - public mutating func append< - E: Error, - P: Producer & ~Copyable & ~Escapable - >( - addingCount newItemCount: Int, - from producer: inout P - ) throws(E) - where P.Element: ~Copyable - { - try self.append(addingCount: newItemCount) { target throws(E) in - while !target.isFull { - guard try producer.generate(into: &target) else { break } - } - } - } -#endif - -#if compiler(>=6.4) && UnstableContainersPreview - /// Appends all the items generated by a producer to the end of this deque. - /// - /// If the deque doesn't have sufficient capacity to accommodate all the - /// elements, then this method reallocates the deque's storage - /// to grow it, using a geometric growth rate. - /// - /// - Parameters: - /// - producer: A producer that generates the items to append. - /// - /// - Complexity: O(*n*) where *n* is the number of new items, when - /// amortized over many similarly-sized invocations on the same deque. - @_alwaysEmitIntoClient - public mutating func append< - E: Error, - P: Producer & ~Copyable & ~Escapable - >( - from producer: inout P - ) throws(E) - where P.Element: ~Copyable - { - var done = false - while !done { - try self.append(addingCount: freeCapacity) { target throws(E) in - while !target.isFull, !done { - done = try !producer.generate(into: &target) - } - } - } - } #endif } diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Consumption.swift b/Sources/BasicContainers/RigidArray/RigidArray+Consumption.swift index d17a84e7..096569e0 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Consumption.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Consumption.swift @@ -138,7 +138,7 @@ extension RigidArray where Element: ~Copyable { #endif #if compiler(>=6.4) && UnstableContainersPreview -@available(SwiftStdlib 6.4, *) +@available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { @_alwaysEmitIntoClient @inline(__always) @@ -148,9 +148,9 @@ extension RigidArray where Element: ~Copyable { } } -@available(SwiftStdlib 6.4, *) +@available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { - @available(SwiftStdlib 6.4, *) + @available(SwiftStdlib 5.0, *) @frozen public struct SubrangeConsumer: ~Copyable, ~Escapable { // FIXME: We have to use our own MutableRef because the standard one @@ -191,11 +191,11 @@ extension RigidArray where Element: ~Copyable { } -@available(SwiftStdlib 6.4, *) +@available(SwiftStdlib 5.0, *) extension RigidArray.SubrangeConsumer: Drain where Element: ~Copyable { } -@available(SwiftStdlib 6.4, *) +@available(SwiftStdlib 5.0, *) extension RigidArray.SubrangeConsumer where Element: ~Copyable { @inlinable public var count: Int { diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Container.swift b/Sources/BasicContainers/RigidArray/RigidArray+Container.swift index c46aa70e..d2aa4ae1 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Container.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Container.swift @@ -44,7 +44,7 @@ extension RigidArray: RandomAccessContainer where Element: ~Copyable {} @available(SwiftStdlib 5.0, *) extension RigidArray: MutableContainer where Element: ~Copyable {} -@available(SwiftStdlib 6.4, *) +@available(SwiftStdlib 5.0, *) extension RigidArray: RangeReplaceableContainer where Element: ~Copyable {} #endif #endif diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Insertions.swift b/Sources/BasicContainers/RigidArray/RigidArray+Insertions.swift index 82b7da61..980a0460 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Insertions.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Insertions.swift @@ -170,6 +170,7 @@ extension RigidArray where Element: ~Copyable { moving items: inout InputSpan, at index: Int ) { + // FIXME: Remove when InputSpan starts conforming to RangeReplaceableContainer items.withUnsafeMutableBufferPointer { buffer, count in let source = buffer._extracting(last: count) unsafe self.insert(moving: source, at: index) @@ -199,6 +200,7 @@ extension RigidArray where Element: ~Copyable { moving items: inout OutputSpan, at index: Int ) { + // FIXME: Remove when OutputSpan starts conforming to RangeReplaceableContainer items.withUnsafeMutableBufferPointer { buffer, count in let source = buffer._extracting(first: count) unsafe self.insert(moving: source, at: index) @@ -206,6 +208,7 @@ extension RigidArray where Element: ~Copyable { } } +#if !UnstableContainersPreview /// Inserts the elements of a given array into the given position in this /// array by moving them between the containers. On return, the input array /// becomes empty, but it is not destroyed, and it preserves its original @@ -234,88 +237,9 @@ extension RigidArray where Element: ~Copyable { self.insert(moving: &source, at: index) } } -} - -@available(SwiftStdlib 5.0, *) -extension RigidArray where Element: ~Copyable { -#if UnstableContainersPreview - /// Inserts the elements of a given array into the given position in this - /// array by consuming the source container. - /// - /// All existing elements at or following 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. - /// - /// - Parameters: - /// - 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. - /// - /// - Complexity: O(`count` + `items.count`) - @_alwaysEmitIntoClient - public mutating func insert( - consuming items: consuming RigidArray, - 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 RigidArray where Element: ~Copyable { -#if compiler(>=6.4) && UnstableContainersPreview - /// Inserts at most `newItemCount` items generated by a producer into this - /// array, starting at the given index. - /// - /// Existing elements in the array's storage are moved as needed to make room - /// for the new items. - /// - /// If the target array does not have sufficient capacity to hold the - /// specified number of new items, then this triggers a runtime error. - /// - /// This operation inserts as many items as the producer can generate before - /// either reaching `newItemCount`, or the producer hitting its end, or - /// throwing an error. If the producer has more than `newItemCount` items - /// left in its underlying sequence, then extra items remain available after - /// this method returns. - /// - /// If the operation inserts fewer than `newItemCount` items, then it results - /// in a gap in ring buffer storage that needs to be closed by moving some - /// items to their correct positions given the adjusted count. This adds some - /// overhead compared to adding exactly as many items as promised. - /// - /// - Parameters: - /// - newItemCount: The maximum number of items to insert into the array. - /// - index: The position at which to insert the new items. - /// `index` must be a valid index in the array. - /// - producer: A producer that generates the items to append. - /// - /// - Complexity: O(`self.count` + `newItemCount`) - @_alwaysEmitIntoClient - public mutating func insert< - E: Error, - P: Producer & ~Copyable & ~Escapable - >( - addingCount newItemCount: Int, - from producer: inout P, - at index: Int - ) throws(E) - where P.Element: ~Copyable - { - try insert(addingCount: newItemCount, at: index) { target throws(E) in - while !target.isFull, try producer.generate(into: &target) { - // Do nothing - } - } - } - #endif -} - @available(SwiftStdlib 5.0, *) extension RigidArray { /// Copies the elements of a fully initialized buffer pointer into this @@ -406,82 +330,28 @@ extension RigidArray { } } -#if compiler(>=6.4) && UnstableContainersPreview +#if !UnstableContainersPreview @_alwaysEmitIntoClient - internal mutating func _insertContainer< - C: Container & ~Copyable & ~Escapable - >( - at index: Int, - copying items: borrowing C, - newCount: Int + package mutating func _insertCollection( + addingCount newCount: Int, + copying items: some Collection, + at index: Index ) { - var it = items.makeIterableIterator_() - insert(addingCount: newCount, at: index) { target in - while !target.isFull { - let source = it.nextSpan_(maximumCount: target.freeCapacity) - precondition(!source.isEmpty, "Broken container: mismatching count") - target._append(copying: source) + let done: Void? = items.withContiguousStorageIfAvailable { buffer in + precondition(buffer.count == newCount, "Broken Collection: mismatching count") + self.insert(addingCount: buffer.count, at: index) { target in + target._append(copying: buffer) } } - precondition(it.nextSpan_().isEmpty, "Broken container: mismatching count") - } -#endif - - @inlinable - internal mutating func _insertCollection( - at index: Int, - copying items: some Collection, - newCount: Int - ) { - _checkValidIndex(index) - precondition(newCount <= freeCapacity, "RigidArray capacity overflow") - let gap = unsafe _openGap(at: index, count: newCount) - - let done: Void? = items.withContiguousStorageIfAvailable { buffer in - let i = unsafe gap._initializePrefix(copying: buffer) - precondition( - i == newCount, - "Broken Collection: count doesn't match contents") - _count += newCount - } if done != nil { return } - - var (it, copied) = unsafe items._copyContents(initializing: gap) - precondition( - it.next() == nil && copied == newCount, - "Broken Collection: count doesn't match contents") - _count += newCount - } - -#if compiler(>=6.4) && UnstableContainersPreview - /// Copies the elements of a container into this array at the specified - /// position. - /// - /// The new elements are inserted before the element currently at the - /// specified index. If you pass the array's `endIndex` as the `index` - /// parameter, then the new elements are appended to the end of the array. - /// - /// All existing elements at or following the specified position are moved to - /// make room for the new item. - /// - /// If the capacity of the array isn't sufficient to accommodate the new - /// elements, then this method triggers a runtime error. - /// - /// - Parameters: - /// - newElements: The new elements to insert into the array. - /// - index: The position at which to insert the new elements. It must be - /// a valid index of the array. - /// - /// - 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) + var it = items.makeIterator() + self.insert(addingCount: newCount, at: index) { target in + while !target.isFull { + guard let item = it.next() else { preconditionFailure() } + target.append(item) + } + } + precondition(it.next() == nil, "Broken Collection") } #endif @@ -504,46 +374,16 @@ extension RigidArray { /// a valid index of the array. /// /// - 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 compiler(>=6.4) && UnstableContainersPreview - /// Copies the elements of a container into this array at the specified - /// position. - /// - /// The new elements are inserted before the element currently at the - /// specified index. If you pass the array's `endIndex` as the `index` - /// parameter, then the new elements are appended to the end of the array. - /// - /// All existing elements at or following the specified position are moved to - /// make room for the new item. - /// - /// If the capacity of the array isn't sufficient to accommodate the new - /// elements, then this method triggers a runtime error. - /// - /// - Parameters: - /// - newElements: The new elements to insert into the array. - /// - index: The position at which to insert the new elements. It must be - /// a valid index of the array. - /// - /// - Complexity: O(`self.count` + `newElements.count`) @_alwaysEmitIntoClient @inline(__always) - public mutating func insert< - C: Container & Collection - >( - copying newElements: borrowing C, at index: Int + public mutating func insert( + copying items: some Collection, at index: Int ) { - _insertContainer( - at: index, copying: newElements, newCount: newElements.count) + // FIXME: Remove this -- RangeReplaceContainer already has this algorithm. + // (Note that this would be source breaking while RRC lives in the separate + // ContainersPreview module.) + _insertCollection(addingCount: items.count, copying: items, at: index) } -#endif } #endif diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Removals.swift b/Sources/BasicContainers/RigidArray/RigidArray+Removals.swift index 7770abea..1d502fe6 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Removals.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Removals.swift @@ -114,13 +114,14 @@ extension RigidArray where Element: ~Copyable { /// - Complexity: O(`count`) @_alwaysEmitIntoClient public mutating func removeSubrange(_ bounds: some RangeExpression) { - // FIXME: Remove this in favor of a standard algorithm. + // FIXME: Remove this in favor of the RangeReplaceableContainer algorithm. removeSubrange(bounds.relative(to: indices)) } } @available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { +#if !UnstableContainersPreview /// Removes and returns the last element of the array, if there is one. /// /// - Returns: The last element of the array if the array is not empty; @@ -129,10 +130,11 @@ extension RigidArray where Element: ~Copyable { /// - Complexity: O(1) @_alwaysEmitIntoClient public mutating func popLast() -> Element? { - // FIXME: Remove this in favor of a standard algorithm. + // FIXME: Remove this in favor of the RangeReplaceableContainer algorithm. if isEmpty { return nil } return removeLast() } +#endif } #endif diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Append.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Append.swift index 7a66eddb..bb48b11f 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Append.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Append.swift @@ -132,6 +132,7 @@ extension UniqueArray where Element: ~Copyable { _storage.append(moving: &items) } +#if !UnstableContainersPreview /// Appends the elements of a given array to the end of this array by moving /// them between the containers. On return, the input array becomes empty, but /// it is not destroyed, and it preserves its original storage capacity. @@ -149,70 +150,19 @@ extension UniqueArray where Element: ~Copyable { public mutating func append( moving items: inout RigidArray ) { - // FIXME: Remove this in favor of a generic algorithm over range-replaceable containers _ensureFreeCapacity(items.count) - _storage.append(moving: &items) + items.edit { source in + source.withUnsafeMutableBufferPointer { buffer, count in + _storage.append(moving: buffer._extracting(first: count)) + count = 0 + } + } } +#endif } @available(SwiftStdlib 5.0, *) extension UniqueArray where Element: ~Copyable { -#if UnstableContainersPreview - /// Appends the elements of a given container to the end of this array by - /// consuming the source container. - /// - /// If the target array does not have sufficient capacity to hold all items - /// in the source array, then this automatically grows the target array's - /// capacity, using a geometric growth rate. - /// - /// - Parameters: - /// - items: An array whose items to move to the end of this array. - /// - /// - Complexity: O(`items.count`) - @_alwaysEmitIntoClient - public mutating func append( - consuming items: consuming RigidArray - ) { - // FIXME: Remove this in favor of a generic algorithm over consumable containers - var items = items - self.append(moving: &items) - } -#endif - -#if compiler(>=6.4) && UnstableContainersPreview - /// Appends at most `newItemCount` items generated by a producer to the end of - /// this array. - /// - /// If the array doesn't have sufficient capacity to accommodate the specified - /// number of new elements, then this method reallocates the array's storage - /// to grow it, using a geometric growth rate. - /// - /// This operation appends as many items as the producer can generate before - /// either reaching its end (or throwing an error), or filling the specified - /// capacity. This operation only consumes the first `newItemCount` items in the - /// producer; if the producer has more, then they remain available after this - /// method returns. - /// - /// - Parameters: - /// - newItemCount: The maximum number of items to append to the array. - /// - producer: A producer that generates the items to append. - /// - /// - Complexity: O(*n*) where *n* is the number of new items, when - /// amortized over many similar invocations on the same array. - @_alwaysEmitIntoClient - public mutating func append< - E: Error, - P: Producer & ~Copyable & ~Escapable - >( - addingCount newItemCount: Int, - from producer: inout P - ) throws(E) - where P.Element: ~Copyable - { - _ensureFreeCapacity(newItemCount) - try _storage.append(addingCount: newItemCount, from: &producer) - } -#endif #if compiler(>=6.4) && UnstableContainersPreview /// Appends all the items generated by a producer to the end of this deque. diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Consumption.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Consumption.swift index 01364e04..8b848901 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Consumption.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Consumption.swift @@ -117,7 +117,7 @@ extension UniqueArray where Element: ~Copyable { #endif #if compiler(>=6.4) && UnstableContainersPreview -@available(SwiftStdlib 6.4, *) +@available(SwiftStdlib 5.0, *) extension UniqueArray where Element: ~Copyable { public typealias SubrangeConsumer = RigidArray.SubrangeConsumer diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift index 0483039b..d330f1d0 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift @@ -48,10 +48,10 @@ extension UniqueArray: RandomAccessContainer where Element: ~Copyable {} extension UniqueArray: MutableContainer where Element: ~Copyable {} #if compiler(>=6.4) -@available(SwiftStdlib 6.4, *) +@available(SwiftStdlib 5.0, *) extension UniqueArray: RangeReplaceableContainer where Element: ~Copyable {} -@available(SwiftStdlib 6.4, *) +@available(SwiftStdlib 5.0, *) extension UniqueArray: DynamicContainer where Element: ~Copyable {} #endif #endif diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Insertions.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Insertions.swift index 83d19688..00f052a0 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Insertions.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Insertions.swift @@ -144,6 +144,7 @@ extension UniqueArray where Element: ~Copyable { moving items: inout InputSpan, at index: Int ) { + // FIXME: Remove when InputSpan starts conforming to RangeReplaceableContainer _ensureFreeCapacity(items.count) _storage.insert(moving: &items, at: index) } @@ -171,10 +172,12 @@ extension UniqueArray where Element: ~Copyable { moving items: inout OutputSpan, at index: Int ) { + // FIXME: Remove when OutputSpan starts conforming to RangeReplaceableContainer _ensureFreeCapacity(items.count) _storage.insert(moving: &items, at: index) } +#if !UnstableContainersPreview /// Inserts the elements of a given array into the given position in this /// array by moving them between the containers. On return, the input array /// becomes empty, but it is not destroyed, and it preserves its original @@ -186,6 +189,7 @@ extension UniqueArray where Element: ~Copyable { /// /// - Parameters: /// - items: An array whose contents to move into `self`. + /// - index: The position in `self` at which to insert the new items. /// /// - Complexity: O(`self.count` + `items.count`) @_alwaysEmitIntoClient @@ -197,88 +201,9 @@ extension UniqueArray where Element: ~Copyable { _ensureFreeCapacity(items.count) _storage.insert(moving: &items, at: index) } -} - -@available(SwiftStdlib 5.0, *) -extension UniqueArray where Element: ~Copyable { -#if UnstableContainersPreview - /// Inserts the elements of a given array into the given position in this - /// array by consuming the source container. - /// - /// If the array does not have sufficient capacity to hold all elements, - /// then this reallocates storage to extend its capacity, using a geometric - /// growth rate. - /// - /// - Parameters: - /// - items: A fully initialized buffer whose contents to move into - /// the array. - /// - /// - Complexity: O(`self.count` + `items.count`) - @_alwaysEmitIntoClient - public mutating func insert( - consuming items: consuming RigidArray, - at index: Int - ) { - // FIXME: Remove this in favor of a generic algorithm over consumable containers - // FIXME: Avoid moving the subsequent elements twice. - _ensureFreeCapacity(items.count) - _storage.insert(consuming: items, at: index) - } #endif } -@available(SwiftStdlib 5.0, *) -extension UniqueArray where Element: ~Copyable { -#if compiler(>=6.4) && UnstableContainersPreview - /// Inserts at most `newItemCount` items generated by a producer into this - /// array, starting at the given index. - /// - /// Existing elements in the array's storage are moved as needed to make room - /// for the new items. - /// - /// If the array does not have sufficient capacity to hold enough items, - /// then this reallocates the array's storage to grow its capacity, using a - /// geometric growth rate. - /// - /// This operation inserts as many items as the producer can generate before - /// either reaching `newItemCount`, or the producer hitting its end, or - /// throwing an error. If the producer has more than `newItemCount` items - /// left in its underlying sequence, then extra items remain available after - /// this method returns. - /// - /// If the operation inserts fewer than `newItemCount` items, then it results - /// in a gap in array storage that needs to be closed by moving some - /// items to their correct positions given the adjusted count. This adds some - /// overhead compared to adding exactly as many items as promised. - /// - /// - Parameters: - /// - newItemCount: The maximum number of items to insert into the array. - /// - index: The position at which to insert the new items. - /// `index` must be a valid index in the array. - /// - producer: A producer that generates the items to append. - /// - /// - Complexity: O(`self.count` + `newItemCount`) when amortized over many - /// similar invocations on the same array. - @_alwaysEmitIntoClient - public mutating func insert< - E: Error, - P: Producer & ~Copyable & ~Escapable - >( - addingCount newItemCount: Int, - from producer: inout P, - at index: Int - ) throws(E) - where P.Element: ~Copyable - { - try insert(addingCount: newItemCount, at: index) { target throws(E) in - while !target.isFull, try producer.generate(into: &target) { - // Do nothing - } - } - } - #endif -} - @available(SwiftStdlib 5.0, *) extension UniqueArray { /// Copies the elements of a fully initialized buffer pointer into this @@ -368,42 +293,6 @@ extension UniqueArray { _storage.insert(copying: newElements, at: index) } -#if compiler(>=6.4) && UnstableContainersPreview - /// Copies the elements of a container into this array at the specified - /// position. - /// - /// The new elements are inserted before the element currently at the - /// specified index. If you pass the array's `endIndex` as the `index` - /// parameter, then the new elements are appended to the end of the array. - /// - /// All existing elements at or following the specified position are moved to - /// make room for the new item. - /// - /// If the array does not have sufficient capacity to hold enough elements, - /// then this reallocates the array's storage to extend its capacity, using a - /// geometric growth rate. - /// - /// - Parameters: - /// - newElements: The new elements to insert into the array. - /// - index: The position at which to insert the new elements. It must be - /// a valid index of the array. - /// - /// - Complexity: O(*n* + *m*), where *n* is count of this array and - /// *m* is the count of `newElements`. - @_alwaysEmitIntoClient - @inline(__always) - public mutating func insert< - C: Container & ~Copyable & ~Escapable - >( - copying newElements: borrowing C, at index: Int - ) { - // FIXME: Avoid moving the subsequent elements twice. - let c = newElements.count - _ensureFreeCapacity(c) - _storage._insertContainer(at: index, copying: newElements, newCount: c) - } -#endif - /// Copies the elements of a collection into this array at the specified /// position. /// @@ -428,48 +317,15 @@ extension UniqueArray { public mutating func insert( copying newElements: some Collection, at index: Int ) { + // FIXME: Remove this -- RangeReplaceContainer already has this algorithm. + // (Note that this would be source breaking while RRC lives in the separate + // ContainersPreview module.) // FIXME: Avoid moving the subsequent elements twice. let newCount = newElements.count _ensureFreeCapacity(newCount) _storage._insertCollection( - at: index, copying: newElements, newCount: newCount) + addingCount: newCount, copying: newElements, at: index) } - -#if compiler(>=6.4) && UnstableContainersPreview - /// Copies the elements of a container into this array at the specified - /// position. - /// - /// The new elements are inserted before the element currently at the - /// specified index. If you pass the array's `endIndex` as the `index` - /// parameter, then the new elements are appended to the end of the array. - /// - /// All existing elements at or following the specified position are moved to - /// make room for the new item. - /// - /// If the array does not have sufficient capacity to hold enough elements, - /// then this reallocates the array's storage to extend its capacity, using a - /// geometric growth rate. - /// - /// - Parameters: - /// - newElements: The new elements to insert into the array. - /// - index: The position at which to insert the new elements. It must be - /// a valid index of the array. - /// - /// - Complexity: O(*n* + *m*), where *n* is count of this array and - /// *m* is the count of `newElements`. - @_alwaysEmitIntoClient - @inline(__always) - public mutating func insert< - C: Container & Collection - >( - copying newElements: borrowing C, at index: Int - ) { - // FIXME: Avoid moving the subsequent elements twice. - let c = newElements.count - _ensureFreeCapacity(c) - _storage._insertContainer(at: index, copying: newElements, newCount: c) - } -#endif } #endif diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Removals.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Removals.swift index e910461b..25b488e8 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Removals.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Removals.swift @@ -103,13 +103,14 @@ extension UniqueArray where Element: ~Copyable { /// - Complexity: O(`self.count`) @_alwaysEmitIntoClient public mutating func removeSubrange(_ bounds: some RangeExpression) { - // FIXME: Remove this in favor of a standard algorithm. + // FIXME: Remove this in favor of the RangeReplaceableContainer algorithm. removeSubrange(bounds.relative(to: indices)) } } @available(SwiftStdlib 5.0, *) extension UniqueArray where Element: ~Copyable { +#if !UnstableContainersPreview /// Removes and returns the last element of the array, if there is one. /// /// - Returns: The last element of the array if the array is not empty; @@ -118,9 +119,11 @@ extension UniqueArray where Element: ~Copyable { /// - Complexity: O(1) @_alwaysEmitIntoClient public mutating func popLast() -> Element? { + // FIXME: Remove this in favor of the RangeReplaceableContainer algorithm. if isEmpty { return nil } return removeLast() } +#endif } #endif diff --git a/Sources/ContainersPreview/CMakeLists.txt b/Sources/ContainersPreview/CMakeLists.txt index 81814b02..605be2cb 100644 --- a/Sources/ContainersPreview/CMakeLists.txt +++ b/Sources/ContainersPreview/CMakeLists.txt @@ -64,6 +64,7 @@ target_sources(${module_name} PRIVATE "Protocols/Producer+Reduce.swift" "Types/InputSpan.swift" "Types/MutableRef.swift" + "Types/OutputSpan+Extras.swift" "Types/Shared.swift" "Types/SpanIterator.swift" "Types/UniqueBox.swift" diff --git a/Sources/ContainersPreview/Protocols/Container/Container+Filter.swift b/Sources/ContainersPreview/Protocols/Container/Container+Filter.swift index 85563c04..3fbe82f5 100644 --- a/Sources/ContainersPreview/Protocols/Container/Container+Filter.swift +++ b/Sources/ContainersPreview/Protocols/Container/Container+Filter.swift @@ -19,6 +19,7 @@ import InternalCollectionsUtilities @available(SwiftStdlib 6.4, *) extension Container where Self: ~Copyable /*& ~Escapable*/, Element: ~Copyable { + @_alwaysEmitIntoClient @_lifetime(borrow self) public func _filter( _ isIncluded: @escaping (borrowing Element) -> Bool @@ -29,6 +30,7 @@ extension Container where Self: ~Copyable /*& ~Escapable*/, Element: ~Copyable { @available(SwiftStdlib 6.4, *) extension ContainerIterator where Base.Element: ~Copyable { + @_alwaysEmitIntoClient @_lifetime(copy self) public func filter( _ isIncluded: @escaping (borrowing Element) -> Bool @@ -57,7 +59,7 @@ where Base.Element: ~Copyable @_alwaysEmitIntoClient public var _remainder: Span - @inlinable + @_alwaysEmitIntoClient @_lifetime(copy _base) internal init( _base: Ref, @@ -70,7 +72,7 @@ where Base.Element: ~Copyable self._remainder = .init() } - @inlinable + @_alwaysEmitIntoClient @_lifetime(borrow _base) internal init( _base: borrowing Base, diff --git a/Sources/ContainersPreview/Protocols/Container/Container.swift b/Sources/ContainersPreview/Protocols/Container/Container.swift index e4d0e772..89eb8e6f 100644 --- a/Sources/ContainersPreview/Protocols/Container/Container.swift +++ b/Sources/ContainersPreview/Protocols/Container/Container.swift @@ -249,44 +249,31 @@ extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { /// If the input index is the end index, then this returns an empty span. /// Otherwise the result is non-empty, with its first element matching the /// element at the input index. - @inlinable + @_alwaysEmitIntoClient @_lifetime(borrow self) public func nextSpan(after index: inout Index) -> Span { nextSpan(after: &index, maximumCount: Int.max) } - -// @inlinable -// @_lifetime(borrow self) -// public func nextSpan(after index: inout Index, maximumCount: Int) -> Span { -// let original = index -// var span = nextSpan(after: &index) -// if span.count > maximumCount { -// span = span.extracting(first: maximumCount) -// // Index remains within the same span, so offseting it is expected to be quick -// index = self.index(original, offsetBy: maximumCount) -// } -// return span -// } } @available(SwiftStdlib 5.0, *) extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { - @inlinable + @_alwaysEmitIntoClient public var isEmpty: Bool { startIndex == endIndex } - @inlinable + @_alwaysEmitIntoClient public var count: Int { distance(from: startIndex, to: endIndex) } - @inlinable + @_alwaysEmitIntoClient public func formIndex(after index: inout Index) { index = self.index(after: index) } - @inlinable + @_alwaysEmitIntoClient public func index(_ index: Index, offsetBy n: Int) -> Index { precondition( n >= 0, @@ -328,7 +315,7 @@ extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { #endif } - @inlinable + @_alwaysEmitIntoClient public func formIndex( _ index: inout Index, offsetBy n: inout Int, limitedBy limit: Index ) { @@ -347,7 +334,18 @@ extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { } } - @inlinable + @_alwaysEmitIntoClient + public func index( + _ index: Index, offsetBy n: Int, limitedBy limit: Index + ) -> Index? { + var index = index + var n = n + self.formIndex(&index, offsetBy: &n, limitedBy: limit) + if n != 0 { return nil } + return index + } + + @_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 @@ -400,18 +398,18 @@ extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { #endif } - @inlinable + @_alwaysEmitIntoClient public func index(alignedDown index: Index) -> Index { index } - @inlinable + @_alwaysEmitIntoClient public func index(alignedUp index: Index) -> Index { index } - @inlinable + @_alwaysEmitIntoClient public func _customIndexOfEquatableElement(_: borrowing Element) -> Index?? { nil } - @inlinable + @_alwaysEmitIntoClient public func _customLastIndexOfEquatableElement( _ element: borrowing Element ) -> Index?? { @@ -422,6 +420,7 @@ extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { @available(SwiftStdlib 5.0, *) extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { + @_alwaysEmitIntoClient @_transparent public var underestimatedCount_: Int { count } } diff --git a/Sources/ContainersPreview/Protocols/Container/ContainerIterator.swift b/Sources/ContainersPreview/Protocols/Container/ContainerIterator.swift index d44b67ed..6028bc7a 100644 --- a/Sources/ContainersPreview/Protocols/Container/ContainerIterator.swift +++ b/Sources/ContainersPreview/Protocols/Container/ContainerIterator.swift @@ -20,6 +20,7 @@ where Element: ~Copyable, IterableIterator_ == ContainerIterator { + @_alwaysEmitIntoClient @_lifetime(borrow self) public func makeIterableIterator_() -> IterableIterator_ { ContainerIterator(_borrowing: self, from: self.startIndex) @@ -33,12 +34,16 @@ public struct ContainerIterator< where Base.Element: ~Copyable { public typealias Element = Base.Element - - let _base: Ref // FIXME: This doesn't support nonescapable Bases - var _position: Base.Index + @_alwaysEmitIntoClient + package let _base: Ref // FIXME: This doesn't support nonescapable Bases + + @_alwaysEmitIntoClient + package var _position: Base.Index + + @_alwaysEmitIntoClient @_lifetime(borrow base) - init(_borrowing base: borrowing @_addressable Base, from position: Base.Index) { + package init(_borrowing base: borrowing @_addressable Base, from position: Base.Index) { self._base = Ref(base) self._position = position } @@ -52,12 +57,14 @@ where { public typealias Element_ = Base.Element + @_alwaysEmitIntoClient @_unsafeNonescapableResult // FIXME: we cannot convert from a borrow to an inout dependence?! @_lifetime(&self) public mutating func nextSpan_(maximumCount: Int) -> Span { _base.value.nextSpan(after: &self._position, maximumCount: maximumCount) } + @_alwaysEmitIntoClient @_lifetime(self: copy self) public mutating func skip_(by maximumOffset: Int) -> Int { // FIXME: If we aren't modeling bidirectional iterators, then this should diff --git a/Sources/ContainersPreview/Protocols/Container/DynamicContainer.swift b/Sources/ContainersPreview/Protocols/Container/DynamicContainer.swift index 389f3153..c2b5f6c1 100644 --- a/Sources/ContainersPreview/Protocols/Container/DynamicContainer.swift +++ b/Sources/ContainersPreview/Protocols/Container/DynamicContainer.swift @@ -22,17 +22,33 @@ where Element: ~Copyable mutating func reserveCapacity(_ minimumCapacity: Int) + /// The number of items that can be added to the container without forcing + /// it to allocate extra storage. This is primarily intended to serve as a + /// hint for the batch size of appends, to allow bulk operation even if + /// the number of items to be appended is not known in advance. + /// + /// If the container does not have simple, predictable allocation behavior, + /// then this should return the size of the container's primitive allocation + /// unit. For example, in a balanced rope that organizes its contents into a + /// tree of fixed-capacity nodes, it may be a good choice to use the maximum + /// node size as the (constant) free capacity, even though it may not + /// correlate exactly with actual allocation behavior. + /// + /// If a container always reports a free capacity of 0, then appending a + /// sequence of items of an unknown size may run slower than expected. + /// + /// - Complexity: O(1) var freeCapacity: Int { get } } @available(SwiftStdlib 5.0, *) extension DynamicContainer where Self: ~Copyable, Element: ~Copyable { - @inlinable + @_alwaysEmitIntoClient public init() { self.init(minimumCapacity: 0) } - @inlinable + @_alwaysEmitIntoClient public init( minimumCapacity: Int, initializingWith initializer: (inout OutputSpan) throws(E) -> Void @@ -41,7 +57,7 @@ extension DynamicContainer where Self: ~Copyable, Element: ~Copyable { try self.append(addingCount: minimumCapacity, initializingWith: initializer) } - @inlinable + @_alwaysEmitIntoClient public init< E: Error, P: Producer & ~Copyable & ~Escapable @@ -55,7 +71,7 @@ extension DynamicContainer where Self: ~Copyable, Element: ~Copyable { try self.append(from: producer) } - @inlinable + @_alwaysEmitIntoClient public mutating func append< E: Error, P: Producer & ~Copyable & ~Escapable @@ -66,15 +82,22 @@ extension DynamicContainer where Self: ~Copyable, Element: ~Copyable { { while true { let c = Swift.max(producer.underestimatedCount, self.freeCapacity) - try self.append(addingCount: c) { target throws(E) in - while !target.isFull { - guard try producer.generate(into: &target) else { return } + if c > 0 { + try self.append(addingCount: c) { target throws(E) in + while !target.isFull { + guard try producer.generate(into: &target) else { return } + } } } - // Nudge the container to resize itself, providing more `freeCapacity` in - // the next iteration. Doing this separately avoids forcing the container - // to unnecessarily reallocate itself when the producer is already - // complete. (In exchange, we have to move a handful of items twice.) + // Nudge the container to resize itself, hopefully providing more + // `freeCapacity` in the next iteration. Doing this separately avoids + // forcing the container to unnecessarily reallocate itself when the + // producer is already complete. + // + // In exchange, when neither the producer nor the container provides + // a nonzero count/capacity, then every single item will be added + // individually, resulting in appending all items one by one, but with + // additional overhead spent on the repeared property invocations. guard let next = try producer.next() else { return } self.append(next) } @@ -83,7 +106,7 @@ extension DynamicContainer where Self: ~Copyable, Element: ~Copyable { @available(SwiftStdlib 5.0, *) extension DynamicContainer where Self: ~Copyable, Element: Copyable { - @inlinable + @_alwaysEmitIntoClient public init(repeating repeatedValue: Element, count: Int) { var c = count self.init(minimumCapacity: count) { target in diff --git a/Sources/ContainersPreview/Protocols/Container/MutableContainer.swift b/Sources/ContainersPreview/Protocols/Container/MutableContainer.swift index 3b748578..267352c1 100644 --- a/Sources/ContainersPreview/Protocols/Container/MutableContainer.swift +++ b/Sources/ContainersPreview/Protocols/Container/MutableContainer.swift @@ -95,15 +95,13 @@ where after index: inout Index, maximumCount: Int ) -> MutableSpan - - // FIXME: What about previousMutableSpan? } @available(SwiftStdlib 5.0, *) extension MutableContainer where Self: ~Copyable & ~Escapable, Element: ~Copyable { - @inlinable + @_alwaysEmitIntoClient @_lifetime(&self) mutating func nextMutableSpan( after index: inout Index, diff --git a/Sources/ContainersPreview/Protocols/Container/RangeReplaceableContainer.swift b/Sources/ContainersPreview/Protocols/Container/RangeReplaceableContainer.swift index 22c3db74..d9142942 100644 --- a/Sources/ContainersPreview/Protocols/Container/RangeReplaceableContainer.swift +++ b/Sources/ContainersPreview/Protocols/Container/RangeReplaceableContainer.swift @@ -47,6 +47,10 @@ where mutating func remove(at index: Index) -> Element mutating func removeSubrange(_ bounds: Range) mutating func removeAll() + mutating func removeFirst() -> Element + mutating func removeFirst(_ n: Int) + mutating func _customRemoveLast() -> Element? + mutating func _customRemoveLast(_ n: Int) -> Bool mutating func insert( addingCount newItemCount: Int, @@ -70,7 +74,7 @@ where extension RangeReplaceableContainer where Self: ~Copyable & ~Escapable, Element: ~Copyable { - @inlinable + @_alwaysEmitIntoClient public mutating func remove(at index: Index) -> Element { let range = Range(uncheckedBounds: (index, self.index(after: index))) var result: Element? @@ -83,7 +87,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable return result } - @inlinable + @_alwaysEmitIntoClient public mutating func removeSubrange(_ bounds: Range) { replace( removing: bounds, @@ -92,12 +96,39 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable initializingWith: { _ in }) } - @inlinable - public mutating func removeAll() { - removeSubrange(startIndex ..< endIndex) + @_alwaysEmitIntoClient + public mutating func removeFirst() -> Element { + precondition( + !isEmpty, + "Can't remove first element from an empty container") + return self.remove(at: self.startIndex) } - @inlinable + @_alwaysEmitIntoClient + public mutating func removeFirst(_ n: Int) { + if n == 0 { return } + precondition(n >= 0, "Number of elements to remove should be non-negative") + let start = self.startIndex + guard + let end = self.index(start, offsetBy: n, limitedBy: endIndex) + else { + preconditionFailure( + "Can't remove more items from a container than it has") + } + removeSubrange(start ..< end) + } + + @_alwaysEmitIntoClient + public mutating func _customRemoveLast() -> Element? { + nil + } + + @_alwaysEmitIntoClient + public mutating func _customRemoveLast(_ n: Int) -> Bool { + false + } + + @_alwaysEmitIntoClient public mutating func insert( addingCount newItemCount: Int, at index: Index, @@ -110,7 +141,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable initializingWith: initializer) } - @inlinable + @_alwaysEmitIntoClient public mutating func insert( _ item: consuming Element, at index: Index ) { @@ -120,7 +151,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable } } - @inlinable + @_alwaysEmitIntoClient public mutating func append( addingCount newItemCount: Int, initializingWith initializer: (inout OutputSpan) throws(E) -> Void @@ -131,7 +162,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable initializingWith: initializer) } - @inlinable + @_alwaysEmitIntoClient public mutating func append(_ item: consuming Element) { insert(item, at: endIndex) } @@ -143,7 +174,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable extension RangeReplaceableContainer where Self: ~Copyable & ~Escapable, Element: ~Copyable { - @inlinable + @_alwaysEmitIntoClient public mutating func replace< E: Error, P: Producer & ~Copyable & ~Escapable @@ -164,7 +195,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable }) } - @inlinable + @_alwaysEmitIntoClient public mutating func replace< E: Error, P: CountedProducer & ~Copyable & ~Escapable @@ -183,7 +214,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable } } - @inlinable + @_alwaysEmitIntoClient public mutating func replace( removing subrange: some RangeExpression2, consumingWith consumer: (inout InputSpan) -> Void, @@ -211,7 +242,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable fatalError() } - @inlinable + @_alwaysEmitIntoClient public mutating func replace( removing subrange: some RangeExpression2, addingCount newItemCount: Int, @@ -224,7 +255,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable initializingWith: initializer) } - @inlinable + @_alwaysEmitIntoClient public mutating func replace< C: RangeReplaceableContainer & ~Copyable & ~Escapable >( @@ -234,7 +265,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable replace(removing: targetSubrange, addingFrom: source.consumeAll()) } - @inlinable + @_alwaysEmitIntoClient public mutating func replace< C: RangeReplaceableContainer & ~Copyable & ~Escapable >( @@ -252,7 +283,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable } } - @inlinable + @_alwaysEmitIntoClient public mutating func replace< C: RangeReplaceableContainer & ~Copyable & ~Escapable >( @@ -267,7 +298,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable @available(SwiftStdlib 5.0, *) extension RangeReplaceableContainer where Self: ~Copyable & ~Escapable, Element: ~Copyable { - @inlinable + @_alwaysEmitIntoClient public mutating func consume( _ subrange: Range, consumingWith consumer: (inout InputSpan) -> Void @@ -281,13 +312,13 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { }) } - @inlinable + @_alwaysEmitIntoClient @_lifetime(&self) public mutating func consumeAll() -> SubrangeConsumer { consume(startIndex ..< endIndex) } - @inlinable + @_alwaysEmitIntoClient @_lifetime(&self) public mutating func consume( _ subrange: some RangeExpression2 @@ -305,7 +336,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { fatalError() } - @inlinable + @_alwaysEmitIntoClient @_lifetime(&self) public mutating func consume( _ subrange: UnboundedRange @@ -313,7 +344,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { consume(startIndex ..< endIndex) } - @inlinable + @_alwaysEmitIntoClient @_lifetime(&self) public mutating func consumeFirst(_ n: Int) -> SubrangeConsumer { precondition(n >= 0, "Count of elements to consume is out of bounds") @@ -333,7 +364,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { - @inlinable + @_alwaysEmitIntoClient @_lifetime(&self) public mutating func consumeLast(_ n: Int) -> SubrangeConsumer { precondition(n >= 0, "Count of elements to consume is out of bounds") @@ -350,14 +381,19 @@ where extension RangeReplaceableContainer where Self: ~Copyable & ~Escapable, Element: ~Copyable { - @inlinable + @_alwaysEmitIntoClient + public mutating func removeAll() { + removeSubrange(startIndex ..< endIndex) + } + + @_alwaysEmitIntoClient public mutating func removeSubrange( _ bounds: some RangeExpression2 ) { removeSubrange(bounds.relative(to: self)) } - @inlinable + @_alwaysEmitIntoClient public mutating func removeSubrange( _ bounds: UnboundedRange ) { @@ -365,6 +401,48 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable } } +@available(SwiftStdlib 5.0, *) +extension RangeReplaceableContainer +where Self: BidirectionalContainer & ~Copyable & ~Escapable, Element: ~Copyable +{ + @_alwaysEmitIntoClient + public mutating func removeLast() -> Element { + precondition( + !self.isEmpty, + "Can't remove last element from an empty container") + if let result = self._customRemoveLast() { return result } + return self.remove(at: self.index(before: self.endIndex)) + } + + @_alwaysEmitIntoClient + public mutating func removeLast(_ n: Int) { + if n == 0 { return } + precondition(n >= 0, "Number of elements to remove should be non-negative") + if self._customRemoveLast(n) { + return + } + let end = self.endIndex + guard let start = self.index(end, offsetBy: -n, limitedBy: self.startIndex) + else { + preconditionFailure( + "Can't remove more items from a collection than it contains") + } + self.removeSubrange(start ..< end) + } +} + +@available(SwiftStdlib 5.0, *) +extension RangeReplaceableContainer +where Self: BidirectionalContainer & ~Copyable & ~Escapable, Element: ~Copyable +{ + @_alwaysEmitIntoClient + public mutating func popLast() -> Element? { + if self.isEmpty { return nil } + if let result = self._customRemoveLast() { return result } + return self.remove(at: self.index(before: self.endIndex)) + } +} + @available(SwiftStdlib 5.0, *) extension RangeReplaceableContainer where Self: ~Copyable & ~Escapable, Element: ~Copyable @@ -390,7 +468,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable /// - index: The position at which to insert the new items. /// `index` must be a valid index in the container. /// - producer: A producer that generates the items to append. - @inlinable + @_alwaysEmitIntoClient public mutating func insert< E: Error, P: Producer & ~Copyable & ~Escapable @@ -428,7 +506,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable /// - index: The position at which to insert the new items. /// `index` must be a valid index in the container. /// - producer: A producer that generates the items to append. - @inlinable + @_alwaysEmitIntoClient public mutating func insert< E: Error, P: CountedProducer & ~Copyable & ~Escapable @@ -448,7 +526,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable } } - @inlinable + @_alwaysEmitIntoClient public mutating func insert< C: RangeReplaceableContainer & ~Copyable & ~Escapable >( @@ -458,7 +536,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable self.insert(from: source.consumeAll(), at: index) } - @inlinable + @_alwaysEmitIntoClient public mutating func insert< C: RangeReplaceableContainer & ~Copyable & ~Escapable >( @@ -475,7 +553,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable } } - @inlinable + @_alwaysEmitIntoClient public mutating func insert< C: RangeReplaceableContainer & ~Copyable & ~Escapable >( @@ -504,7 +582,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { /// - Parameters: /// - newItemCount: The number of items to append to the container. /// - producer: A producer that generates the items to append. - @inlinable + @_alwaysEmitIntoClient public mutating func append< E: Error, P: Producer & ~Copyable & ~Escapable @@ -529,7 +607,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { /// /// - Parameters: /// - producer: A producer that generates the items to append. - @inlinable + @_alwaysEmitIntoClient public mutating func append< E: Error, P: CountedProducer & ~Copyable & ~Escapable @@ -552,7 +630,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { /// /// - Parameters: /// - items: A container whose contents to move into this container. - @inlinable + @_alwaysEmitIntoClient public mutating func append< C: RangeReplaceableContainer & ~Copyable & ~Escapable >( @@ -561,7 +639,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { self.append(from: items.consumeAll()) } - @inlinable + @_alwaysEmitIntoClient public mutating func append< C: RangeReplaceableContainer & ~Copyable & ~Escapable >( @@ -585,7 +663,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { /// /// - Parameters: /// - items: A container whose contents to move into this container. - @inlinable + @_alwaysEmitIntoClient public mutating func append< C: RangeReplaceableContainer & ~Copyable & ~Escapable >( @@ -603,7 +681,7 @@ where Self: ~Copyable & ~Escapable, Element: Copyable { - @inlinable + @_alwaysEmitIntoClient public mutating func replace & ~Copyable & ~Escapable>( removing subrange: Range, copying items: borrowing C @@ -760,7 +838,7 @@ where } } - @inlinable + @_alwaysEmitIntoClient public mutating func append< S: Iterable_ & ~Copyable & ~Escapable >( diff --git a/Sources/ContainersPreview/Protocols/Producer+Filter.swift b/Sources/ContainersPreview/Protocols/Producer+Filter.swift index cec00ff5..da668868 100644 --- a/Sources/ContainersPreview/Protocols/Producer+Filter.swift +++ b/Sources/ContainersPreview/Protocols/Producer+Filter.swift @@ -11,6 +11,10 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +#endif + #if compiler(>=6.4) && UnstableContainersPreview @available(SwiftStdlib 5.0, *) diff --git a/Sources/ContainersPreview/Protocols/Producer+Map.swift b/Sources/ContainersPreview/Protocols/Producer+Map.swift index 05bba6be..3e2acba9 100644 --- a/Sources/ContainersPreview/Protocols/Producer+Map.swift +++ b/Sources/ContainersPreview/Protocols/Producer+Map.swift @@ -11,6 +11,10 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +#endif + #if compiler(>=6.4) && UnstableContainersPreview @available(SwiftStdlib 5.0, *) diff --git a/Sources/ContainersPreview/Protocols/Producer+Reduce.swift b/Sources/ContainersPreview/Protocols/Producer+Reduce.swift index 1807dd18..ee9684b2 100644 --- a/Sources/ContainersPreview/Protocols/Producer+Reduce.swift +++ b/Sources/ContainersPreview/Protocols/Producer+Reduce.swift @@ -11,6 +11,10 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +#endif + #if compiler(>=6.4) && UnstableContainersPreview @available(SwiftStdlib 5.0, *) diff --git a/Sources/ContainersPreview/Protocols/Producer.swift b/Sources/ContainersPreview/Protocols/Producer.swift index eb848282..737f30cb 100644 --- a/Sources/ContainersPreview/Protocols/Producer.swift +++ b/Sources/ContainersPreview/Protocols/Producer.swift @@ -11,6 +11,10 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +#endif + #if compiler(>=6.4) && UnstableContainersPreview @_alwaysEmitIntoClient diff --git a/Sources/ContainersPreview/Types/OutputSpan+Extras.swift b/Sources/ContainersPreview/Types/OutputSpan+Extras.swift new file mode 100644 index 00000000..0e2bfdb8 --- /dev/null +++ b/Sources/ContainersPreview/Types/OutputSpan+Extras.swift @@ -0,0 +1,51 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// 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 +// +// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +#endif + +#if compiler(>=6.2) && UnstableContainersPreview +@available(SwiftStdlib 5.0, *) +extension OutputSpan where Element: ~Copyable { + @_lifetime(source: copy source) + @inlinable + @inline(__always) + @_lifetime(self: copy self) + package mutating func _append(moving source: inout InputSpan) { + // FIXME: This needs to be in the stdlib. + source.withUnsafeMutableBufferPointer { src, srcCount in + let srcItems = src._extracting( + uncheckedFrom: src.count &- srcCount, + to: src.count) + self._append(moving: srcItems) + srcCount = 0 + } + } + + @_alwaysEmitIntoClient + @_lifetime(self: copy self) + package mutating func _consumeAll( + consumingWith consumer: (inout InputSpan) -> Void + ) { + self.withUnsafeMutableBufferPointer { buffer, count in + var span = InputSpan( + buffer: buffer._extracting(first: count), + initializedCount: count) + consumer(&span) + _ = consume span + count = 0 + } + } +} +#endif diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Consumption.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Consumption.swift index 92de4c9c..5a014007 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Consumption.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Consumption.swift @@ -167,7 +167,7 @@ extension RigidDeque where Element: ~Copyable { #if compiler(>=6.4) && UnstableContainersPreview @available(SwiftStdlib 5.0, *) extension RigidDeque where Element: ~Copyable { - @available(SwiftStdlib 6.4, *) + @available(SwiftStdlib 5.0, *) @_alwaysEmitIntoClient @inline(__always) @_lifetime(&self) @@ -178,7 +178,7 @@ extension RigidDeque where Element: ~Copyable { @available(SwiftStdlib 5.0, *) extension RigidDeque where Element: ~Copyable { - @available(SwiftStdlib 6.4, *) + @available(SwiftStdlib 5.0, *) @frozen public struct SubrangeConsumer: ~Copyable, ~Escapable { // FIXME: We have to use our own MutableRef because the standard one @@ -221,11 +221,11 @@ extension RigidDeque where Element: ~Copyable { } } -@available(SwiftStdlib 6.4, *) +@available(SwiftStdlib 5.0, *) extension RigidDeque.SubrangeConsumer: Drain where Element: ~Copyable { } -@available(SwiftStdlib 6.4, *) +@available(SwiftStdlib 5.0, *) extension RigidDeque.SubrangeConsumer where Element: ~Copyable { @inlinable public var count: Int { diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift index 2e7aa125..e11cfa0c 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift @@ -77,10 +77,10 @@ extension RigidDeque: BidirectionalContainer where Element: ~Copyable {} extension RigidDeque: RandomAccessContainer where Element: ~Copyable {} #if compiler(>=6.4) -@available(SwiftStdlib 6.4, *) +@available(SwiftStdlib 5.0, *) extension RigidDeque: MutableContainer where Element: ~Copyable {} -@available(SwiftStdlib 6.4, *) +@available(SwiftStdlib 5.0, *) extension RigidDeque: RangeReplaceableContainer where Element: ~Copyable {} #endif #endif diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Hashable.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Hashable.swift index acec6cd3..3659a1b6 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Hashable.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Hashable.swift @@ -17,6 +17,7 @@ import InternalCollectionsUtilities #endif +#if compiler(>=6.4) && UnstableContainersPreview @available(SwiftStdlib 6.4, *) extension RigidDeque: Hashable where Element: Hashable & ~Copyable { } @@ -33,5 +34,19 @@ extension RigidDeque where Element: Hashable & ~Copyable { } } } +#else +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: Hashable { + @inlinable + public func hash(into hasher: inout Hasher) { + hasher.combine(self.count) + let segments = self._handle.segments() + segments.first.span._hashContents(into: &hasher) + if let second = segments.second { + second.span._hashContents(into: &hasher) + } + } +} +#endif #endif diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Removals.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Removals.swift index 1ce0d2cd..ea5c1d1a 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Removals.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Removals.swift @@ -59,7 +59,13 @@ extension RigidDeque where Element: ~Copyable { precondition(!isEmpty, "Cannot remove first element of an empty RigidDeque") return _handle.uncheckedRemoveFirst() } - + + @_alwaysEmitIntoClient + public mutating func _customRemoveLast() -> Element? { + precondition(!isEmpty, "Cannot remove last element of an empty RigidDeque") + return _handle.uncheckedRemoveLast() + } + /// Removes and returns the last element of the deque. /// /// The deque must not be empty. @@ -91,7 +97,15 @@ extension RigidDeque where Element: ~Copyable { precondition(k <= count, "Cannot remove more elements than there are in the container") _handle.uncheckedRemoveFirst(k) } - + + @_alwaysEmitIntoClient + public mutating func _customRemoveLast(_ n: Int) -> Bool { + precondition(n >= 0, "Cannot remove a negative number of elements") + precondition(n <= count, "Cannot remove more elements than there are in the container") + _handle.uncheckedRemoveLast(n) + return true + } + /// Removes and discards the specified number of elements from the end of the /// deque. /// @@ -139,6 +153,7 @@ extension RigidDeque where Element: ~Copyable { return _handle.uncheckedRemoveFirst() } +#if !UnstableContainersPreview /// Removes and returns the last element of the deque, if there is one. /// /// - Returns: The last element of the original deque if it was not empty; @@ -150,6 +165,7 @@ extension RigidDeque where Element: ~Copyable { guard !isEmpty else { return nil } return _handle.uncheckedRemoveLast() } +#endif } #endif diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Consumption.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Consumption.swift index cc3f0d39..ffe09acb 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Consumption.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Consumption.swift @@ -148,7 +148,7 @@ extension UniqueDeque where Element: ~Copyable { } #if compiler(>=6.4) && UnstableContainersPreview -@available(SwiftStdlib 6.4, *) +@available(SwiftStdlib 5.0, *) extension UniqueDeque where Element: ~Copyable { public typealias SubrangeConsumer = RigidDeque.SubrangeConsumer diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift index 3124ebef..7922a568 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift @@ -46,10 +46,10 @@ extension UniqueDeque: RandomAccessContainer where Element: ~Copyable {} extension UniqueDeque: MutableContainer where Element: ~Copyable {} #if compiler(>=6.4) -@available(SwiftStdlib 6.4, *) +@available(SwiftStdlib 5.0, *) extension UniqueDeque: RangeReplaceableContainer where Element: ~Copyable {} -@available(SwiftStdlib 6.4, *) +@available(SwiftStdlib 5.0, *) extension UniqueDeque: DynamicContainer where Element: ~Copyable {} #endif #endif diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Hashable.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Hashable.swift index 32c19298..350a0004 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Hashable.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Hashable.swift @@ -13,6 +13,7 @@ #if compiler(>=6.2) +#if compiler(>=6.4) && UnstableContainersPreview @available(SwiftStdlib 6.4, *) extension UniqueDeque: Hashable where Element: Hashable & ~Copyable { } @@ -24,5 +25,14 @@ extension UniqueDeque where Element: Hashable & ~Copyable { self._storage.hash(into: &hasher) } } +#else +@available(SwiftStdlib 5.0, *) +extension UniqueDeque where Element: Hashable { + @inlinable + public func hash(into hasher: inout Hasher) { + self._storage.hash(into: &hasher) + } +} +#endif #endif diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Removals.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Removals.swift index a8b3d543..c86c82a5 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Removals.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Removals.swift @@ -136,6 +136,7 @@ extension UniqueDeque where Element: ~Copyable { _storage.popFirst() } +#if !UnstableContainersPreview /// Removes and returns the last element of the deque, if there is one. /// /// - Returns: The last element of the original deque if it was not empty; @@ -147,6 +148,7 @@ extension UniqueDeque where Element: ~Copyable { public mutating func popLast() -> Element? { _storage.popLast() } +#endif } #endif diff --git a/Sources/InternalCollectionsUtilities/OutputSpan+Extras.swift b/Sources/InternalCollectionsUtilities/OutputSpan+Extras.swift index dd2396d9..db015f28 100644 --- a/Sources/InternalCollectionsUtilities/OutputSpan+Extras.swift +++ b/Sources/InternalCollectionsUtilities/OutputSpan+Extras.swift @@ -67,23 +67,6 @@ extension OutputSpan where Element: ~Copyable { } } -#if UnstableContainersPreview - @_lifetime(source: copy source) - @inlinable - @inline(__always) - @_lifetime(self: copy self) - package mutating func _append(moving source: inout InputSpan) { - // FIXME: This needs to be in the stdlib. - source.withUnsafeMutableBufferPointer { src, srcCount in - let srcItems = src._extracting( - uncheckedFrom: src.count &- srcCount, - to: src.count) - self._append(moving: srcItems) - srcCount = 0 - } - } -#endif - @_lifetime(source: copy source) @inlinable @inline(__always) @@ -154,26 +137,5 @@ extension OutputSpan where Element: ~Copyable { } } -#if UnstableContainersPreview - -@available(SwiftStdlib 5.0, *) -extension OutputSpan where Element: ~Copyable { - @_alwaysEmitIntoClient - @_lifetime(self: copy self) - package mutating func _consumeAll( - consumingWith consumer: (inout InputSpan) -> Void - ) { - self.withUnsafeMutableBufferPointer { buffer, count in - var span = InputSpan( - buffer: buffer._extracting(first: count), - initializedCount: count) - consumer(&span) - _ = consume span - count = 0 - } - } -} -#endif - #endif diff --git a/Sources/InternalCollectionsUtilities/Span+Extras.swift b/Sources/InternalCollectionsUtilities/Span+Extras.swift index a7742688..de5d7ddc 100644 --- a/Sources/InternalCollectionsUtilities/Span+Extras.swift +++ b/Sources/InternalCollectionsUtilities/Span+Extras.swift @@ -38,7 +38,7 @@ extension Span where Element: ~Copyable { } } -#if compiler(>=6.4) && UnstableContainersPreview +#if compiler(>=6.4) @available(SwiftStdlib 5.0, *) extension Span where Element: Equatable & ~Copyable { @_alwaysEmitIntoClient @@ -78,7 +78,7 @@ extension Span where Element: Equatable /* & ~Copyable */ { } #endif -#if compiler(>=6.4) && UnstableContainersPreview +#if compiler(>=6.4) @available(SwiftStdlib 5.0, *) extension Span where Element: Hashable & ~Copyable { @_alwaysEmitIntoClient diff --git a/Xcode/Collections.xcodeproj/project.pbxproj b/Xcode/Collections.xcodeproj/project.pbxproj index ae8ff6ec..f0ee3b97 100644 --- a/Xcode/Collections.xcodeproj/project.pbxproj +++ b/Xcode/Collections.xcodeproj/project.pbxproj @@ -7,6 +7,7 @@ objects = { /* Begin PBXBuildFile section */ + 7D12E33D2FF5CC2A003050AB /* OutputSpan+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D12E33C2FF5CC2A003050AB /* OutputSpan+Extras.swift */; }; 7D24E3ED2FAD4C37005A55EB /* RigidArray+Formatter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D24E3EC2FAD4C37005A55EB /* RigidArray+Formatter.swift */; }; 7D2A77262F27F1D1005780C7 /* Span+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77252F27F1D1005780C7 /* Span+Extras.swift */; }; 7D2A77392F27F1E4005780C7 /* UniqueBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77332F27F1E4005780C7 /* UniqueBox.swift */; }; @@ -133,6 +134,10 @@ 7D59D05C2FE48B89005B5097 /* Optional+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D59D0592FE48B89005B5097 /* Optional+Extras.swift */; }; 7D59D05D2FE48B89005B5097 /* OutputSpan+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D59D05A2FE48B89005B5097 /* OutputSpan+Extras.swift */; }; 7D59D05E2FE48B89005B5097 /* TemporaryAllocation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D59D05B2FE48B89005B5097 /* TemporaryAllocation.swift */; }; + 7D59D0662FE49C87005B5097 /* Span+Container.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D59D0642FE49C87005B5097 /* Span+Container.swift */; }; + 7D59D0672FE49C87005B5097 /* InputSpan+Container.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D59D0612FE49C87005B5097 /* InputSpan+Container.swift */; }; + 7D59D0682FE49C87005B5097 /* MutableSpan+Container.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D59D0622FE49C87005B5097 /* MutableSpan+Container.swift */; }; + 7D59D0692FE49C87005B5097 /* OutputSpan+Container.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D59D0632FE49C87005B5097 /* OutputSpan+Container.swift */; }; 7D7246872F3D9DDB00112FD0 /* _HTable+Iteration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D7246802F3D9DDB00112FD0 /* _HTable+Iteration.swift */; }; 7D7246882F3D9DDB00112FD0 /* RigidDictionary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D7246832F3D9DDB00112FD0 /* RigidDictionary.swift */; }; 7D7246892F3D9DDB00112FD0 /* _HTable+Find.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D72467E2F3D9DDB00112FD0 /* _HTable+Find.swift */; }; @@ -147,6 +152,8 @@ 7D7646062FAAA2B9008639E5 /* UniqueBoxTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D7646052FAAA2B9008639E5 /* UniqueBoxTests.swift */; }; 7D7646082FAAABE3008639E5 /* UniqueDeque+Deprecated.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D7646072FAAABDF008639E5 /* UniqueDeque+Deprecated.swift */; }; 7D77E6122FCF810E003FA63B /* CountedProducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D77E6112FCF810E003FA63B /* CountedProducer.swift */; }; + 7D77E6252FD0F880003FA63B /* UnsafePointer+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D77E6242FD0F87B003FA63B /* UnsafePointer+Extras.swift */; }; + 7D77E6272FD0F94B003FA63B /* UnsafeMutablePointer+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D77E6262FD0F940003FA63B /* UnsafeMutablePointer+Extras.swift */; }; 7D9748D42E9748930098631A /* BigString+Chunk+UTF16.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9748D32E9748930098631A /* BigString+Chunk+UTF16.swift */; }; 7D9748D52E9748930098631A /* BigString+Chunk+UnicodeScalar.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9748D12E9748930098631A /* BigString+Chunk+UnicodeScalar.swift */; }; 7D9748D62E9748930098631A /* BigString+Chunk+Character.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9748CF2E9748930098631A /* BigString+Chunk+Character.swift */; }; @@ -609,6 +616,7 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ + 7D12E33C2FF5CC2A003050AB /* OutputSpan+Extras.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "OutputSpan+Extras.swift"; sourceTree = ""; }; 7D24E3EC2FAD4C37005A55EB /* RigidArray+Formatter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidArray+Formatter.swift"; sourceTree = ""; }; 7D24E9862FAD53E1005A55EB /* RigidArray_Fixture.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RigidArray_Fixture.swift; sourceTree = ""; }; 7D24E9882FAD53E1005A55EB /* Package.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Package.swift; sourceTree = ""; }; @@ -703,7 +711,6 @@ 7D479CFA2F4D080500A8CB59 /* UniqueDictionary+Keys.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueDictionary+Keys.swift"; sourceTree = ""; }; 7D479CFB2F4D080500A8CB59 /* UniqueDictionary+Removals.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueDictionary+Removals.swift"; sourceTree = ""; }; 7D479CFE2F4E487700A8CB59 /* RigidSet+Equatable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidSet+Equatable.swift"; sourceTree = ""; }; - 7D48BCC92E51524200D7F6F7 /* CMakeLists.txt */ = {isa = PBXFileReference; lastKnownFileType = text; path = CMakeLists.txt; sourceTree = ""; }; 7D48BCDB2E51554900D7F6F7 /* ClassBox.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClassBox.swift; sourceTree = ""; }; 7D48BCDD2E51558700D7F6F7 /* TestPrintable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TestPrintable.swift; sourceTree = ""; }; 7D48BCDE2E51558700D7F6F7 /* LifetimeTrackedStruct.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LifetimeTrackedStruct.swift; sourceTree = ""; }; @@ -744,6 +751,11 @@ 7D59D0592FE48B89005B5097 /* Optional+Extras.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Optional+Extras.swift"; sourceTree = ""; }; 7D59D05A2FE48B89005B5097 /* OutputSpan+Extras.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "OutputSpan+Extras.swift"; sourceTree = ""; }; 7D59D05B2FE48B89005B5097 /* TemporaryAllocation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TemporaryAllocation.swift; sourceTree = ""; }; + 7D59D0602FE49BDA005B5097 /* CMakeLists.txt */ = {isa = PBXFileReference; lastKnownFileType = text; path = CMakeLists.txt; sourceTree = ""; }; + 7D59D0612FE49C87005B5097 /* InputSpan+Container.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "InputSpan+Container.swift"; sourceTree = ""; }; + 7D59D0622FE49C87005B5097 /* MutableSpan+Container.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "MutableSpan+Container.swift"; sourceTree = ""; }; + 7D59D0632FE49C87005B5097 /* OutputSpan+Container.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "OutputSpan+Container.swift"; sourceTree = ""; }; + 7D59D0642FE49C87005B5097 /* Span+Container.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Span+Container.swift"; sourceTree = ""; }; 7D5A64D229CCE8CC00CB2595 /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; 7D5A64D329CCEE9A00CB2595 /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; 7D5A64D829CCF0FE00CB2595 /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; @@ -763,6 +775,8 @@ 7D7646052FAAA2B9008639E5 /* UniqueBoxTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UniqueBoxTests.swift; sourceTree = ""; }; 7D7646072FAAABDF008639E5 /* UniqueDeque+Deprecated.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueDeque+Deprecated.swift"; sourceTree = ""; }; 7D77E6112FCF810E003FA63B /* CountedProducer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CountedProducer.swift; sourceTree = ""; }; + 7D77E6242FD0F87B003FA63B /* UnsafePointer+Extras.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UnsafePointer+Extras.swift"; sourceTree = ""; }; + 7D77E6262FD0F940003FA63B /* UnsafeMutablePointer+Extras.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UnsafeMutablePointer+Extras.swift"; sourceTree = ""; }; 7D9748CF2E9748930098631A /* BigString+Chunk+Character.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BigString+Chunk+Character.swift"; sourceTree = ""; }; 7D9748D02E9748930098631A /* BigString+Chunk+Index.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BigString+Chunk+Index.swift"; sourceTree = ""; }; 7D9748D12E9748930098631A /* BigString+Chunk+UnicodeScalar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BigString+Chunk+UnicodeScalar.swift"; sourceTree = ""; }; @@ -978,7 +992,6 @@ 7DE91F1F29CA70F3004483EB /* _CharacterRecognizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _CharacterRecognizer.swift; sourceTree = ""; }; 7DE91F2029CA70F3004483EB /* String.Index+ABI.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "String.Index+ABI.swift"; sourceTree = ""; }; 7DE91F2129CA70F3004483EB /* Optional Utilities.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Optional Utilities.swift"; sourceTree = ""; }; - 7DE91F2E29CA70F3004483EB /* CMakeLists.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = CMakeLists.txt; sourceTree = ""; }; 7DE91F3029CA70F3004483EB /* _SortedCollection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _SortedCollection.swift; sourceTree = ""; }; 7DE91F3829CA70F3004483EB /* _UniqueCollection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _UniqueCollection.swift; sourceTree = ""; }; 7DE91F3B29CA70F3004483EB /* BitSet+SetAlgebra symmetricDifference.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitSet+SetAlgebra symmetricDifference.swift"; sourceTree = ""; }; @@ -1238,6 +1251,7 @@ 7DFA40832FD3A98D00CD20C1 /* OrderedSet+Move.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "OrderedSet+Move.swift"; sourceTree = ""; }; 7DFA40852FD3A99D00CD20C1 /* OrderedDictionary+Move.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "OrderedDictionary+Move.swift"; sourceTree = ""; }; 7DFA40892FD3ACE700CD20C1 /* UnsafeBufferTrimTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UnsafeBufferTrimTests.swift; sourceTree = ""; }; + 7DFC9DF62FEB5D7D00BE8808 /* CMakeLists.txt */ = {isa = PBXFileReference; lastKnownFileType = text; path = CMakeLists.txt; sourceTree = ""; }; A93AC20F2E7C841700A824DF /* CMakeLists.txt */ = {isa = PBXFileReference; lastKnownFileType = text; path = CMakeLists.txt; sourceTree = ""; }; A93AC21A2E7C845300A824DF /* ArrayLayout.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ArrayLayout.swift; sourceTree = ""; }; A93AC21B2E7C845300A824DF /* RigidArrayTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RigidArrayTests.swift; sourceTree = ""; }; @@ -1340,6 +1354,7 @@ children = ( 7D2A77332F27F1E4005780C7 /* UniqueBox.swift */, 7DC037C82FE3792300CF0CB8 /* MutableRef.swift */, + 7D12E33C2FF5CC2A003050AB /* OutputSpan+Extras.swift */, 7D2A77352F27F1E4005780C7 /* InputSpan.swift */, 7D2A77362F27F1E4005780C7 /* Shared.swift */, 7DACFA112F75FBF100291F2E /* SpanIterator.swift */, @@ -1452,9 +1467,10 @@ 7D48BCCE2E51524200D7F6F7 /* ContainersPreview */ = { isa = PBXGroup; children = ( + 7D59D0602FE49BDA005B5097 /* CMakeLists.txt */, + 7D59D0652FE49C87005B5097 /* Conformances */, 7D2A77312F27F1E4005780C7 /* Protocols */, 7D2A77372F27F1E4005780C7 /* Types */, - 7D48BCC92E51524200D7F6F7 /* CMakeLists.txt */, 7D6FEE312E88A4B9007C1B86 /* ContainersPreview.docc */, ); path = ContainersPreview; @@ -1490,6 +1506,17 @@ path = Container; sourceTree = ""; }; + 7D59D0652FE49C87005B5097 /* Conformances */ = { + isa = PBXGroup; + children = ( + 7D59D0612FE49C87005B5097 /* InputSpan+Container.swift */, + 7D59D0622FE49C87005B5097 /* MutableSpan+Container.swift */, + 7D59D0632FE49C87005B5097 /* OutputSpan+Container.swift */, + 7D59D0642FE49C87005B5097 /* Span+Container.swift */, + ); + path = Conformances; + sourceTree = ""; + }; 7D7246822F3D9DDB00112FD0 /* HashTable */ = { isa = PBXGroup; children = ( @@ -1941,6 +1968,7 @@ children = ( 7DEBDAE229CBEE5300ADC226 /* IntegerTricks */, 7DEBDADA29CBEE5300ADC226 /* UnsafeBitSet */, + 7DFC9DF62FEB5D7D00BE8808 /* CMakeLists.txt */, 7DE91F3029CA70F3004483EB /* _SortedCollection.swift */, 7DE91F3829CA70F3004483EB /* _UniqueCollection.swift */, 7DAD89A82E8B09EC00DD5786 /* Debugging.swift */, @@ -1956,7 +1984,8 @@ 7DAD89AD2E8B09EC00DD5786 /* UnsafeMutableBufferPointer+Extras.swift */, 7DAD89AE2E8B09EC00DD5786 /* UnsafeMutableRawBufferPointer+Extras.swift */, 7DAD89AF2E8B09EC00DD5786 /* UnsafeRawBufferPointer+Extras.swift */, - 7DE91F2E29CA70F3004483EB /* CMakeLists.txt */, + 7D77E6242FD0F87B003FA63B /* UnsafePointer+Extras.swift */, + 7D77E6262FD0F940003FA63B /* UnsafeMutablePointer+Extras.swift */, ); path = InternalCollectionsUtilities; sourceTree = ""; @@ -2685,6 +2714,7 @@ 7D2A77952F27F2BF005780C7 /* Deque+Codable.swift in Sources */, 7D2A77962F27F2BF005780C7 /* RigidDeque+Experimental.swift in Sources */, 7D2A77972F27F2BF005780C7 /* Deque+Testing.swift in Sources */, + 7D12E33D2FF5CC2A003050AB /* OutputSpan+Extras.swift in Sources */, 7D2A77982F27F2BF005780C7 /* RigidDeque+Replacements.swift in Sources */, 7D7246872F3D9DDB00112FD0 /* _HTable+Iteration.swift in Sources */, 7D7246882F3D9DDB00112FD0 /* RigidDictionary.swift in Sources */, @@ -2718,6 +2748,7 @@ 7D57A2B82F33FF48002543BD /* RigidArray+Consumption.swift in Sources */, 7DA23F582F32C66300E4C03A /* RigidArray+Equatable.swift in Sources */, 7D479CFC2F4D080500A8CB59 /* UniqueDictionary+Removals.swift in Sources */, + 7D77E6272FD0F94B003FA63B /* UnsafeMutablePointer+Extras.swift in Sources */, 7D479CFD2F4D080500A8CB59 /* UniqueDictionary+Keys.swift in Sources */, 7DE9208A29CA70F4004483EB /* BigString+Comparable.swift in Sources */, 7DE9213629CA70F4004483EB /* TreeSet+SetAlgebra basics.swift in Sources */, @@ -2731,6 +2762,7 @@ 7DE9204629CA70F3004483EB /* _Hashtable+Header.swift in Sources */, 7DE9208129CA70F4004483EB /* BigString+CustomStringConvertible.swift in Sources */, 7DE920A929CA70F4004483EB /* Optional Utilities.swift in Sources */, + 7D77E6252FD0F880003FA63B /* UnsafePointer+Extras.swift in Sources */, 7DE920BD29CA70F4004483EB /* BitSet+SetAlgebra symmetricDifference.swift in Sources */, 7DE9208229CA70F4004483EB /* BigString+BidirectionalCollection.swift in Sources */, 7D479CDF2F47D5CA00A8CB59 /* RigidDictionary+Insertions.swift in Sources */, @@ -3054,6 +3086,10 @@ 7DE9217E29CA70F4004483EB /* Heap+ExpressibleByArrayLiteral.swift in Sources */, 7D57EDD32F647DB10029D5E3 /* RandomAccessContainer.swift in Sources */, 7D57EDD52F647DB10029D5E3 /* MutableContainer.swift in Sources */, + 7D59D0662FE49C87005B5097 /* Span+Container.swift in Sources */, + 7D59D0672FE49C87005B5097 /* InputSpan+Container.swift in Sources */, + 7D59D0682FE49C87005B5097 /* MutableSpan+Container.swift in Sources */, + 7D59D0692FE49C87005B5097 /* OutputSpan+Container.swift in Sources */, 7D57EDD62F647DB10029D5E3 /* DynamicContainer.swift in Sources */, 7D57EDD72F647DB10029D5E3 /* Drain+Reduce.swift in Sources */, 7D57EDD82F647DB10029D5E3 /* Producer+Map.swift in Sources */, diff --git a/Xcode/Collections.xcodeproj/xcshareddata/xcschemes/Collections.xcscheme b/Xcode/Collections.xcodeproj/xcshareddata/xcschemes/Collections.xcscheme index 48e313d4..afc31473 100644 --- a/Xcode/Collections.xcodeproj/xcshareddata/xcschemes/Collections.xcscheme +++ b/Xcode/Collections.xcodeproj/xcshareddata/xcschemes/Collections.xcscheme @@ -1,6 +1,6 @@ Date: Wed, 1 Jul 2026 16:01:14 -0700 Subject: [PATCH 19/50] =?UTF-8?q?IterableIteratorProtocol=5F=20=E2=86=92?= =?UTF-8?q?=20BorrowingIteratorProtocol=5F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../RigidDictionary+Indices.swift | 2 +- .../RigidSet/RigidSet+BorrowingSequence.swift | 2 +- Sources/ContainersPreview/CMakeLists.txt | 16 ++--- ...t => BorrowingIteratorProtocol+Copy.swift} | 2 +- ...owingIteratorProtocol+ElementsEqual.swift} | 10 +-- ...=> BorrowingIteratorProtocol+Filter.swift} | 6 +- ...ft => BorrowingIteratorProtocol+Map.swift} | 4 +- ... BorrowingIteratorProtocol+MapError.swift} | 6 +- ...=> BorrowingIteratorProtocol+Reduce.swift} | 2 +- ...rrowingIteratorProtocol+SpanwiseZip.swift} | 4 +- ....swift => BorrowingIteratorProtocol.swift} | 10 +-- .../Container/Container+Filter.swift | 2 +- .../Container/ContainerIterator.swift | 2 +- .../Iterable+Standard Conformances.swift | 4 +- .../Protocols/Iterable.swift | 2 +- .../Types/SpanIterator.swift | 2 +- .../RigidDeque/RigidDeque+Container.swift | 2 +- .../MinimalTypes/StaccatoContainer.swift | 2 +- Xcode/Collections.xcodeproj/project.pbxproj | 64 +++++++++---------- 19 files changed, 72 insertions(+), 72 deletions(-) rename Sources/ContainersPreview/Protocols/{IterableIteratorProtocol+Copy.swift => BorrowingIteratorProtocol+Copy.swift} (98%) rename Sources/ContainersPreview/Protocols/{IterableIteratorProtocol+ElementsEqual.swift => BorrowingIteratorProtocol+ElementsEqual.swift} (95%) rename Sources/ContainersPreview/Protocols/{IterableIteratorProtocol+Filter.swift => BorrowingIteratorProtocol+Filter.swift} (92%) rename Sources/ContainersPreview/Protocols/{IterableIteratorProtocol+Map.swift => BorrowingIteratorProtocol+Map.swift} (97%) rename Sources/ContainersPreview/Protocols/{IterableIteratorProtocol+MapError.swift => BorrowingIteratorProtocol+MapError.swift} (93%) rename Sources/ContainersPreview/Protocols/{IterableIteratorProtocol+Reduce.swift => BorrowingIteratorProtocol+Reduce.swift} (97%) rename Sources/ContainersPreview/Protocols/{IterableIteratorProtocol+SpanwiseZip.swift => BorrowingIteratorProtocol+SpanwiseZip.swift} (96%) rename Sources/ContainersPreview/Protocols/{IterableIteratorProtocol.swift => BorrowingIteratorProtocol.swift} (95%) diff --git a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Indices.swift b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Indices.swift index 198e3606..6563d56d 100644 --- a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Indices.swift +++ b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Indices.swift @@ -82,7 +82,7 @@ where Key: ~Copyable, Value: ~Copyable } @available(SwiftStdlib 6.4, *) -extension RigidDictionary.Indices.IterableIterator_: IterableIteratorProtocol_ +extension RigidDictionary.Indices.IterableIterator_: BorrowingIteratorProtocol_ where Key: ~Copyable, Value: ~Copyable { public typealias Element_ = Element diff --git a/Sources/BasicContainers/RigidSet/RigidSet+BorrowingSequence.swift b/Sources/BasicContainers/RigidSet/RigidSet+BorrowingSequence.swift index 555248de..dcda6311 100644 --- a/Sources/BasicContainers/RigidSet/RigidSet+BorrowingSequence.swift +++ b/Sources/BasicContainers/RigidSet/RigidSet+BorrowingSequence.swift @@ -39,7 +39,7 @@ extension RigidSet: Iterable_ where Element: ~Copyable { @frozen public struct IterableIterator_: - IterableIteratorProtocol_, + BorrowingIteratorProtocol_, ~Copyable, ~Escapable { diff --git a/Sources/ContainersPreview/CMakeLists.txt b/Sources/ContainersPreview/CMakeLists.txt index 605be2cb..2e2a478c 100644 --- a/Sources/ContainersPreview/CMakeLists.txt +++ b/Sources/ContainersPreview/CMakeLists.txt @@ -41,14 +41,14 @@ target_sources(${module_name} PRIVATE "Protocols/Container/RangeExpression2.swift" "Protocols/Container/RangeReplaceableContainer.swift" "Protocols/Container/Strideable+Limits.swift" - "Protocols/IterableIteratorProtocol.swift" - "Protocols/IterableIteratorProtocol+Copy.swift" - "Protocols/IterableIteratorProtocol+ElementsEqual.swift" - "Protocols/IterableIteratorProtocol+Filter.swift" - "Protocols/IterableIteratorProtocol+Map.swift" - "Protocols/IterableIteratorProtocol+MapError.swift" - "Protocols/IterableIteratorProtocol+Reduce.swift" - "Protocols/IterableIteratorProtocol+SpanwiseZip.swift" + "Protocols/BorrowingIteratorProtocol.swift" + "Protocols/BorrowingIteratorProtocol+Copy.swift" + "Protocols/BorrowingIteratorProtocol+ElementsEqual.swift" + "Protocols/BorrowingIteratorProtocol+Filter.swift" + "Protocols/BorrowingIteratorProtocol+Map.swift" + "Protocols/BorrowingIteratorProtocol+MapError.swift" + "Protocols/BorrowingIteratorProtocol+Reduce.swift" + "Protocols/BorrowingIteratorProtocol+SpanwiseZip.swift" "Protocols/Iterable.swift" "Protocols/Iterable+Algorithms.swift" "Protocols/Iterable+Standard Conformances.swift" diff --git a/Sources/ContainersPreview/Protocols/IterableIteratorProtocol+Copy.swift b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+Copy.swift similarity index 98% rename from Sources/ContainersPreview/Protocols/IterableIteratorProtocol+Copy.swift rename to Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+Copy.swift index 73007d3a..9831a128 100644 --- a/Sources/ContainersPreview/Protocols/IterableIteratorProtocol+Copy.swift +++ b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+Copy.swift @@ -14,7 +14,7 @@ #if compiler(>=6.4) && UnstableContainersPreview @available(SwiftStdlib 5.0, *) -extension IterableIteratorProtocol_ +extension BorrowingIteratorProtocol_ where Self: ~Copyable & ~Escapable, Element_: Copyable diff --git a/Sources/ContainersPreview/Protocols/IterableIteratorProtocol+ElementsEqual.swift b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+ElementsEqual.swift similarity index 95% rename from Sources/ContainersPreview/Protocols/IterableIteratorProtocol+ElementsEqual.swift rename to Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+ElementsEqual.swift index 32d14064..b9786690 100644 --- a/Sources/ContainersPreview/Protocols/IterableIteratorProtocol+ElementsEqual.swift +++ b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+ElementsEqual.swift @@ -80,14 +80,14 @@ where } @available(SwiftStdlib 5.0, *) -extension IterableIteratorProtocol_ +extension BorrowingIteratorProtocol_ where Self: ~Copyable & ~Escapable, Element_: ~Copyable & Equatable { @inlinable package consuming func elementsEqual< - Other: IterableIteratorProtocol_ & ~Copyable & ~Escapable + Other: BorrowingIteratorProtocol_ & ~Copyable & ~Escapable >( _ other: consuming Other, ) throws(Failure_) -> Bool @@ -113,7 +113,7 @@ where @inlinable package consuming func _directElementsEqual< - Other: IterableIteratorProtocol_ & ~Copyable & ~Escapable + Other: BorrowingIteratorProtocol_ & ~Copyable & ~Escapable >( _ other: consuming Other, ) throws(Failure_) -> Bool @@ -174,14 +174,14 @@ where } @available(SwiftStdlib 5.0, *) -extension IterableIteratorProtocol_ +extension BorrowingIteratorProtocol_ where Self: ~Copyable & ~Escapable, Element_: ~Copyable { @inlinable package consuming func elementsEqual< - Other: IterableIteratorProtocol_ & ~Copyable & ~Escapable + Other: BorrowingIteratorProtocol_ & ~Copyable & ~Escapable >( _ other: consuming Other, by areEquivalent: (borrowing Element_, borrowing Other.Element_) throws(Failure_) -> Bool diff --git a/Sources/ContainersPreview/Protocols/IterableIteratorProtocol+Filter.swift b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+Filter.swift similarity index 92% rename from Sources/ContainersPreview/Protocols/IterableIteratorProtocol+Filter.swift rename to Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+Filter.swift index f42c869d..62ea6c1e 100644 --- a/Sources/ContainersPreview/Protocols/IterableIteratorProtocol+Filter.swift +++ b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+Filter.swift @@ -14,7 +14,7 @@ #if compiler(>=6.4) && UnstableContainersPreview @available(SwiftStdlib 5.0, *) -extension IterableIteratorProtocol_ +extension BorrowingIteratorProtocol_ where Self: ~Copyable & ~Escapable, Element_: ~Copyable @@ -30,7 +30,7 @@ where @available(SwiftStdlib 5.0, *) public struct BorrowingFilter< - Base: IterableIteratorProtocol_ & ~Copyable & ~Escapable + Base: BorrowingIteratorProtocol_ & ~Copyable & ~Escapable >: ~Copyable, ~Escapable where Base.Element_: ~Copyable { public typealias Element_ = Base.Element_ @@ -56,7 +56,7 @@ where Base.Element_: ~Copyable { // FIXME: Sendable @available(SwiftStdlib 5.0, *) -extension BorrowingFilter: IterableIteratorProtocol_ +extension BorrowingFilter: BorrowingIteratorProtocol_ where Base: ~Copyable & ~Escapable, Base.Element_: ~Copyable { @_lifetime(&self) public mutating func nextSpan_(maximumCount: Int) throws(Failure) -> Span { diff --git a/Sources/ContainersPreview/Protocols/IterableIteratorProtocol+Map.swift b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+Map.swift similarity index 97% rename from Sources/ContainersPreview/Protocols/IterableIteratorProtocol+Map.swift rename to Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+Map.swift index 07d7acd1..9192d9c0 100644 --- a/Sources/ContainersPreview/Protocols/IterableIteratorProtocol+Map.swift +++ b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+Map.swift @@ -14,7 +14,7 @@ #if compiler(>=6.4) && UnstableContainersPreview @available(SwiftStdlib 5.0, *) -extension IterableIteratorProtocol_ +extension BorrowingIteratorProtocol_ where Self: ~Copyable & ~Escapable, Element_: ~Copyable @@ -52,7 +52,7 @@ where @available(SwiftStdlib 5.0, *) public struct BorrowingMapProducer< - Base: IterableIteratorProtocol_ & ~Copyable & ~Escapable, + Base: BorrowingIteratorProtocol_ & ~Copyable & ~Escapable, Element: ~Copyable, >: ~Copyable, ~Escapable { @_alwaysEmitIntoClient diff --git a/Sources/ContainersPreview/Protocols/IterableIteratorProtocol+MapError.swift b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+MapError.swift similarity index 93% rename from Sources/ContainersPreview/Protocols/IterableIteratorProtocol+MapError.swift rename to Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+MapError.swift index 14d8ed99..87f358e3 100644 --- a/Sources/ContainersPreview/Protocols/IterableIteratorProtocol+MapError.swift +++ b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+MapError.swift @@ -14,7 +14,7 @@ #if compiler(>=6.4) && UnstableContainersPreview @available(SwiftStdlib 5.0, *) -extension IterableIteratorProtocol_ +extension BorrowingIteratorProtocol_ where Self: ~Copyable & ~Escapable, Element_: ~Copyable @@ -41,7 +41,7 @@ where @frozen public struct ErrorMappedIterator< - Base: IterableIteratorProtocol_ & ~Copyable & ~Escapable, + Base: BorrowingIteratorProtocol_ & ~Copyable & ~Escapable, Failure: Error >: ~Copyable, ~Escapable where Base.Element_: ~Copyable { @@ -62,7 +62,7 @@ where Base.Element_: ~Copyable { } } -extension ErrorMappedIterator: IterableIteratorProtocol_ +extension ErrorMappedIterator: BorrowingIteratorProtocol_ where Base: ~Copyable & ~Escapable, Base.Element_: ~Copyable diff --git a/Sources/ContainersPreview/Protocols/IterableIteratorProtocol+Reduce.swift b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+Reduce.swift similarity index 97% rename from Sources/ContainersPreview/Protocols/IterableIteratorProtocol+Reduce.swift rename to Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+Reduce.swift index c6526bb8..6f766bb2 100644 --- a/Sources/ContainersPreview/Protocols/IterableIteratorProtocol+Reduce.swift +++ b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+Reduce.swift @@ -14,7 +14,7 @@ #if compiler(>=6.4) && UnstableContainersPreview @available(SwiftStdlib 5.0, *) -extension IterableIteratorProtocol_ +extension BorrowingIteratorProtocol_ where Self: ~Copyable & ~Escapable, Element_: ~Copyable diff --git a/Sources/ContainersPreview/Protocols/IterableIteratorProtocol+SpanwiseZip.swift b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+SpanwiseZip.swift similarity index 96% rename from Sources/ContainersPreview/Protocols/IterableIteratorProtocol+SpanwiseZip.swift rename to Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+SpanwiseZip.swift index f84d3ffd..60dcaf3a 100644 --- a/Sources/ContainersPreview/Protocols/IterableIteratorProtocol+SpanwiseZip.swift +++ b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+SpanwiseZip.swift @@ -18,14 +18,14 @@ import InternalCollectionsUtilities #if compiler(>=6.4) && UnstableContainersPreview @available(SwiftStdlib 5.0, *) -extension IterableIteratorProtocol_ +extension BorrowingIteratorProtocol_ where Self: ~Copyable & ~Escapable, Element_: ~Copyable { @inlinable internal consuming func _spanwiseZip< - Other: IterableIteratorProtocol_ & ~Copyable & ~Escapable, + Other: BorrowingIteratorProtocol_ & ~Copyable & ~Escapable, State: ~Copyable >( state: inout State, diff --git a/Sources/ContainersPreview/Protocols/IterableIteratorProtocol.swift b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol.swift similarity index 95% rename from Sources/ContainersPreview/Protocols/IterableIteratorProtocol.swift rename to Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol.swift index 3cd13d16..b26aa039 100644 --- a/Sources/ContainersPreview/Protocols/IterableIteratorProtocol.swift +++ b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol.swift @@ -18,7 +18,7 @@ import InternalCollectionsUtilities #endif @available(SwiftStdlib 5.0, *) -public protocol IterableIteratorProtocol_: ~Copyable, ~Escapable { +public protocol BorrowingIteratorProtocol_: ~Copyable, ~Escapable { associatedtype Element_: ~Copyable associatedtype Failure_: Error = Never @@ -86,7 +86,7 @@ public protocol IterableIteratorProtocol_: ~Copyable, ~Escap } @available(SwiftStdlib 5.0, *) -extension IterableIteratorProtocol_ +extension BorrowingIteratorProtocol_ where Self: ~Copyable & ~Escapable, Element_: ~Copyable { @_lifetime(&self) @_lifetime(self: copy self) @@ -97,7 +97,7 @@ where Self: ~Copyable & ~Escapable, Element_: ~Copyable { } @available(SwiftStdlib 5.0, *) -extension IterableIteratorProtocol_ +extension BorrowingIteratorProtocol_ where Self: ~Copyable & ~Escapable, Element_: ~Copyable { @_lifetime(self: copy self) @inlinable @@ -113,7 +113,7 @@ where Self: ~Copyable & ~Escapable, Element_: ~Copyable { } @available(SwiftStdlib 5.0, *) -extension IterableIteratorProtocol_ where Self: ~Copyable & ~Escapable { +extension BorrowingIteratorProtocol_ where Self: ~Copyable & ~Escapable { #if false // FIXME: This doesn't work, but it should? @_lifetime(&self) @_lifetime(self: copy self) @@ -126,7 +126,7 @@ extension IterableIteratorProtocol_ where Self: ~Copyable & ~Escapable { } @available(SwiftStdlib 5.0, *) -extension IterableIteratorProtocol_ +extension BorrowingIteratorProtocol_ where Self: ~Copyable & ~Escapable, Element_: Copyable { @_lifetime(self: copy self) diff --git a/Sources/ContainersPreview/Protocols/Container/Container+Filter.swift b/Sources/ContainersPreview/Protocols/Container/Container+Filter.swift index 3fbe82f5..47107f6d 100644 --- a/Sources/ContainersPreview/Protocols/Container/Container+Filter.swift +++ b/Sources/ContainersPreview/Protocols/Container/Container+Filter.swift @@ -88,7 +88,7 @@ where Base.Element: ~Copyable // FIXME: Sendable @available(SwiftStdlib 6.4, *) -extension ContainerFilter: IterableIteratorProtocol_ where Element: ~Copyable { +extension ContainerFilter: BorrowingIteratorProtocol_ where Element: ~Copyable { public typealias Element_ = Base.Element @_lifetime(&self) // FIXME: This should be `@_lifetime(copy self)` diff --git a/Sources/ContainersPreview/Protocols/Container/ContainerIterator.swift b/Sources/ContainersPreview/Protocols/Container/ContainerIterator.swift index 6028bc7a..80483914 100644 --- a/Sources/ContainersPreview/Protocols/Container/ContainerIterator.swift +++ b/Sources/ContainersPreview/Protocols/Container/ContainerIterator.swift @@ -50,7 +50,7 @@ where Base.Element: ~Copyable } @available(SwiftStdlib 6.4, *) -extension ContainerIterator: IterableIteratorProtocol_ +extension ContainerIterator: BorrowingIteratorProtocol_ where Base: ~Copyable /*FIXME: & ~Escapable*/, Base.Element: ~Copyable diff --git a/Sources/ContainersPreview/Protocols/Iterable+Standard Conformances.swift b/Sources/ContainersPreview/Protocols/Iterable+Standard Conformances.swift index d835a892..95b3544e 100644 --- a/Sources/ContainersPreview/Protocols/Iterable+Standard Conformances.swift +++ b/Sources/ContainersPreview/Protocols/Iterable+Standard Conformances.swift @@ -113,7 +113,7 @@ where Bound: Strideable, Bound.Stride: SignedInteger public typealias Element = Bound @frozen - public struct IterableIterator_: IterableIteratorProtocol_, ~Copyable { + public struct IterableIterator_: BorrowingIteratorProtocol_, ~Copyable { @usableFromInline internal var _current: InlineArray<1, Bound> @@ -169,7 +169,7 @@ where Bound: Strideable, Bound.Stride: SignedInteger public typealias Element = Bound @frozen - public struct IterableIterator_: IterableIteratorProtocol_, ~Copyable { + public struct IterableIterator_: BorrowingIteratorProtocol_, ~Copyable { @usableFromInline internal var _current: InlineArray<1, Bound> diff --git a/Sources/ContainersPreview/Protocols/Iterable.swift b/Sources/ContainersPreview/Protocols/Iterable.swift index 359239fd..36e3db27 100644 --- a/Sources/ContainersPreview/Protocols/Iterable.swift +++ b/Sources/ContainersPreview/Protocols/Iterable.swift @@ -18,7 +18,7 @@ public protocol Iterable_: ~Copyable, ~Escapable { associatedtype Element_: ~Copyable associatedtype Failure_: Error = Never - associatedtype IterableIterator_: IterableIteratorProtocol_ & ~Copyable & ~Escapable + associatedtype IterableIterator_: BorrowingIteratorProtocol_ & ~Copyable & ~Escapable var underestimatedCount_: Int { get } diff --git a/Sources/ContainersPreview/Types/SpanIterator.swift b/Sources/ContainersPreview/Types/SpanIterator.swift index 0eb1867e..a5513c27 100644 --- a/Sources/ContainersPreview/Types/SpanIterator.swift +++ b/Sources/ContainersPreview/Types/SpanIterator.swift @@ -16,7 +16,7 @@ /// A borrowing iterator that provides access to the elements of a single /// span through a `BorrowingIteratorProtocol` interface. @available(SwiftStdlib 5.0, *) -public struct SpanIterator: IterableIteratorProtocol_, ~Copyable, ~Escapable +public struct SpanIterator: BorrowingIteratorProtocol_, ~Copyable, ~Escapable where Element_: ~Copyable { @usableFromInline diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift index e11cfa0c..3084493b 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift @@ -23,7 +23,7 @@ import ContainersPreview extension RigidDeque where Element: ~Copyable { #if compiler(>=6.4) && UnstableContainersPreview @frozen - public struct BorrowingIterator: ~Escapable, IterableIteratorProtocol_ { + public struct BorrowingIterator: ~Escapable, BorrowingIteratorProtocol_ { public typealias Element_ = Element @usableFromInline diff --git a/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift b/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift index 74211c6c..9591b8a0 100644 --- a/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift +++ b/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift @@ -76,7 +76,7 @@ package struct _StaccatoParameters { } @available(SwiftStdlib 5.0, *) -public struct _StaccatoBorrowingIterator: IterableIteratorProtocol_, ~Escapable { +public struct _StaccatoBorrowingIterator: BorrowingIteratorProtocol_, ~Escapable { public typealias Element_ = Element internal let _contents: Span diff --git a/Xcode/Collections.xcodeproj/project.pbxproj b/Xcode/Collections.xcodeproj/project.pbxproj index f0ee3b97..89720ff8 100644 --- a/Xcode/Collections.xcodeproj/project.pbxproj +++ b/Xcode/Collections.xcodeproj/project.pbxproj @@ -204,19 +204,19 @@ 7DAD89B72E8B09EC00DD5786 /* UnsafeRawBufferPointer+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DAD89AF2E8B09EC00DD5786 /* UnsafeRawBufferPointer+Extras.swift */; }; 7DB257A12F58B1AA007B539F /* RigidDictionary+Debugging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DB257A02F58B1A3007B539F /* RigidDictionary+Debugging.swift */; }; 7DB257A32F58B1D3007B539F /* UniqueDictionary+Debugging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DB257A22F58B1CC007B539F /* UniqueDictionary+Debugging.swift */; }; - 7DC037B72FE3492D00CF0CB8 /* IterableIteratorProtocol+Copy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037B12FE3492D00CF0CB8 /* IterableIteratorProtocol+Copy.swift */; }; + 7DC037B72FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Copy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037B12FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Copy.swift */; }; 7DC037B82FE3492D00CF0CB8 /* Iterable+Utilities.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037AF2FE3492D00CF0CB8 /* Iterable+Utilities.swift */; }; 7DC037B92FE3492D00CF0CB8 /* Iterable+Standard Conformances.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037AE2FE3492D00CF0CB8 /* Iterable+Standard Conformances.swift */; }; - 7DC037BA2FE3492D00CF0CB8 /* IterableIteratorProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037B02FE3492D00CF0CB8 /* IterableIteratorProtocol.swift */; }; + 7DC037BA2FE3492D00CF0CB8 /* BorrowingIteratorProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037B02FE3492D00CF0CB8 /* BorrowingIteratorProtocol.swift */; }; 7DC037BB2FE3492D00CF0CB8 /* Iterable+Algorithms.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037AD2FE3492D00CF0CB8 /* Iterable+Algorithms.swift */; }; - 7DC037BC2FE3492D00CF0CB8 /* IterableIteratorProtocol+Filter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037B32FE3492D00CF0CB8 /* IterableIteratorProtocol+Filter.swift */; }; + 7DC037BC2FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Filter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037B32FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Filter.swift */; }; 7DC037BD2FE3492D00CF0CB8 /* Iterable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037AC2FE3492D00CF0CB8 /* Iterable.swift */; }; - 7DC037BE2FE3492D00CF0CB8 /* IterableIteratorProtocol+ElementsEqual.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037B22FE3492D00CF0CB8 /* IterableIteratorProtocol+ElementsEqual.swift */; }; - 7DC037BF2FE3492D00CF0CB8 /* IterableIteratorProtocol+Reduce.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037B52FE3492D00CF0CB8 /* IterableIteratorProtocol+Reduce.swift */; }; - 7DC037C02FE3492D00CF0CB8 /* IterableIteratorProtocol+SpanwiseZip.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037B62FE3492D00CF0CB8 /* IterableIteratorProtocol+SpanwiseZip.swift */; }; - 7DC037C12FE3492D00CF0CB8 /* IterableIteratorProtocol+Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037B42FE3492D00CF0CB8 /* IterableIteratorProtocol+Map.swift */; }; + 7DC037BE2FE3492D00CF0CB8 /* BorrowingIteratorProtocol+ElementsEqual.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037B22FE3492D00CF0CB8 /* BorrowingIteratorProtocol+ElementsEqual.swift */; }; + 7DC037BF2FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Reduce.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037B52FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Reduce.swift */; }; + 7DC037C02FE3492D00CF0CB8 /* BorrowingIteratorProtocol+SpanwiseZip.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037B62FE3492D00CF0CB8 /* BorrowingIteratorProtocol+SpanwiseZip.swift */; }; + 7DC037C12FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037B42FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Map.swift */; }; 7DC037C32FE34B2800CF0CB8 /* Heap+Testing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037C22FE34B2800CF0CB8 /* Heap+Testing.swift */; }; - 7DC037C52FE3717A00CF0CB8 /* IterableIteratorProtocol+MapError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037C42FE3717200CF0CB8 /* IterableIteratorProtocol+MapError.swift */; }; + 7DC037C52FE3717A00CF0CB8 /* BorrowingIteratorProtocol+MapError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037C42FE3717200CF0CB8 /* BorrowingIteratorProtocol+MapError.swift */; }; 7DC037C92FE3792300CF0CB8 /* MutableRef.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037C82FE3792300CF0CB8 /* MutableRef.swift */; }; 7DC85F8D2F3FDC91004A4E3D /* String+Padding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC85F8C2F3FDC82004A4E3D /* String+Padding.swift */; }; 7DC85F8F2F43D065004A4E3D /* RigidDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC85F8E2F43D05F004A4E3D /* RigidDictionaryTests.swift */; }; @@ -832,15 +832,15 @@ 7DC037AD2FE3492D00CF0CB8 /* Iterable+Algorithms.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Iterable+Algorithms.swift"; sourceTree = ""; }; 7DC037AE2FE3492D00CF0CB8 /* Iterable+Standard Conformances.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Iterable+Standard Conformances.swift"; sourceTree = ""; }; 7DC037AF2FE3492D00CF0CB8 /* Iterable+Utilities.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Iterable+Utilities.swift"; sourceTree = ""; }; - 7DC037B02FE3492D00CF0CB8 /* IterableIteratorProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IterableIteratorProtocol.swift; sourceTree = ""; }; - 7DC037B12FE3492D00CF0CB8 /* IterableIteratorProtocol+Copy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "IterableIteratorProtocol+Copy.swift"; sourceTree = ""; }; - 7DC037B22FE3492D00CF0CB8 /* IterableIteratorProtocol+ElementsEqual.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "IterableIteratorProtocol+ElementsEqual.swift"; sourceTree = ""; }; - 7DC037B32FE3492D00CF0CB8 /* IterableIteratorProtocol+Filter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "IterableIteratorProtocol+Filter.swift"; sourceTree = ""; }; - 7DC037B42FE3492D00CF0CB8 /* IterableIteratorProtocol+Map.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "IterableIteratorProtocol+Map.swift"; sourceTree = ""; }; - 7DC037B52FE3492D00CF0CB8 /* IterableIteratorProtocol+Reduce.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "IterableIteratorProtocol+Reduce.swift"; sourceTree = ""; }; - 7DC037B62FE3492D00CF0CB8 /* IterableIteratorProtocol+SpanwiseZip.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "IterableIteratorProtocol+SpanwiseZip.swift"; sourceTree = ""; }; + 7DC037B02FE3492D00CF0CB8 /* BorrowingIteratorProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BorrowingIteratorProtocol.swift; sourceTree = ""; }; + 7DC037B12FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Copy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BorrowingIteratorProtocol+Copy.swift"; sourceTree = ""; }; + 7DC037B22FE3492D00CF0CB8 /* BorrowingIteratorProtocol+ElementsEqual.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BorrowingIteratorProtocol+ElementsEqual.swift"; sourceTree = ""; }; + 7DC037B32FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Filter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BorrowingIteratorProtocol+Filter.swift"; sourceTree = ""; }; + 7DC037B42FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Map.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BorrowingIteratorProtocol+Map.swift"; sourceTree = ""; }; + 7DC037B52FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Reduce.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BorrowingIteratorProtocol+Reduce.swift"; sourceTree = ""; }; + 7DC037B62FE3492D00CF0CB8 /* BorrowingIteratorProtocol+SpanwiseZip.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BorrowingIteratorProtocol+SpanwiseZip.swift"; sourceTree = ""; }; 7DC037C22FE34B2800CF0CB8 /* Heap+Testing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Heap+Testing.swift"; sourceTree = ""; }; - 7DC037C42FE3717200CF0CB8 /* IterableIteratorProtocol+MapError.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "IterableIteratorProtocol+MapError.swift"; sourceTree = ""; }; + 7DC037C42FE3717200CF0CB8 /* BorrowingIteratorProtocol+MapError.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BorrowingIteratorProtocol+MapError.swift"; sourceTree = ""; }; 7DC037C82FE3792300CF0CB8 /* MutableRef.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MutableRef.swift; sourceTree = ""; }; 7DC85F8C2F3FDC82004A4E3D /* String+Padding.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "String+Padding.swift"; sourceTree = ""; }; 7DC85F8E2F43D05F004A4E3D /* RigidDictionaryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RigidDictionaryTests.swift; sourceTree = ""; }; @@ -1327,14 +1327,14 @@ 7DC037AD2FE3492D00CF0CB8 /* Iterable+Algorithms.swift */, 7DC037AE2FE3492D00CF0CB8 /* Iterable+Standard Conformances.swift */, 7DC037AF2FE3492D00CF0CB8 /* Iterable+Utilities.swift */, - 7DC037B02FE3492D00CF0CB8 /* IterableIteratorProtocol.swift */, - 7DC037B12FE3492D00CF0CB8 /* IterableIteratorProtocol+Copy.swift */, - 7DC037B22FE3492D00CF0CB8 /* IterableIteratorProtocol+ElementsEqual.swift */, - 7DC037B32FE3492D00CF0CB8 /* IterableIteratorProtocol+Filter.swift */, - 7DC037B42FE3492D00CF0CB8 /* IterableIteratorProtocol+Map.swift */, - 7DC037C42FE3717200CF0CB8 /* IterableIteratorProtocol+MapError.swift */, - 7DC037B52FE3492D00CF0CB8 /* IterableIteratorProtocol+Reduce.swift */, - 7DC037B62FE3492D00CF0CB8 /* IterableIteratorProtocol+SpanwiseZip.swift */, + 7DC037B02FE3492D00CF0CB8 /* BorrowingIteratorProtocol.swift */, + 7DC037B12FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Copy.swift */, + 7DC037B22FE3492D00CF0CB8 /* BorrowingIteratorProtocol+ElementsEqual.swift */, + 7DC037B32FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Filter.swift */, + 7DC037B42FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Map.swift */, + 7DC037C42FE3717200CF0CB8 /* BorrowingIteratorProtocol+MapError.swift */, + 7DC037B52FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Reduce.swift */, + 7DC037B62FE3492D00CF0CB8 /* BorrowingIteratorProtocol+SpanwiseZip.swift */, 7D57EDCE2F647DB10029D5E3 /* Container */, 7D77E6112FCF810E003FA63B /* CountedProducer.swift */, 7D2A772F2F27F1E4005780C7 /* Drain.swift */, @@ -2661,22 +2661,22 @@ 7D479CB02F450E4600A8CB59 /* RigidSet+BorrowingSequence.swift in Sources */, 7DE9216629CA70F4004483EB /* _HashNode+Storage.swift in Sources */, 7DE920CE29CA70F4004483EB /* BitSet+CustomReflectable.swift in Sources */, - 7DC037C52FE3717A00CF0CB8 /* IterableIteratorProtocol+MapError.swift in Sources */, + 7DC037C52FE3717A00CF0CB8 /* BorrowingIteratorProtocol+MapError.swift in Sources */, 7DE9215029CA70F4004483EB /* _UnmanagedHashNode.swift in Sources */, 7DE920EF29CA70F4004483EB /* BitArray+Codable.swift in Sources */, 7DE920C029CA70F4004483EB /* BitSet+SetAlgebra conformance.swift in Sources */, 7DE9203C29CA70F3004483EB /* OrderedSet+Partial SetAlgebra formSymmetricDifference.swift in Sources */, - 7DC037B72FE3492D00CF0CB8 /* IterableIteratorProtocol+Copy.swift in Sources */, + 7DC037B72FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Copy.swift in Sources */, 7DC037B82FE3492D00CF0CB8 /* Iterable+Utilities.swift in Sources */, 7DC037B92FE3492D00CF0CB8 /* Iterable+Standard Conformances.swift in Sources */, - 7DC037BA2FE3492D00CF0CB8 /* IterableIteratorProtocol.swift in Sources */, + 7DC037BA2FE3492D00CF0CB8 /* BorrowingIteratorProtocol.swift in Sources */, 7DC037BB2FE3492D00CF0CB8 /* Iterable+Algorithms.swift in Sources */, - 7DC037BC2FE3492D00CF0CB8 /* IterableIteratorProtocol+Filter.swift in Sources */, + 7DC037BC2FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Filter.swift in Sources */, 7DC037BD2FE3492D00CF0CB8 /* Iterable.swift in Sources */, - 7DC037BE2FE3492D00CF0CB8 /* IterableIteratorProtocol+ElementsEqual.swift in Sources */, - 7DC037BF2FE3492D00CF0CB8 /* IterableIteratorProtocol+Reduce.swift in Sources */, - 7DC037C02FE3492D00CF0CB8 /* IterableIteratorProtocol+SpanwiseZip.swift in Sources */, - 7DC037C12FE3492D00CF0CB8 /* IterableIteratorProtocol+Map.swift in Sources */, + 7DC037BE2FE3492D00CF0CB8 /* BorrowingIteratorProtocol+ElementsEqual.swift in Sources */, + 7DC037BF2FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Reduce.swift in Sources */, + 7DC037C02FE3492D00CF0CB8 /* BorrowingIteratorProtocol+SpanwiseZip.swift in Sources */, + 7DC037C12FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Map.swift in Sources */, 7DE9209029CA70F4004483EB /* Rope.swift in Sources */, 7D2A77782F27F2BF005780C7 /* Deque._Storage.swift in Sources */, 7D2A77792F27F2BF005780C7 /* RigidDeque+Prepend.swift in Sources */, From bb0dc189efd298e115c4555a6dce0821541a6e31 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 1 Jul 2026 17:39:08 -0700 Subject: [PATCH 20/50] =?UTF-8?q?maximumCount=20=E2=86=92=20maxCount?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit While we’re here, adjust `RigidSet.insert(maximumCount:initializingWith:)` and similar APIs to be consistent with RangeReplaceableContainer’s methods. --- Sources/BasicContainers/CMakeLists.txt | 1 + .../HashTable/_HTable+Deprecated.swift | 63 +++++++++++++++++++ .../HashTable/_HTable+Iteration.swift | 22 +++---- .../RigidArray/RigidArray+Consumption.swift | 4 +- .../RigidArray/RigidArray+Container.swift | 38 +++++------ .../RigidArray/RigidArray+Deprecated.swift | 27 ++++++++ .../RigidArray/RigidArray+Replacements.swift | 4 +- .../RigidDictionary+Indices.swift | 4 +- .../RigidSet/RigidSet+BorrowingSequence.swift | 8 +-- .../RigidSet/RigidSet+Deprecated.swift | 63 +++++++++++++++++++ .../RigidSet/RigidSet+Initializers.swift | 6 +- .../RigidSet/RigidSet+Insertions.swift | 40 ++++++++---- .../UniqueArray/UniqueArray+Container.swift | 30 ++++----- .../UniqueArray/UniqueArray+Deprecated.swift | 27 ++++++++ .../UniqueArray+Replacements.swift | 6 +- .../UniqueSet/UniqueSet+Deprecations.swift | 30 +++++++++ .../UniqueSet/UniqueSet+Initializers.swift | 2 +- .../UniqueSet/UniqueSet+Insertions.swift | 11 ++-- .../BitArray+ChunkedBitsIterators.swift | 6 +- .../BitArray/BitArray+Copy.swift | 2 +- .../BitArray+RangeReplaceableCollection.swift | 2 +- Sources/ContainersPreview/CMakeLists.txt | 2 +- .../Conformances/InputSpan+Container.swift | 18 +++--- .../Conformances/MutableSpan+Container.swift | 18 +++--- .../Conformances/OutputSpan+Container.swift | 18 +++--- .../Conformances/Span+Container.swift | 12 ++-- ...rowingIteratorProtocol+ElementsEqual.swift | 4 +- .../BorrowingIteratorProtocol+Filter.swift | 4 +- .../BorrowingIteratorProtocol+Map.swift | 4 +- .../BorrowingIteratorProtocol+MapError.swift | 4 +- ...orrowingIteratorProtocol+SpanwiseZip.swift | 4 +- .../Protocols/BorrowingIteratorProtocol.swift | 14 ++--- .../Container/BidirectionalContainer.swift | 12 ++-- .../Container/Container+Filter.swift | 6 +- .../Protocols/Container/Container.swift | 28 ++++----- .../Container/ContainerIterator.swift | 4 +- .../Container/MutableContainer.swift | 22 +++---- .../Container/RangeReplaceableContainer.swift | 28 +++------ .../Protocols/Drain+Map.swift | 2 +- .../ContainersPreview/Protocols/Drain.swift | 18 +++--- .../Protocols/Iterable+Algorithms.swift | 4 +- .../Iterable+Standard Conformances.swift | 4 +- .../Protocols/Iterable+Utilities.swift | 2 +- .../Protocols/Producer.swift | 12 ++-- ...+Extras.swift => OutputSpan+Helpers.swift} | 0 .../Types/SpanIterator.swift | 4 +- .../Deque/Deque._UnsafeHandle.swift | 4 +- .../RigidDeque/RigidDeque+Consumption.swift | 4 +- .../RigidDeque/RigidDeque+Container.swift | 22 +++---- .../RigidDeque/RigidDeque+Prepend.swift | 4 +- .../RigidDeque/RigidDeque+Replacements.swift | 2 +- .../UniqueDeque/UniqueDeque+Container.swift | 12 ++-- .../UniqueDeque/UniqueDeque+Prepend.swift | 2 +- .../BigString/Views/BigString+UTF8View.swift | 2 +- .../RigidArrayTests.swift | 2 +- .../BasicContainersTests/RigidSetTests.swift | 18 +++--- .../BorrowingSequenceTests.swift | 2 +- Tests/DequeTests/RigidDequeCrashTests.swift | 10 +-- Tests/DequeTests/RigidDequeTests.swift | 6 +- .../Assertions+Containers.swift | 4 +- .../ConformanceCheckers/CheckContainer.swift | 4 +- .../MinimalTypes/CustomDrain.swift | 4 +- .../MinimalTypes/StaccatoContainer.swift | 14 ++--- Xcode/Collections.xcodeproj/project.pbxproj | 20 ++++-- 64 files changed, 505 insertions(+), 275 deletions(-) create mode 100644 Sources/BasicContainers/HashTable/_HTable+Deprecated.swift create mode 100644 Sources/BasicContainers/RigidSet/RigidSet+Deprecated.swift create mode 100644 Sources/BasicContainers/UniqueSet/UniqueSet+Deprecations.swift rename Sources/ContainersPreview/Types/{OutputSpan+Extras.swift => OutputSpan+Helpers.swift} (100%) diff --git a/Sources/BasicContainers/CMakeLists.txt b/Sources/BasicContainers/CMakeLists.txt index 29bc573c..ceeb6e37 100644 --- a/Sources/BasicContainers/CMakeLists.txt +++ b/Sources/BasicContainers/CMakeLists.txt @@ -57,6 +57,7 @@ target_sources(${module_name} PRIVATE "HashTable/_HTable+Bucket.swift" "HashTable/_HTable+Consumption.swift" "HashTable/_HTable+Debug.swift" + "HashTable/_HTable+Deprecated.swift" "HashTable/_HTable+Find.swift" "HashTable/_HTable+Insert.swift" "HashTable/_HTable+Iteration.swift" diff --git a/Sources/BasicContainers/HashTable/_HTable+Deprecated.swift b/Sources/BasicContainers/HashTable/_HTable+Deprecated.swift new file mode 100644 index 00000000..449d93db --- /dev/null +++ b/Sources/BasicContainers/HashTable/_HTable+Deprecated.swift @@ -0,0 +1,63 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception +// +//===----------------------------------------------------------------------===// + +#if COLLECTIONS_SINGLE_MODULE + +#if compiler(>=6.2) +extension _HTable.BucketIterator { + // FIXME: Remove after 27.0 releases + @available(*, deprecated, renamed: "advanceToOccupied(maxCount:)") + @usableFromInline + @discardableResult + @_lifetime(self: copy self) + internal mutating func advanceToOccupied( + maximumCount: Int + ) -> Bool { + self.advanceToOccupied(maxCount: maximumCount) + } + + // FIXME: Remove after 27.0 releases + @available(*, deprecated, renamed: "advanceToUnoccupied(maxCount:)") + @usableFromInline + @discardableResult + @_lifetime(self: copy self) + internal mutating func advanceToUnoccupied( + maximumCount: Int + ) -> Bool { + self.advanceToUnoccupied(maxCount: maximumCount) + } + + // FIXME: Remove after 27.0 releases + @available(*, deprecated, renamed: "nextOccupiedRegion(maxCount:)") + @usableFromInline + @_lifetime(self: copy self) + internal mutating func nextOccupiedRegion( + maximumCount: Int + ) -> Range? { + self.nextOccupiedRegion(maxCount: maximumCount) + } + + // FIXME: Remove after 27.0 releases + @available(*, deprecated, renamed: "nextUnoccupiedRegion(maxCount:)") + @usableFromInline + @_lifetime(self: copy self) + internal mutating func nextUnoccupiedRegion( + maximumCount: Int + ) -> Range? { + self.nextUnoccupiedRegion(maxCount: maximumCount) + } +} +#endif + +#endif + diff --git a/Sources/BasicContainers/HashTable/_HTable+Iteration.swift b/Sources/BasicContainers/HashTable/_HTable+Iteration.swift index 2905a889..728ee918 100644 --- a/Sources/BasicContainers/HashTable/_HTable+Iteration.swift +++ b/Sources/BasicContainers/HashTable/_HTable+Iteration.swift @@ -232,9 +232,9 @@ extension _HTable.BucketIterator { @discardableResult @_lifetime(self: copy self) package mutating func advanceToOccupied( - maximumCount: Int + maxCount: Int ) -> Bool { - var remainder = UInt(bitPattern: maximumCount) + var remainder = UInt(bitPattern: maxCount) if isAtEnd { return false } if _words == nil { let delta = Swift.min(_endBucket._offset &- _bucket._offset, remainder) @@ -309,11 +309,11 @@ extension _HTable.BucketIterator { @discardableResult @_lifetime(self: copy self) package mutating func advanceToUnoccupied( - maximumCount: Int + maxCount: Int ) -> Bool { - assert(maximumCount > 0) + assert(maxCount > 0) assert(!isAtEnd) - var remainder = UInt(bitPattern: maximumCount) + var remainder = UInt(bitPattern: maxCount) if _words == nil { let delta = Swift.min(_endBucket._offset &- _bucket._offset, remainder) _bucket._offset &+= delta @@ -363,13 +363,13 @@ extension _HTable.BucketIterator { @usableFromInline @_lifetime(self: copy self) package mutating func nextOccupiedRegion( - maximumCount: Int = .max + maxCount: Int = .max ) -> Range? { - assert(maximumCount > 0) + assert(maxCount > 0) guard self.advanceToOccupied() else { return nil } assert(self.isOccupied) let start = self.currentBucket - self.advanceToUnoccupied(maximumCount: maximumCount) + self.advanceToUnoccupied(maxCount: maxCount) let end = self.currentBucket return Range(uncheckedBounds: (start, end)) } @@ -377,13 +377,13 @@ extension _HTable.BucketIterator { @usableFromInline @_lifetime(self: copy self) package mutating func nextUnoccupiedRegion( - maximumCount: Int = .max + maxCount: Int = .max ) -> Range? { - assert(maximumCount > 0) + assert(maxCount > 0) guard self.advanceToUnoccupied() else { return nil } assert(!self.isOccupied) let start = self.currentBucket - self.advanceToOccupied(maximumCount: maximumCount) + self.advanceToOccupied(maxCount: maxCount) let end = self.currentBucket return Range(uncheckedBounds: (start, end)) } diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Consumption.swift b/Sources/BasicContainers/RigidArray/RigidArray+Consumption.swift index 096569e0..2447d23f 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Consumption.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Consumption.swift @@ -205,11 +205,11 @@ extension RigidArray.SubrangeConsumer where Element: ~Copyable { @inlinable @_lifetime(&self) @_lifetime(self: copy self) - public mutating func drainNext(maximumCount: Int) -> InputSpan { + public mutating func drainNext(maxCount: Int) -> InputSpan { if _remainder.isEmpty { return .init() } - let buffer = _remainder._trim(first: maximumCount) + let buffer = _remainder._trim(first: maxCount) return _overrideLifetime( InputSpan(buffer: buffer, initializedCount: buffer.count), mutating: &self) diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Container.swift b/Sources/BasicContainers/RigidArray/RigidArray+Container.swift index d2aa4ae1..8b825fe2 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Container.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Container.swift @@ -324,7 +324,7 @@ extension RigidArray where Element: ~Copyable { /// Return a span over the array's storage that begins with the element at /// the given index, and extends to the end of the contiguous storage chunk - /// that contains it, but no more than `maximumCount` items. + /// that contains it, but no more than `maxCount` items. /// /// On return, the index is updated to address the next item following the /// end of the returned span. @@ -335,30 +335,30 @@ extension RigidArray where Element: ~Copyable { /// /// var index = items.startIndex /// while true { - /// let span = items.nextSpan(after: &index, maximumCount: 4) + /// let span = items.nextSpan(after: &index, maxCount: 4) /// if span.isEmpty { break } /// // Process items in `span` /// } /// - /// The `maximumCount` argument gives the caller control over the number of + /// The `maxCount` argument gives the caller control over the number of /// items it receives from the iterator. This lets the caller avoid getting /// more elements than it would be able to immediately process, which would /// significantly complicate container use. /// /// If the caller is able to process any number available items, it can signal - /// that by passing `Int.max` as the `maximumCount`, or simply by calling the + /// that by passing `Int.max` as the `maxCount`, or simply by calling the /// `nexSpan(after:)` method, which does precisely that. This is frequently /// the case when the caller simply wants to iterate over the entire /// container in a single loop. /// - /// `maximumCount` sets an upper bound. To read a specific number of items, + /// `maxCount` sets an upper bound. To read a specific number of items, /// the caller usually needs to invoke `nextSpan` in a loop: /// /// var items: some Container /// var index = items.startIndex /// var remainder = numberOfItemsToRead /// while remainder > 0 { - /// let next = items.nextSpan(after: &index, maximumCount: remainder) + /// let next = items.nextSpan(after: &index, maxCount: remainder) /// guard !next.isEmpty else { /// // Container does not have enough items /// break @@ -381,10 +381,10 @@ extension RigidArray where Element: ~Copyable { /// - Parameter index: A valid index in the container, including the end /// index. On return, this index is advanced by the count of the resulting /// span, to simplify iteration. - /// - Parameter maximumCount: The maximum number of items the caller is able - /// to process immediately. `maximumCount` must be greater than zero. + /// - Parameter maxCount: The maximum number of items the caller is able + /// to process immediately. `maxCount` must be greater than zero. /// If you are able to process an arbitrary number of items, set - /// `maximumCount` to `Int.max`, or call the `nextSpan(after:)` method. + /// `maxCount` to `Int.max`, or call the `nextSpan(after:)` method. /// - Returns: A span over contiguous storage that starts at the given index. /// If the input index is the end index, then this returns an empty span. /// Otherwise the result is non-empty, with its first element matching the @@ -393,34 +393,36 @@ extension RigidArray where Element: ~Copyable { @inlinable @_lifetime(borrow self) public func nextSpan( - after index: inout Int, maximumCount: Int + after index: inout Int, maxCount: Int ) -> Span { _checkValidIndex(index) - precondition(maximumCount > 0, "maximumCount must be positive") + precondition(maxCount > 0, "maxCount must be positive") let start = index - index = start &+ Swift.min(maximumCount, _count &- start) + index = start &+ Swift.min(maxCount, _count &- start) return _span(in: Range(uncheckedBounds: (start, index))) } @inlinable @_lifetime(&self) - public mutating func nextMutableSpan(after index: inout Int, maximumCount: Int) -> MutableSpan { + public mutating func nextMutableSpan( + after index: inout Int, maxCount: Int + ) -> MutableSpan { _checkValidIndex(index) - precondition(maximumCount > 0, "maximumCount must be positive") + precondition(maxCount > 0, "maxCount must be positive") let start = index - index = start &+ Swift.min(maximumCount, _count &- start) + index = start &+ Swift.min(maxCount, _count &- start) return _mutableSpan(in: Range(uncheckedBounds: (start, index))) } @inlinable @_lifetime(borrow self) public func previousSpan( - before index: inout Int, maximumCount: Int + before index: inout Int, maxCount: Int ) -> Span { _checkValidIndex(index) - precondition(maximumCount > 0, "maximumCount must be positive") + precondition(maxCount > 0, "maxCount must be positive") let start = index - index = start &- Swift.min(maximumCount, start) + index = start &- Swift.min(maxCount, start) return _span(in: Range(uncheckedBounds: (index, start))) } } diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Deprecated.swift b/Sources/BasicContainers/RigidArray/RigidArray+Deprecated.swift index 43cc2db5..68d90aa8 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Deprecated.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Deprecated.swift @@ -15,6 +15,33 @@ @available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { + @available(*, deprecated, renamed: "nextSpan(after:maxCount:)") + @inlinable + @_lifetime(borrow self) + public func nextSpan( + after index: inout Int, maximumCount: Int + ) -> Span { + self.nextSpan(after: &index, maxCount: maximumCount) + } + + @available(*, deprecated, renamed: "nextMutableSpan(after:maxCount:)") + @inlinable + @_lifetime(&self) + public mutating func nextMutableSpan( + after index: inout Int, maximumCount: Int + ) -> MutableSpan { + self.nextMutableSpan(after: &index, maxCount: maximumCount) + } + + @available(*, deprecated, renamed: "previousSpan(before:maxCount:)") + @inlinable + @_lifetime(borrow self) + public func previousSpan( + before index: inout Int, maximumCount: Int + ) -> Span { + self.previousSpan(before: &index, maxCount: maximumCount) + } + /// Append a given number of items to the end of this array by populating /// an output span. /// diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Replacements.swift b/Sources/BasicContainers/RigidArray/RigidArray+Replacements.swift index c62bd142..99085eec 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Replacements.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Replacements.swift @@ -446,7 +446,7 @@ extension RigidArray where Element: ~Copyable { /// - newItemCount: The maximum number of items to insert into the array. /// - producer: A producer that generates the items to append. /// - /// - Complexity: O(`self.count` + `maximumCount`) + /// - Complexity: O(`self.count` + `newItemCount`) @_alwaysEmitIntoClient public mutating func replace< E: Error, @@ -594,7 +594,7 @@ extension RigidArray { var it = items.makeIterableIterator_() self.replace(removing: subrange, addingCount: newCount) { target in while !target.isFull { - let source = it.nextSpan_(maximumCount: target.freeCapacity) + let source = it.nextSpan_(maxCount: target.freeCapacity) precondition( !source.isEmpty, "Broken Container: count doesn't match contents") diff --git a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Indices.swift b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Indices.swift index 6563d56d..c8e933cf 100644 --- a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Indices.swift +++ b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Indices.swift @@ -15,7 +15,7 @@ import ContainersPreview #endif -#if compiler(>=6.4) && UnstableHashedContainers +#if compiler(>=6.4) && UnstableHashedContainers && UnstableContainersPreview @available(SwiftStdlib 6.2, *) extension RigidDictionary where Key: ~Copyable, Value: ~Copyable { @@ -87,7 +87,7 @@ where Key: ~Copyable, Value: ~Copyable { public typealias Element_ = Element @_lifetime(&self) - public mutating func nextSpan_(maximumCount: Int) -> Span { + public mutating func nextSpan_(maxCount: Int) -> Span { guard _it.advanceToOccupied() else { return .init() } _current[0] = Element(_bucket: _it.currentBucket) _it.advanceToNextBit() diff --git a/Sources/BasicContainers/RigidSet/RigidSet+BorrowingSequence.swift b/Sources/BasicContainers/RigidSet/RigidSet+BorrowingSequence.swift index dcda6311..14884934 100644 --- a/Sources/BasicContainers/RigidSet/RigidSet+BorrowingSequence.swift +++ b/Sources/BasicContainers/RigidSet/RigidSet+BorrowingSequence.swift @@ -70,11 +70,11 @@ extension RigidSet: Iterable_ where Element: ~Copyable { } @_alwaysEmitIntoClient - @_lifetime(&self) // FIXME: This should be `@_lifetime(copy self)` - public mutating func nextSpan_(maximumCount: Int) -> Span { - precondition(maximumCount > 0, "maximumCount must be positive") + @_lifetime(&self) + public mutating func nextSpan_(maxCount: Int) -> Span { + precondition(maxCount > 0, "maxCount must be positive") guard - let next = _bucketIterator.nextOccupiedRegion(maximumCount: maximumCount) + let next = _bucketIterator.nextOccupiedRegion(maxCount: maxCount) else { return .init() } diff --git a/Sources/BasicContainers/RigidSet/RigidSet+Deprecated.swift b/Sources/BasicContainers/RigidSet/RigidSet+Deprecated.swift new file mode 100644 index 00000000..9e118d5c --- /dev/null +++ b/Sources/BasicContainers/RigidSet/RigidSet+Deprecated.swift @@ -0,0 +1,63 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception +// +//===----------------------------------------------------------------------===// + +#if COLLECTIONS_SINGLE_MODULE // Don't define these outside the Xcode project + +#if compiler(>=6.4) && UnstableHashedContainers +@available(SwiftStdlib 5.0, *) +extension RigidSet where Element: ~Copyable { + @available(*, deprecated, renamed: "insert(addingCount:initializingWith:)") + @_alwaysEmitIntoClient + public mutating func insert( + maximumCount: Int, + initializingWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) -> Void { + try self.insert(addingCount: maximumCount, initializingWith: initializer) + } + + @available(*, deprecated, renamed: "insert(addingCount:from:)") + @_alwaysEmitIntoClient + public mutating func insert< + E: Error, + P: Producer & ~Copyable & ~Escapable + >( + maximumCount: Int?, + from producer: inout P + ) throws(E) + where P.Element: ~Copyable + { + try self.insert(addingCount: maximumCount, from: &producer) + } + + @available(*, deprecated, renamed: "insert(addingCount:from:)") + @_alwaysEmitIntoClient + public mutating func insert< + D: Drain & ~Copyable & ~Escapable + >( + maximumCount: Int?, + from drain: inout D + ) { + var remainder = drain.count + while remainder > 0 { + var span = drain.drainNext(maxCount: remainder) + guard !span.isEmpty else { break } + remainder &-= span.count + while let next = span.popFirst() { + self.insert(next) + } + } + } +} +#endif + +#endif diff --git a/Sources/BasicContainers/RigidSet/RigidSet+Initializers.swift b/Sources/BasicContainers/RigidSet/RigidSet+Initializers.swift index 7146c0b3..d7bc1cf8 100644 --- a/Sources/BasicContainers/RigidSet/RigidSet+Initializers.swift +++ b/Sources/BasicContainers/RigidSet/RigidSet+Initializers.swift @@ -46,7 +46,7 @@ extension RigidSet where Element: ~Copyable { initializingWith initializer: (inout OutputSpan) throws(E) -> Void ) throws(E) { self.init(capacity: capacity) - try self.insert(maximumCount: capacity, initializingWith: initializer) + try self.insert(addingCount: capacity, initializingWith: initializer) } #if UnstableContainersPreview @@ -61,7 +61,7 @@ extension RigidSet where Element: ~Copyable { where P.Element: ~Copyable { self.init(capacity: capacity) - try self.insert(maximumCount: capacity, from: &producer) + try self.insert(addingCount: capacity, from: &producer) } #endif @@ -74,7 +74,7 @@ extension RigidSet where Element: ~Copyable { from drain: inout D ) { self.init(capacity: capacity) - self.insert(maximumCount: capacity, from: &drain) + self.insert(addingCount: capacity, from: &drain) } #endif } diff --git a/Sources/BasicContainers/RigidSet/RigidSet+Insertions.swift b/Sources/BasicContainers/RigidSet/RigidSet+Insertions.swift index 0fdd0c99..b103301c 100644 --- a/Sources/BasicContainers/RigidSet/RigidSet+Insertions.swift +++ b/Sources/BasicContainers/RigidSet/RigidSet+Insertions.swift @@ -102,7 +102,8 @@ extension RigidSet where Element: ~Copyable { /// Inserts the given element in the set if it is not already present. /// /// - Parameter item: An element to insert into the set. - /// - Returns: + /// - Returns: `item` if an equal member already exists in the set; + /// otherwise `nil`. @inlinable @discardableResult public mutating func insert( @@ -121,14 +122,14 @@ extension RigidSet where Element: ~Copyable { extension RigidSet where Element: ~Copyable { @_alwaysEmitIntoClient public mutating func insert( - maximumCount: Int, + addingCount newItemCount: Int, initializingWith initializer: (inout OutputSpan) throws(E) -> Void ) throws(E) -> Void { - precondition(maximumCount >= 0, "Cannot insert a negative number of items") - guard maximumCount > 0 else { return } - precondition(freeCapacity >= maximumCount, "RigidSet capacity overflow") - var remainder = maximumCount - + precondition(newItemCount >= 0, "Cannot insert a negative number of items") + guard newItemCount > 0 else { return } + precondition(freeCapacity >= newItemCount, "RigidSet capacity overflow") + var remainder = newItemCount + // FIXME: Instead of getting temporary buffers, we could place the new // items in unoccupied buckets, then incrementally // rehash them into their correct location, like the stdlib does for @@ -171,13 +172,13 @@ extension RigidSet where Element: ~Copyable { E: Error, P: Producer & ~Copyable & ~Escapable >( - maximumCount: Int? = nil, + addingCount newItemCount: Int? = nil, from producer: inout P ) throws(E) where P.Element: ~Copyable { try self.insert( - maximumCount: maximumCount ?? freeCapacity + addingCount: newItemCount ?? freeCapacity ) { target throws(E) in while !target.isFull { guard try producer.generate(into: &target) else { break } @@ -186,23 +187,36 @@ extension RigidSet where Element: ~Copyable { } #endif +#if UnstableContainersPreview + @_alwaysEmitIntoClient + public mutating func insert< + E: Error, + P: CountedProducer & ~Copyable & ~Escapable + >( + from producer: consuming P + ) throws(E) { + try self.insert(addingCount: producer.count, from: &producer) + try producer._expectEnd("Invalid CountedProducer") + } +#endif + #if UnstableContainersPreview @_alwaysEmitIntoClient public mutating func insert< D: Drain & ~Copyable & ~Escapable >( - maximumCount: Int? = nil, - from drain: inout D + from drain: consuming D ) { - var remainder = maximumCount ?? freeCapacity + var remainder = drain.count while remainder > 0 { - var span = drain.drainNext(maximumCount: remainder) + var span = drain.drainNext(maxCount: remainder) guard !span.isEmpty else { break } remainder &-= span.count while let next = span.popFirst() { self.insert(next) } } + drain._expectEnd("Invalid Drain") } #endif } diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift index d330f1d0..39ca060c 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift @@ -284,7 +284,7 @@ extension UniqueArray where Element: ~Copyable { /// Return a span over the array's storage that begins with the element at /// the given index, and extends to the end of the contiguous storage chunk - /// that contains it, but no more than `maximumCount` items. + /// that contains it, but no more than `maxCount` items. /// /// On return, the index is updated to address the next item following the /// end of the returned span. @@ -295,30 +295,30 @@ extension UniqueArray where Element: ~Copyable { /// /// var index = items.startIndex /// while true { - /// let span = items.nextSpan(after: &index, maximumCount: 4) + /// let span = items.nextSpan(after: &index, maxCount: 4) /// if span.isEmpty { break } /// // Process items in `span` /// } /// - /// The `maximumCount` argument gives the caller control over the number of + /// The `maxCount` argument gives the caller control over the number of /// items it receives from the iterator. This lets the caller avoid getting /// more elements than it would be able to immediately process, which would /// significantly complicate container use. /// /// If the caller is able to process any number available items, it can signal - /// that by passing `Int.max` as the `maximumCount`, or simply by calling the + /// that by passing `Int.max` as the `maxCount`, or simply by calling the /// `nexSpan(after:)` method, which does precisely that. This is frequently /// the case when the caller simply wants to iterate over the entire /// container in a single loop. /// - /// `maximumCount` sets an upper bound. To read a specific number of items, + /// `maxCount` sets an upper bound. To read a specific number of items, /// the caller usually needs to invoke `nextSpan` in a loop: /// /// var items: some Container /// var index = items.startIndex /// var remainder = numberOfItemsToRead /// while remainder > 0 { - /// let next = items.nextSpan(after: &index, maximumCount: remainder) + /// let next = items.nextSpan(after: &index, maxCount: remainder) /// guard !next.isEmpty else { /// // Container does not have enough items /// break @@ -341,10 +341,10 @@ extension UniqueArray where Element: ~Copyable { /// - Parameter index: A valid index in the container, including the end /// index. On return, this index is advanced by the count of the resulting /// span, to simplify iteration. - /// - Parameter maximumCount: The maximum number of items the caller is able - /// to process immediately. `maximumCount` must be greater than zero. + /// - Parameter maxCount: The maximum number of items the caller is able + /// to process immediately. `maxCount` must be greater than zero. /// If you are able to process an arbitrary number of items, set - /// `maximumCount` to `Int.max`, or call the `nextSpan(after:)` method. + /// `maxCount` to `Int.max`, or call the `nextSpan(after:)` method. /// - Returns: A span over contiguous storage that starts at the given index. /// If the input index is the end index, then this returns an empty span. /// Otherwise the result is non-empty, with its first element matching the @@ -353,25 +353,25 @@ extension UniqueArray where Element: ~Copyable { @inlinable @_lifetime(borrow self) public func nextSpan( - after index: inout Int, maximumCount: Int + after index: inout Int, maxCount: Int ) -> Span { - _storage.nextSpan(after: &index, maximumCount: maximumCount) + _storage.nextSpan(after: &index, maxCount: maxCount) } @inlinable @_lifetime(&self) public mutating func nextMutableSpan( - after index: inout Int, maximumCount: Int + after index: inout Int, maxCount: Int ) -> MutableSpan { - _storage.nextMutableSpan(after: &index, maximumCount: maximumCount) + _storage.nextMutableSpan(after: &index, maxCount: maxCount) } @inlinable @_lifetime(borrow self) public func previousSpan( - before index: inout Int, maximumCount: Int + before index: inout Int, maxCount: Int ) -> Span { - _storage.previousSpan(before: &index, maximumCount: maximumCount) + _storage.previousSpan(before: &index, maxCount: maxCount) } } diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Deprecated.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Deprecated.swift index 8a7b7028..b1839027 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Deprecated.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Deprecated.swift @@ -15,6 +15,33 @@ @available(SwiftStdlib 5.0, *) extension UniqueArray where Element: ~Copyable { + @available(*, deprecated, renamed: "nextSpan(after:maxCount:)") + @inlinable + @_lifetime(borrow self) + public func nextSpan( + after index: inout Int, maximumCount: Int + ) -> Span { + self.nextSpan(after: &index, maxCount: maximumCount) + } + + @available(*, deprecated, renamed: "nextMutableSpan(after:maxCount:)") + @inlinable + @_lifetime(&self) + public mutating func nextMutableSpan( + after index: inout Int, maximumCount: Int + ) -> MutableSpan { + self.nextMutableSpan(after: &index, maxCount: maximumCount) + } + + @available(*, deprecated, renamed: "previousSpan(before:maxCount:)") + @inlinable + @_lifetime(borrow self) + public func previousSpan( + before index: inout Int, maximumCount: Int + ) -> Span { + self.previousSpan(before: &index, maxCount: maximumCount) + } + /// Initializes a new unique array with the specified capacity and no elements. @available(*, deprecated, renamed: "init(minimumCapacity:)") @inlinable diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Replacements.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Replacements.swift index 2b6c91b5..816e5818 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Replacements.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Replacements.swift @@ -346,7 +346,7 @@ extension UniqueArray where Element: ~Copyable { @available(SwiftStdlib 5.0, *) extension UniqueArray where Element: ~Copyable { #if compiler(>=6.4) && UnstableContainersPreview - /// Replaces the specified range of elements by at most `maximumCount` items + /// Replaces the specified range of elements by at most `maxCount` items /// generated by a producer. /// /// This method has the effect of removing the specified range of elements @@ -367,8 +367,8 @@ extension UniqueArray where Element: ~Copyable { /// directly expressed by calling `removeSubrange`. /// /// This operation inserts as many items as the producer can generate before - /// either reaching `maximumCount`, or the producer hitting its end, or - /// throwing an error. If the producer has more than `maximumCount` items left in + /// either reaching `maxCount`, or the producer hitting its end, or + /// throwing an error. If the producer has more than `maxCount` items left in /// its underlying sequence, then extra items remain available after this /// method returns. /// diff --git a/Sources/BasicContainers/UniqueSet/UniqueSet+Deprecations.swift b/Sources/BasicContainers/UniqueSet/UniqueSet+Deprecations.swift new file mode 100644 index 00000000..08823fe8 --- /dev/null +++ b/Sources/BasicContainers/UniqueSet/UniqueSet+Deprecations.swift @@ -0,0 +1,30 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception +// +//===----------------------------------------------------------------------===// + +#if COLLECTIONS_SINGLE_MODULE // Don't define these outside the Xcode project + +#if compiler(>=6.4) && UnstableHashedContainers +@available(SwiftStdlib 5.0, *) +extension UniqueSet where Element: ~Copyable { + @available(*, deprecated, renamed: "insert(addingCount:initializingWith:)") + @_alwaysEmitIntoClient + public mutating func insert( + maximumCount: Int, + initializingWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) -> Void { + try self.insert(addingCount: maximumCount, initializingWith: initializer) + } +} +#endif + +#endif diff --git a/Sources/BasicContainers/UniqueSet/UniqueSet+Initializers.swift b/Sources/BasicContainers/UniqueSet/UniqueSet+Initializers.swift index 03ffcf4f..c6855e27 100644 --- a/Sources/BasicContainers/UniqueSet/UniqueSet+Initializers.swift +++ b/Sources/BasicContainers/UniqueSet/UniqueSet+Initializers.swift @@ -46,7 +46,7 @@ extension UniqueSet where Element: ~Copyable { ) throws(E) { self.init(minimumCapacity: minimumCapacity) try self.insert( - maximumCount: minimumCapacity, + addingCount: minimumCapacity, initializingWith: initializer) } diff --git a/Sources/BasicContainers/UniqueSet/UniqueSet+Insertions.swift b/Sources/BasicContainers/UniqueSet/UniqueSet+Insertions.swift index 1a9d235b..162de94b 100644 --- a/Sources/BasicContainers/UniqueSet/UniqueSet+Insertions.swift +++ b/Sources/BasicContainers/UniqueSet/UniqueSet+Insertions.swift @@ -56,7 +56,8 @@ extension UniqueSet where Element: ~Copyable { /// Inserts the given element in the set if it is not already present. /// /// - Parameter item: An element to insert into the set. - /// - Returns: + /// - Returns: `item` if an equal member already exists in the set; + /// otherwise `nil`. @inlinable @discardableResult public mutating func insert( @@ -71,12 +72,12 @@ extension UniqueSet where Element: ~Copyable { extension UniqueSet where Element: ~Copyable { @_alwaysEmitIntoClient public mutating func insert( - maximumCount: Int, + addingCount newItemCount: Int, initializingWith initializer: (inout OutputSpan) throws(E) -> Void ) throws(E) -> Void { - _ensureFreeCapacity(maximumCount) + _ensureFreeCapacity(newItemCount) try _storage.insert( - maximumCount: maximumCount, initializingWith: initializer) + addingCount: newItemCount, initializingWith: initializer) } #if UnstableContainersPreview @@ -92,7 +93,7 @@ extension UniqueSet where Element: ~Copyable { var done = false while !done { _ensureFreeCapacity(Swift.max(producer.underestimatedCount, 1)) - try self.insert(maximumCount: self.freeCapacity) { target throws(E) in + try self.insert(addingCount: self.freeCapacity) { target throws(E) in while !target.isFull, !done { done = try !producer.generate(into: &target) } diff --git a/Sources/BitCollections/BitArray/BitArray+ChunkedBitsIterators.swift b/Sources/BitCollections/BitArray/BitArray+ChunkedBitsIterators.swift index 5b6c7610..715bb5ab 100644 --- a/Sources/BitCollections/BitArray/BitArray+ChunkedBitsIterators.swift +++ b/Sources/BitCollections/BitArray/BitArray+ChunkedBitsIterators.swift @@ -87,15 +87,15 @@ internal struct _ChunkedBitsBackwardIterator { extension IteratorProtocol where Element == Bool { mutating func _nextChunk( - maximumCount: UInt = _Word._capacity + maxCount: UInt = _Word._capacity ) -> (bits: _Word, count: UInt) { - assert(maximumCount <= _Word.capacity) + assert(maxCount <= _Word.capacity) var bits = _Word.empty var c: UInt = 0 while let v = next() { if v { bits.insert(c) } c += 1 - if c == maximumCount { break } + if c == maxCount { break } } return (bits, c) } diff --git a/Sources/BitCollections/BitArray/BitArray+Copy.swift b/Sources/BitCollections/BitArray/BitArray+Copy.swift index 2cc80b73..f40faecb 100644 --- a/Sources/BitCollections/BitArray/BitArray+Copy.swift +++ b/Sources/BitCollections/BitArray/BitArray+Copy.swift @@ -162,7 +162,7 @@ extension BitArray._UnsafeHandle { var it = source.makeIterator() if pos.bit > 0 { let (bits, count) = it._nextChunk( - maximumCount: _Word._capacity - pos.bit) + maxCount: _Word._capacity - pos.bit) _copy(bits: bits, count: count, to: pos) pos.value += count } diff --git a/Sources/BitCollections/BitArray/BitArray+RangeReplaceableCollection.swift b/Sources/BitCollections/BitArray/BitArray+RangeReplaceableCollection.swift index ca1e319e..7cf20ac8 100644 --- a/Sources/BitCollections/BitArray/BitArray+RangeReplaceableCollection.swift +++ b/Sources/BitCollections/BitArray/BitArray+RangeReplaceableCollection.swift @@ -285,7 +285,7 @@ extension BitArray { var pos = _BitPosition(_count) if pos.bit > 0 { let (bits, count) = it._nextChunk( - maximumCount: _Word._capacity - pos.bit) + maxCount: _Word._capacity - pos.bit) guard count > 0 else { return } _count += count _update { $0._copy(bits: bits, count: count, to: pos) } diff --git a/Sources/ContainersPreview/CMakeLists.txt b/Sources/ContainersPreview/CMakeLists.txt index 2e2a478c..ece38517 100644 --- a/Sources/ContainersPreview/CMakeLists.txt +++ b/Sources/ContainersPreview/CMakeLists.txt @@ -64,7 +64,7 @@ target_sources(${module_name} PRIVATE "Protocols/Producer+Reduce.swift" "Types/InputSpan.swift" "Types/MutableRef.swift" - "Types/OutputSpan+Extras.swift" + "Types/OutputSpan+Helpers.swift" "Types/Shared.swift" "Types/SpanIterator.swift" "Types/UniqueBox.swift" diff --git a/Sources/ContainersPreview/Conformances/InputSpan+Container.swift b/Sources/ContainersPreview/Conformances/InputSpan+Container.swift index ebc6655f..805907ce 100644 --- a/Sources/ContainersPreview/Conformances/InputSpan+Container.swift +++ b/Sources/ContainersPreview/Conformances/InputSpan+Container.swift @@ -31,10 +31,10 @@ where Element: ~Copyable @inlinable @_lifetime(borrow self) - public func nextSpan(after index: inout Index, maximumCount: Int) -> Span { + public func nextSpan(after index: inout Index, maxCount: Int) -> Span { precondition(index >= 0 && index <= count, "Index out of bounds") - precondition(maximumCount > 0, "maximumCount must be positive") - let c = Swift.min(count &- index, maximumCount) + precondition(maxCount > 0, "maxCount must be positive") + let c = Swift.min(count &- index, maxCount) let start = capacity &- count &+ index return _uncheckedSpan(in: Range(uncheckedBounds: (start, start &+ c))) } @@ -42,21 +42,21 @@ where Element: ~Copyable @inlinable @_lifetime(&self) public mutating func nextMutableSpan( - after index: inout Index, maximumCount: Int + after index: inout Index, maxCount: Int ) -> MutableSpan { precondition(index >= 0 && index <= count, "Index out of bounds") - precondition(maximumCount > 0, "maximumCount must be positive") - let c = Swift.min(count &- index, maximumCount) + precondition(maxCount > 0, "maxCount must be positive") + let c = Swift.min(count &- index, maxCount) let start = capacity &- count &+ index return _uncheckedMutableSpan(in: Range(uncheckedBounds: (start, start &+ c))) } @inlinable @_lifetime(borrow self) - public func previousSpan(before index: inout Int, maximumCount: Int) -> Span { + public func previousSpan(before index: inout Int, maxCount: Int) -> Span { precondition(index >= 0 && index <= count, "Index out of bounds") - precondition(maximumCount > 0, "maximumCount must be positive") - let c = Swift.min(index, maximumCount) + precondition(maxCount > 0, "maxCount must be positive") + let c = Swift.min(index, maxCount) let end = capacity &- count &+ index return _uncheckedSpan(in: Range(uncheckedBounds: (end &- c, end))) } diff --git a/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift b/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift index 508332b7..4b524e46 100644 --- a/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift +++ b/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift @@ -31,22 +31,22 @@ extension MutableSpan: RandomAccessContainer where Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(borrow self) public func nextSpan( - after index: inout Int, maximumCount: Int + after index: inout Int, maxCount: Int ) -> Span { precondition(index >= 0 && index <= count, "Index out of bounds") - precondition(maximumCount > 0, "maximumCount must be positive") - let limit = index &+ Swift.min(maximumCount, count &- index) + precondition(maxCount > 0, "maxCount must be positive") + let limit = index &+ Swift.min(maxCount, count &- index) return self.span.extracting(unchecked: Range(uncheckedBounds: (index, limit))) } @_alwaysEmitIntoClient @_lifetime(borrow self) public func previousSpan( - before index: inout Int, maximumCount: Int + before index: inout Int, maxCount: Int ) -> Span { precondition(index >= 0 && index <= count, "Index out of bounds") - precondition(maximumCount > 0, "maximumCount must be positive") - let limit = index &- Swift.min(maximumCount, index) + precondition(maxCount > 0, "maxCount must be positive") + let limit = index &- Swift.min(maxCount, index) return self.span.extracting(unchecked: Range(uncheckedBounds: (limit, index))) } } @@ -55,11 +55,11 @@ extension MutableSpan: MutableContainer where Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(&self) public mutating func nextMutableSpan( - after index: inout Int, maximumCount: Int + after index: inout Int, maxCount: Int ) -> MutableSpan { precondition(index >= 0 && index <= count, "Index out of bounds") - precondition(maximumCount > 0, "maximumCount must be positive") - let limit = index &+ Swift.min(maximumCount, count &- index) + precondition(maxCount > 0, "maxCount must be positive") + let limit = index &+ Swift.min(maxCount, count &- index) return self._mutatingExtracting(unchecked: Range(uncheckedBounds: (index, limit))) } } diff --git a/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift b/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift index 84db9109..d3f5ceb8 100644 --- a/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift +++ b/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift @@ -30,30 +30,30 @@ where Element: ~Copyable @inlinable @_lifetime(borrow self) - public func nextSpan(after index: inout Index, maximumCount: Int) -> Span { + public func nextSpan(after index: inout Index, maxCount: Int) -> Span { precondition(index >= 0 && index <= count, "Index out of bounds") - precondition(maximumCount > 0, "maximumCount must be positive") - let limit = Swift.min(count &- index, maximumCount) + precondition(maxCount > 0, "maxCount must be positive") + let limit = Swift.min(count &- index, maxCount) return self.span.extracting(unchecked: Range(uncheckedBounds: (index, limit))) } @inlinable @_lifetime(&self) public mutating func nextMutableSpan( - after index: inout Index, maximumCount: Int + after index: inout Index, maxCount: Int ) -> MutableSpan { precondition(index >= 0 && index <= count, "Index out of bounds") - precondition(maximumCount > 0, "maximumCount must be positive") - let limit = Swift.min(count &- index, maximumCount) + precondition(maxCount > 0, "maxCount must be positive") + let limit = Swift.min(count &- index, maxCount) return self.mutableSpan._consumingExtracting(Range(uncheckedBounds: (index, limit))) } @inlinable @_lifetime(borrow self) - public func previousSpan(before index: inout Int, maximumCount: Int) -> Span { + public func previousSpan(before index: inout Int, maxCount: Int) -> Span { precondition(index >= 0 && index <= count, "Index out of bounds") - precondition(maximumCount > 0, "maximumCount must be positive") - let limit = Swift.max(0, index - maximumCount) + precondition(maxCount > 0, "maxCount must be positive") + let limit = Swift.max(0, index - maxCount) return self.span.extracting(unchecked: Range(uncheckedBounds: (limit, index))) } } diff --git a/Sources/ContainersPreview/Conformances/Span+Container.swift b/Sources/ContainersPreview/Conformances/Span+Container.swift index 06397241..4d5c81d5 100644 --- a/Sources/ContainersPreview/Conformances/Span+Container.swift +++ b/Sources/ContainersPreview/Conformances/Span+Container.swift @@ -26,19 +26,19 @@ extension Span: RandomAccessContainer where Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(borrow self) - public func nextSpan(after index: inout Int, maximumCount: Int) -> Span { + public func nextSpan(after index: inout Int, maxCount: Int) -> Span { precondition(index >= 0 && index <= count, "Index out of bounds") - precondition(maximumCount > 0, "maximumCount must be positive") - let limit = index &+ Swift.min(maximumCount, count &- index) + 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 previousSpan(before index: inout Int, maximumCount: Int) -> Span { + public func previousSpan(before index: inout Int, maxCount: Int) -> Span { precondition(index >= 0 && index <= count, "Index out of bounds") - precondition(maximumCount > 0, "maximumCount must be positive") - let limit = index &- Swift.min(maximumCount, index) + precondition(maxCount > 0, "maxCount must be positive") + let limit = index &- Swift.min(maxCount, index) return self.extracting(unchecked: Range(uncheckedBounds: (limit, index))) } } diff --git a/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+ElementsEqual.swift b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+ElementsEqual.swift index b9786690..fd321645 100644 --- a/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+ElementsEqual.swift +++ b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+ElementsEqual.swift @@ -123,7 +123,7 @@ where // Note: This is the less efficient implementation of elementsEqual. The // variant in the #else branch would be preferable, but it doesn't work yet. // (It lets the two iterators run at their native speeds, with no artificial - // maximumCounts.) + // maxCounts.) while true { let a = try self.nextSpan_() var i = 0 @@ -131,7 +131,7 @@ where return try other.nextSpan_().isEmpty } while i < a.count { - let b = try other.nextSpan_(maximumCount: a.count - i) + let b = try other.nextSpan_(maxCount: a.count - i) if b.isEmpty { return false } diff --git a/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+Filter.swift b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+Filter.swift index 62ea6c1e..c5cc3d96 100644 --- a/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+Filter.swift +++ b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+Filter.swift @@ -59,10 +59,10 @@ where Base.Element_: ~Copyable { extension BorrowingFilter: BorrowingIteratorProtocol_ where Base: ~Copyable & ~Escapable, Base.Element_: ~Copyable { @_lifetime(&self) - public mutating func nextSpan_(maximumCount: Int) throws(Failure) -> Span { + public mutating func nextSpan_(maxCount: Int) throws(Failure) -> Span { // FIXME: This is quite inefficient compared to Container's filter while true { - let span = try _base.nextSpan_(maximumCount: 1) + let span = try _base.nextSpan_(maxCount: 1) if span.isEmpty { return span } precondition(span.count == 1, "Invalid BorrowingIterator") if try _isIncluded(span[unchecked: 0]) { return span } diff --git a/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+Map.swift b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+Map.swift index 9192d9c0..73affc6c 100644 --- a/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+Map.swift +++ b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+Map.swift @@ -90,7 +90,7 @@ where @inlinable @_lifetime(self: copy self) public mutating func next() throws(Failure) -> Element? { - let span = try _it.nextSpan_(maximumCount: 1) + let span = try _it.nextSpan_(maxCount: 1) guard !span.isEmpty else { return nil } return try _transform(span[unchecked: 0]) } @@ -104,7 +104,7 @@ where ) throws(Failure) -> Bool { var success = false while !target.isFull { - let span = try _it.nextSpan_(maximumCount: target.freeCapacity) + let span = try _it.nextSpan_(maxCount: target.freeCapacity) guard !span.isEmpty else { break } success = true var i = 0 diff --git a/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+MapError.swift b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+MapError.swift index 87f358e3..292db26e 100644 --- a/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+MapError.swift +++ b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+MapError.swift @@ -73,9 +73,9 @@ where @inlinable @_lifetime(&self) @_lifetime(self: copy self) - public mutating func nextSpan_(maximumCount: Int) throws(Failure_) -> Span { + public mutating func nextSpan_(maxCount: Int) throws(Failure_) -> Span { do { - return try _base.nextSpan_(maximumCount: maximumCount) + return try _base.nextSpan_(maxCount: maxCount) } catch { throw _transform(error) } diff --git a/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+SpanwiseZip.swift b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+SpanwiseZip.swift index 60dcaf3a..393f2023 100644 --- a/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+SpanwiseZip.swift +++ b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+SpanwiseZip.swift @@ -38,7 +38,7 @@ where // Note: This is the less efficient implementation of spanwiseZip. The // variant in the #else branch would be preferable, but it doesn't work yet. // (It lets the two iterators run at their native speeds, with no artificial - // maximumCounts.) + // maxCounts.) loop: while true { var a = try self.nextSpan_() @@ -51,7 +51,7 @@ where return } repeat { - let b = try other.nextSpan_(maximumCount: a.count) + let b = try other.nextSpan_(maxCount: a.count) if b.isEmpty { guard try process(&state, a, b) else { return } } else { diff --git a/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol.swift b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol.swift index b26aa039..ea33fd18 100644 --- a/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol.swift +++ b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol.swift @@ -34,10 +34,10 @@ public protocol BorrowingIteratorProtocol_: ~Copyable, ~Esca /// invocation of it. /// /// If the iterator has not yet reached the end of the underlying sequence, - /// then this method returns a non-empty span of at most `maximumCount` + /// then this method returns a non-empty span of at most `maxCount` /// elements, and updates the iterator's current position to the element /// following the last item in the returned span (or the end, if there is - /// none). The `maximumCount` argument allows callers to avoid getting more + /// none). The `maxCount` argument allows callers to avoid getting more /// items that they are able to process in one go, simplifying usage, and /// avoiding materializing more elements than needed. /// @@ -70,7 +70,7 @@ public protocol BorrowingIteratorProtocol_: ~Copyable, ~Esca /// method may vary between different borrows of the same container.) @_lifetime(&self) @_lifetime(self: copy self) - mutating func nextSpan_(maximumCount: Int) throws(Failure_) -> Span + mutating func nextSpan_(maxCount: Int) throws(Failure_) -> Span /// Advance the position of this iterator by the specified offset, or until /// the end of the underlying sequence. @@ -92,7 +92,7 @@ where Self: ~Copyable & ~Escapable, Element_: ~Copyable { @_lifetime(self: copy self) @_transparent public mutating func nextSpan_() throws(Failure_) -> Span { - try nextSpan_(maximumCount: Int.max) + try nextSpan_(maxCount: Int.max) } } @@ -104,7 +104,7 @@ where Self: ~Copyable & ~Escapable, Element_: ~Copyable { public mutating func skip_(by offset: Int) throws(Failure_) -> Int { var remainder = offset while remainder > 0 { - let span = try nextSpan_(maximumCount: remainder) + let span = try nextSpan_(maxCount: remainder) if span.isEmpty { break } remainder &-= span.count } @@ -118,7 +118,7 @@ extension BorrowingIteratorProtocol_ where Self: ~Copyable & ~Escapable { @_lifetime(&self) @_lifetime(self: copy self) public mutating func next() -> Ref? { - let span = nextSpan(maximumCount: 1) + let span = nextSpan(maxCount: 1) guard !span.isEmpty else { return nil } return Ref(_borrowing: span[unchecked: 0]) } @@ -136,7 +136,7 @@ extension BorrowingIteratorProtocol_ try target.withUnsafeMutableBufferPointer { (dst, dstCount) throws(Failure_) -> Void in var tail = dst._extracting(droppingFirst: dstCount) while !tail.isEmpty { - let src = try nextSpan_(maximumCount: tail.count) + let src = try nextSpan_(maxCount: tail.count) if src.isEmpty { break } tail._initializeAndDropPrefix(copying: src) dstCount += src.count diff --git a/Sources/ContainersPreview/Protocols/Container/BidirectionalContainer.swift b/Sources/ContainersPreview/Protocols/Container/BidirectionalContainer.swift index 0a4b54bc..6c1e3535 100644 --- a/Sources/ContainersPreview/Protocols/Container/BidirectionalContainer.swift +++ b/Sources/ContainersPreview/Protocols/Container/BidirectionalContainer.swift @@ -50,7 +50,7 @@ where Element: ~Copyable, Index: Comparable func formIndex(before i: inout Index) @_lifetime(borrow self) - func previousSpan(before index: inout Index, maximumCount: Int) -> Span + func previousSpan(before index: inout Index, maxCount: Int) -> Span override func index(after index: Index) -> Index @@ -77,7 +77,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { @inlinable @_lifetime(borrow self) public func previousSpan(before index: inout Index) -> Span { - previousSpan(before: &index, maximumCount: Int.max) + previousSpan(before: &index, maxCount: Int.max) } @inlinable @@ -107,7 +107,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { var n = n if n >= 0 { while n > 0 { - let span = self.nextSpan(after: &index, maximumCount: n) + let span = self.nextSpan(after: &index, maxCount: n) precondition( !span.isEmpty, "Cannot advance index beyond the end of the container") @@ -116,7 +116,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { } else { n = -n while n > 0 { - let span = self.previousSpan(before: &index, maximumCount: n) + let span = self.previousSpan(before: &index, maxCount: n) precondition( !span.isEmpty, "Cannot advance index beyond the end of the container") @@ -142,7 +142,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { // Skip forward until we find our target or overshoot the limit. while n > 0 { var j = index - let span = self.nextSpan(after: &j, maximumCount: n) + let span = self.nextSpan(after: &j, maxCount: n) precondition( !span.isEmpty, "Cannot advance index beyond the end of the container") @@ -172,7 +172,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { // Skip backward until we find our target or overshoot the limit. while n < 0 { var j = index - let span = self.previousSpan(before: &j, maximumCount: -n) + let span = self.previousSpan(before: &j, maxCount: -n) precondition( !span.isEmpty, "Cannot move index before the start of the container") diff --git a/Sources/ContainersPreview/Protocols/Container/Container+Filter.swift b/Sources/ContainersPreview/Protocols/Container/Container+Filter.swift index 47107f6d..5968aa33 100644 --- a/Sources/ContainersPreview/Protocols/Container/Container+Filter.swift +++ b/Sources/ContainersPreview/Protocols/Container/Container+Filter.swift @@ -92,8 +92,8 @@ extension ContainerFilter: BorrowingIteratorProtocol_ where Element: ~Copyable { public typealias Element_ = Base.Element @_lifetime(&self) // FIXME: This should be `@_lifetime(copy self)` - public mutating func nextSpan_(maximumCount: Int) -> Span { - precondition(maximumCount > 0) + public mutating func nextSpan_(maxCount: Int) -> Span { + precondition(maxCount > 0) while true { // Drop filtered out items from prefix of _remainder var i = 0 @@ -102,7 +102,7 @@ extension ContainerFilter: BorrowingIteratorProtocol_ where Element: ~Copyable { } _remainder = _remainder.extracting(droppingFirst: i) if !_remainder.isEmpty { - let c = Swift.min(_remainder.count, maximumCount) + let c = Swift.min(_remainder.count, maxCount) i = 1 while i < c, _isIncluded(_remainder[unchecked: i]) { i &+= 1 diff --git a/Sources/ContainersPreview/Protocols/Container/Container.swift b/Sources/ContainersPreview/Protocols/Container/Container.swift index 89eb8e6f..dd45a270 100644 --- a/Sources/ContainersPreview/Protocols/Container/Container.swift +++ b/Sources/ContainersPreview/Protocols/Container/Container.swift @@ -109,7 +109,7 @@ public protocol Container: /// Return a span over the container's storage that begins with the element at /// the given index, and extends to the end of the contiguous storage chunk - /// that contains it, but no more than `maximumCount` items. + /// that contains it, but no more than `maxCount` items. /// /// On return, the index is updated to address the next item following the /// end of the returned span. @@ -120,30 +120,30 @@ public protocol Container: /// /// var index = items.startIndex /// while true { - /// let span = items.nextSpan(after: &index, maximumCount: 4) + /// let span = items.nextSpan(after: &index, maxCount: 4) /// if span.isEmpty { break } /// // Process items in `span` /// } /// - /// The `maximumCount` argument gives the caller control over the number of + /// The `maxCount` argument gives the caller control over the number of /// items it receives from the iterator. This lets the caller avoid getting /// more elements than it would be able to immediately process, which would /// significantly complicate container use. /// /// If the caller is able to process any number available items, it can signal - /// that by passing `Int.max` as the `maximumCount`, or simply by calling the + /// that by passing `Int.max` as the `maxCount`, or simply by calling the /// `nexSpan(after:)` method, which does precisely that. This is frequently /// the case when the caller simply wants to iterate over the entire /// container in a single loop. /// - /// `maximumCount` sets an upper bound. To read a specific number of items, + /// `maxCount` sets an upper bound. To read a specific number of items, /// the caller usually needs to invoke `nextSpan` in a loop: /// /// var items: some Container /// var index = items.startIndex /// var remainder = numberOfItemsToRead /// while remainder > 0 { - /// let next = items.nextSpan(after: &index, maximumCount: remainder) + /// let next = items.nextSpan(after: &index, maxCount: remainder) /// guard !next.isEmpty else { /// // Container does not have enough items /// break @@ -166,16 +166,16 @@ public protocol Container: /// - Parameter index: A valid index in the container, including the end /// index. On return, this index is advanced by the count of the resulting /// span, to simplify iteration. - /// - Parameter maximumCount: The maximum number of items the caller is able - /// to process immediately. `maximumCount` must be greater than zero. + /// - Parameter maxCount: The maximum number of items the caller is able + /// to process immediately. `maxCount` must be greater than zero. /// If you are able to process an arbitrary number of items, set - /// `maximumCount` to `Int.max`, or call the `nextSpan(after:)` method. + /// `maxCount` to `Int.max`, or call the `nextSpan(after:)` method. /// - Returns: A span over contiguous storage that starts at the given index. /// If the input index is the end index, then this returns an empty span. /// Otherwise the result is non-empty, with its first element matching the /// element at the input index. @_lifetime(borrow self) - func nextSpan(after index: inout Index, maximumCount: Int) -> Span + func nextSpan(after index: inout Index, maxCount: Int) -> Span /// Return the nearest valid index in this container less than or equal to /// the given index value, which must be valid in at least one view of self. @@ -252,7 +252,7 @@ extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(borrow self) public func nextSpan(after index: inout Index) -> Span { - nextSpan(after: &index, maximumCount: Int.max) + nextSpan(after: &index, maxCount: Int.max) } } @@ -282,16 +282,16 @@ extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { var index = self.index(alignedDown: index) var n = n -#if true // with nextSpan(after:maximumCount:) +#if true // with nextSpan(after:maxCount:) while n > 0 { - let span = self.nextSpan(after: &index, maximumCount: n) + let span = self.nextSpan(after: &index, maxCount: n) precondition( !span.isEmpty, "Cannot advance index beyond the end of the container") n &-= span.count } return index -#else // without nextSpan(after:maximumCount:) +#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. diff --git a/Sources/ContainersPreview/Protocols/Container/ContainerIterator.swift b/Sources/ContainersPreview/Protocols/Container/ContainerIterator.swift index 80483914..bc0bc204 100644 --- a/Sources/ContainersPreview/Protocols/Container/ContainerIterator.swift +++ b/Sources/ContainersPreview/Protocols/Container/ContainerIterator.swift @@ -60,8 +60,8 @@ where @_alwaysEmitIntoClient @_unsafeNonescapableResult // FIXME: we cannot convert from a borrow to an inout dependence?! @_lifetime(&self) - public mutating func nextSpan_(maximumCount: Int) -> Span { - _base.value.nextSpan(after: &self._position, maximumCount: maximumCount) + public mutating func nextSpan_(maxCount: Int) -> Span { + _base.value.nextSpan(after: &self._position, maxCount: maxCount) } @_alwaysEmitIntoClient diff --git a/Sources/ContainersPreview/Protocols/Container/MutableContainer.swift b/Sources/ContainersPreview/Protocols/Container/MutableContainer.swift index 267352c1..c0000f95 100644 --- a/Sources/ContainersPreview/Protocols/Container/MutableContainer.swift +++ b/Sources/ContainersPreview/Protocols/Container/MutableContainer.swift @@ -29,7 +29,7 @@ where /// Return a mutable span over the container's storage that begins with the /// element at the given index, and extends to the end of the contiguous - /// storage chunk that contains it, but no more than `maximumCount` items. + /// storage chunk that contains it, but no more than `maxCount` items. /// /// On return, the index is updated to address the next item following the /// end of the returned span. @@ -40,30 +40,30 @@ where /// /// var index = items.startIndex /// while true { - /// var span = items.nextMutableSpan(after: &index, maximumCount: 4) + /// var span = items.nextMutableSpan(after: &index, maxCount: 4) /// if span.isEmpty { break } /// // Process items in `span` /// } /// - /// The `maximumCount` argument gives the caller control over the number of + /// The `maxCount` argument gives the caller control over the number of /// items it receives from the iterator. This lets the caller avoid getting /// more elements than it would be able to immediately process, which would /// significantly complicate container use. /// /// If the caller is able to process any number available items, it can signal - /// that by passing `Int.max` as the `maximumCount`, or simply by calling the + /// that by passing `Int.max` as the `maxCount`, or simply by calling the /// `nexSpan(after:)` method, which does precisely that. This is frequently /// the case when the caller simply wants to iterate over the entire /// container in a single loop. /// - /// `maximumCount` sets an upper bound. To read a specific number of items, + /// `maxCount` sets an upper bound. To read a specific number of items, /// the caller usually needs to invoke `nextSpan` in a loop: /// /// var items: some MutableContainer /// var index = items.startIndex /// var remainder = numberOfItemsToRead /// while remainder > 0 { - /// let next = items.nextMutableSpan(after: &index, maximumCount: remainder) + /// let next = items.nextMutableSpan(after: &index, maxCount: remainder) /// guard !next.isEmpty else { /// // Container does not have enough items /// break @@ -82,10 +82,10 @@ where /// - Parameter index: A valid index in the container, including the end /// index. On return, this index is advanced by the count of the resulting /// span, to simplify iteration. - /// - Parameter maximumCount: The maximum number of items the caller is able - /// to process immediately. `maximumCount` must be greater than zero. + /// - Parameter maxCount: The maximum number of items the caller is able + /// to process immediately. `maxCount` must be greater than zero. /// If you are able to process an arbitrary number of items, set - /// `maximumCount` to `Int.max`, or call the `nextSpan(after:)` method. + /// `maxCount` to `Int.max`, or call the `nextSpan(after:)` method. /// - Returns: A mutable span over contiguous storage that starts at the given /// index. If the input index is the end index, then this returns an empty /// span. Otherwise the result is non-empty, with its first element @@ -93,7 +93,7 @@ where @_lifetime(&self) mutating func nextMutableSpan( after index: inout Index, - maximumCount: Int + maxCount: Int ) -> MutableSpan } @@ -106,7 +106,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable mutating func nextMutableSpan( after index: inout Index, ) -> MutableSpan { - nextMutableSpan(after: &index, maximumCount: Int.max) + nextMutableSpan(after: &index, maxCount: Int.max) } } diff --git a/Sources/ContainersPreview/Protocols/Container/RangeReplaceableContainer.swift b/Sources/ContainersPreview/Protocols/Container/RangeReplaceableContainer.swift index d9142942..c58d1aea 100644 --- a/Sources/ContainersPreview/Protocols/Container/RangeReplaceableContainer.swift +++ b/Sources/ContainersPreview/Protocols/Container/RangeReplaceableContainer.swift @@ -209,9 +209,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable removing: subrange, addingCount: producer.count, from: &producer) - if try !producer._isAtEnd() { - preconditionFailure("Invalid Container") - } + try producer._expectEnd("Invalid Container") } @_alwaysEmitIntoClient @@ -278,9 +276,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable var producer = source.consume(sourceSubrange) let targetSubrange = targetSubrange.relative(to: self) self.replace(removing: targetSubrange, addingCount: c, from: &producer) - if !producer._isAtEnd() { - preconditionFailure("Invalid Container") - } + producer._expectEnd("Invalid Container") } @_alwaysEmitIntoClient @@ -521,9 +517,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable while !target.isFull, try producer.generate(into: &target) { } } - if try !producer._isAtEnd() { - preconditionFailure("Invalid Container") - } + try producer._expectEnd("Invalid Container") } @_alwaysEmitIntoClient @@ -548,9 +542,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable let c = source.distance(from: sourceSubrange.lowerBound, to: sourceSubrange.upperBound) var producer = source.consume(sourceSubrange) self.insert(addingCount: c, from: &producer, at: index) - if !producer._isAtEnd() { - preconditionFailure("Invalid Container") - } + producer._expectEnd("Invalid Container") } @_alwaysEmitIntoClient @@ -617,9 +609,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { where P.Element: ~Copyable { try append(addingCount: producer.count, from: &producer) - if try !producer._isAtEnd() { - preconditionFailure("Invalid Container") - } + try producer._expectEnd("Invalid Container") } /// Moves the elements of a given container into the end of this one, leaving @@ -650,9 +640,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { let c = source.distance(from: sourceSubrange.lowerBound, to: sourceSubrange.upperBound) var producer = source.consume(sourceSubrange) self.append(addingCount: c, from: &producer) - if !producer._isAtEnd() { - preconditionFailure("Invalid Container") - } + producer._expectEnd("Invalid Container") } /// Appends the elements of a given container to the end of this one by @@ -689,7 +677,7 @@ where var c = items.count var i = items.startIndex self.replace(removing: subrange, addingCount: c) { target in - let source = items.nextSpan(after: &i, maximumCount: target.freeCapacity) + let source = items.nextSpan(after: &i, maxCount: target.freeCapacity) target._append(copying: source) c -= source.count } @@ -707,7 +695,7 @@ where var it = items.makeIterableIterator_() insert(addingCount: newCount, at: index) { target in while !target.isFull { - let source = it.nextSpan_(maximumCount: target.freeCapacity) + let source = it.nextSpan_(maxCount: target.freeCapacity) precondition(!source.isEmpty, "Broken container: mismatching count") target._append(copying: source) } diff --git a/Sources/ContainersPreview/Protocols/Drain+Map.swift b/Sources/ContainersPreview/Protocols/Drain+Map.swift index 319091b8..4feb9a10 100644 --- a/Sources/ContainersPreview/Protocols/Drain+Map.swift +++ b/Sources/ContainersPreview/Protocols/Drain+Map.swift @@ -73,7 +73,7 @@ where ) throws(Error) -> Bool { var success = false while !target.isFull { - var source = _base.drainNext(maximumCount: target.freeCapacity) + var source = _base.drainNext(maxCount: target.freeCapacity) if source.isEmpty { break } success = true while !source.isEmpty { diff --git a/Sources/ContainersPreview/Protocols/Drain.swift b/Sources/ContainersPreview/Protocols/Drain.swift index 039fa984..948e0b0a 100644 --- a/Sources/ContainersPreview/Protocols/Drain.swift +++ b/Sources/ContainersPreview/Protocols/Drain.swift @@ -26,7 +26,7 @@ public protocol Drain: CountedProducer, ~Copyable, ~Escapable where Element: ~Copyable, Failure == Never { /// Returns the next span of consumable items in the sequence underlying this - /// drain, of at most the specified maximum count. A `maximumCount` of nil + /// drain, of at most the specified maximum count. A `maxCount` of nil /// indicates no limit, meaning that the client is able to process an /// arbitrarily large number of elements. /// @@ -36,7 +36,7 @@ where Element: ~Copyable, Failure == Never /// /// While the returned input spans exist, they continue to mutate the drain, /// extending the exclusive access initiated by the call to - /// `drainNext(maximumCount:)`. To call this (or any other) method again, the + /// `drainNext(maxCount:)`. To call this (or any other) method again, the /// returned input span needs to be consumed or otherwise destroyed. /// /// Once this method returns, the contents of the resulting input span are @@ -47,7 +47,7 @@ where Element: ~Copyable, Failure == Never /// temporary location and later reinserting them into the underlying /// construct through some type-specific operations. /// - /// - Parameter maximumCount: The maximum number of items that the client + /// - Parameter maxCount: The maximum number of items that the client /// is prepared to consume, or nil if the client is able to process an /// arbitrary number of elements. If this is non-nil, then it must be a /// positive integer. @@ -57,7 +57,7 @@ where Element: ~Copyable, Failure == Never /// the end of the sequence. @_lifetime(&self) @_lifetime(self: copy self) - mutating func drainNext(maximumCount: Int) -> InputSpan + mutating func drainNext(maxCount: Int) -> InputSpan // TODO: The primary use case does not need this to throw; do we need to allow that? // Note: making this failable is not entirely straightforward, as there is no // easy way to signal partial success -- conforming implementations @@ -75,7 +75,7 @@ where Element: ~Copyable, Failure == Never // ) throws(E) -> R // // This would allow partial consumption, eliminating the need for - // `maximumCount`, but at the cost of having to deal with closures -- + // `maxCount`, but at the cost of having to deal with closures -- // it can be tricky to elegantly flow data/control in & out higher-order // functions. Allowing the function argument to throw also precludes // the drain itself from throwing, unless they are both required @@ -93,7 +93,7 @@ extension Drain where Self: ~Copyable & ~Escapable, Element: ~Copyable { /// /// While the returned input spans exist, they continue to mutate the drain, /// extending the exclusive access initiated by the call to - /// `drain(maximumCount:)`. To call this (or any other) method again, the + /// `drain(maxCount:)`. To call this (or any other) method again, the /// returned input span needs to be consumed or otherwise destroyed. /// /// Once this method returns, the contents of the resulting input span are @@ -111,7 +111,7 @@ extension Drain where Self: ~Copyable & ~Escapable, Element: ~Copyable { @_lifetime(self: copy self) @_transparent public mutating func drainNext() -> InputSpan { - drainNext(maximumCount: Int.max) + drainNext(maxCount: Int.max) } /// Generate the next batch of items into the supplied output span instance, @@ -165,7 +165,7 @@ extension Drain where Self: ~Copyable & ~Escapable, Element: ~Copyable { public mutating func generate( into target: inout OutputSpan ) throws(Never) -> Bool { - var source = self.drainNext(maximumCount: target.freeCapacity) + var source = self.drainNext(maxCount: target.freeCapacity) if source.isEmpty { return false } target._append(moving: &source) return true @@ -207,7 +207,7 @@ extension Drain where Self: ~Copyable & ~Escapable, Element: ~Copyable { ) -> Bool { // FIXME: Compiler crash when this declares throws(Failure) precondition(n >= 0, "Cannot skip a negative number of elements") guard n > 0 else { return true } - let span = drainNext(maximumCount: n) + let span = drainNext(maxCount: n) let success = span.count > 0 n &-= span.count return success diff --git a/Sources/ContainersPreview/Protocols/Iterable+Algorithms.swift b/Sources/ContainersPreview/Protocols/Iterable+Algorithms.swift index 96b7f807..85330318 100644 --- a/Sources/ContainersPreview/Protocols/Iterable+Algorithms.swift +++ b/Sources/ContainersPreview/Protocols/Iterable+Algorithms.swift @@ -76,12 +76,12 @@ extension Iterable_ if el1.isEmpty { // LHS is empty - sequences are equal iff RHS is also empty - let el2 = try iter2.nextSpan_(maximumCount: 1) + let el2 = try iter2.nextSpan_(maxCount: 1) return el2.isEmpty } while el1.count > 0 { - let el2 = try iter2.nextSpan_(maximumCount: el1.count) + let el2 = try iter2.nextSpan_(maxCount: el1.count) if el2.isEmpty { return false } for i in 0.. Span { + public mutating func nextSpan_(maxCount: Int) -> Span { if _progress { _current[0] = _current[0].advanced(by: 1) } @@ -187,7 +187,7 @@ where Bound: Strideable, Bound.Stride: SignedInteger } @inlinable @_lifetime(&self) - public mutating func nextSpan_(maximumCount: Int) -> Span { + public mutating func nextSpan_(maxCount: Int) -> Span { if _progress { _current[0] = _current[0].advanced(by: 1) } diff --git a/Sources/ContainersPreview/Protocols/Iterable+Utilities.swift b/Sources/ContainersPreview/Protocols/Iterable+Utilities.swift index c6734a32..16fb1c8f 100644 --- a/Sources/ContainersPreview/Protocols/Iterable+Utilities.swift +++ b/Sources/ContainersPreview/Protocols/Iterable+Utilities.swift @@ -26,7 +26,7 @@ extension Iterable_ where Self: ~Copyable & ~Escapable, Element_: Copyable { var target = buffer var it = self.makeIterableIterator_() while target.count != 0 { - let span = try it.nextSpan_(maximumCount: target.count) + let span = try it.nextSpan_(maxCount: target.count) if span.isEmpty { return buffer.count - target.count } diff --git a/Sources/ContainersPreview/Protocols/Producer.swift b/Sources/ContainersPreview/Protocols/Producer.swift index 737f30cb..cbbfc7b6 100644 --- a/Sources/ContainersPreview/Protocols/Producer.swift +++ b/Sources/ContainersPreview/Protocols/Producer.swift @@ -266,15 +266,17 @@ extension Producer where Self: ~Copyable & ~Escapable, Element: ~Copyable { @available(SwiftStdlib 5.0, *) extension Producer where Self: ~Copyable & ~Escapable, Element: ~Copyable { - /// Returns true if the producer has no more elements, consuming it in + /// Triggers a runtime trap if the producer is not at its end, consuming it in /// the process. This is implemented by checking if it is possible to /// skip one item. - /// - /// This is useful in preconditions. @inlinable - public consuming func _isAtEnd() throws(Failure) -> Bool { + public consuming func _expectEnd( + _ message: String = "Invalid Producer" + ) throws(Failure) { var c = 1 - return try !skip(by: &c) + if try !skip(by: &c) { + preconditionFailure(message) + } } } diff --git a/Sources/ContainersPreview/Types/OutputSpan+Extras.swift b/Sources/ContainersPreview/Types/OutputSpan+Helpers.swift similarity index 100% rename from Sources/ContainersPreview/Types/OutputSpan+Extras.swift rename to Sources/ContainersPreview/Types/OutputSpan+Helpers.swift diff --git a/Sources/ContainersPreview/Types/SpanIterator.swift b/Sources/ContainersPreview/Types/SpanIterator.swift index a5513c27..6e59e785 100644 --- a/Sources/ContainersPreview/Types/SpanIterator.swift +++ b/Sources/ContainersPreview/Types/SpanIterator.swift @@ -37,8 +37,8 @@ public struct SpanIterator: BorrowingIteratorProtocol_, ~Copyable, ~Es @_lifetime(&self) @_lifetime(self: copy self) @_transparent - public mutating func nextSpan_(maximumCount: Int) -> Span { - let c = Swift.min(maximumCount, _count) + public mutating func nextSpan_(maxCount: Int) -> Span { + let c = Swift.min(maxCount, _count) defer { _start &+= c _count &-= c diff --git a/Sources/DequeModule/Deque/Deque._UnsafeHandle.swift b/Sources/DequeModule/Deque/Deque._UnsafeHandle.swift index 91916abb..db83bd45 100644 --- a/Sources/DequeModule/Deque/Deque._UnsafeHandle.swift +++ b/Sources/DequeModule/Deque/Deque._UnsafeHandle.swift @@ -359,7 +359,7 @@ extension Deque._UnsafeHandle { @inlinable internal func withUnsafeSegment( startingAt start: Int, - maximumCount: Int?, + maxCount: Int?, _ body: (UnsafeBufferPointer) throws -> R ) rethrows -> (end: Int, result: R) { assert(start <= count) @@ -370,7 +370,7 @@ extension Deque._UnsafeHandle { let segmentStart = self.slot(forOffset: start) let segmentEnd = segmentStart < endSlot ? endSlot : limSlot - let count = Swift.min(maximumCount ?? Int.max, segmentEnd.position - segmentStart.position) + let count = Swift.min(maxCount ?? Int.max, segmentEnd.position - segmentStart.position) let result = try body(UnsafeBufferPointer(start: ptr(at: segmentStart), count: count)) return (start + count, result) } diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Consumption.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Consumption.swift index 5a014007..018f6152 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Consumption.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Consumption.swift @@ -235,14 +235,14 @@ extension RigidDeque.SubrangeConsumer where Element: ~Copyable { @inlinable @_lifetime(&self) @_lifetime(self: copy self) - public mutating func drainNext(maximumCount: Int) -> InputSpan { + public mutating func drainNext(maxCount: Int) -> InputSpan { if _buffer1.isEmpty { if _buffer2.isEmpty { return .init() } swap(&_buffer1, &_buffer2) } - let buffer = _buffer1._trim(first: maximumCount) + let buffer = _buffer1._trim(first: maxCount) return _overrideLifetime( InputSpan(buffer: buffer, initializedCount: buffer.count), mutating: &self) diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift index 3084493b..6f671115 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift @@ -48,8 +48,8 @@ extension RigidDeque where Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(&self) // FIXME: This should be `@_lifetime(copy self)` @_lifetime(self: copy self) - public mutating func nextSpan_(maximumCount: Int) -> Span { - let result = _currentSegment._trim(first: maximumCount) + public mutating func nextSpan_(maxCount: Int) -> Span { + let result = _currentSegment._trim(first: maxCount) if _currentSegment.isEmpty { _currentSegment = _nextSegment _nextSegment = Span() @@ -118,25 +118,25 @@ extension RigidDeque where Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(borrow self) - public func nextSpan(after index: inout Int, maximumCount: Int) -> Span { + public func nextSpan(after index: inout Int, maxCount: Int) -> Span { _checkValidIndex(index) - precondition(maximumCount > 0, "maximumCount must be positive") + precondition(maxCount > 0, "maxCount must be positive") let segment = self._handle .nextSegment(after: index) - ._extracting(first: maximumCount) + ._extracting(first: maxCount) index &+= segment.count return _overrideLifetime(Span(_unsafeElements: segment), borrowing: self) } @_lifetime(&self) public mutating func nextMutableSpan( - after index: inout Int, maximumCount: Int + after index: inout Int, maxCount: Int ) -> MutableSpan { _checkValidIndex(index) - precondition(maximumCount > 0, "maximumCount must be positive") + precondition(maxCount > 0, "maxCount must be positive") let segment = self._handle .nextSegment(after: index) - ._extracting(first: maximumCount) + ._extracting(first: maxCount) index &+= segment.count return _overrideLifetime( MutableSpan(_unsafeElements: .init(mutating: segment)), @@ -145,12 +145,12 @@ extension RigidDeque where Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(borrow self) - public func previousSpan(before index: inout Int, maximumCount: Int) -> Span { + public func previousSpan(before index: inout Int, maxCount: Int) -> Span { _checkValidIndex(index) - precondition(maximumCount > 0, "maximumCount must be positive") + precondition(maxCount > 0, "maxCount must be positive") let segment = self._handle .previousSegment(before: index) - ._extracting(last: maximumCount) + ._extracting(last: maxCount) index &-= segment.count return _overrideLifetime(Span(_unsafeElements: segment), borrowing: self) } diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift index 931cba4d..47c5227a 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift @@ -202,7 +202,7 @@ extension RigidDeque where Element: ~Copyable { /// many items as promised. /// /// - Parameters: - /// - maximumCount: The maximum number of items to prepend to the deque, or + /// - maxCount: The maximum number of items to prepend to the deque, or /// nil to use all available capacity. /// - producer: A producer that generates the items to prepend. /// @@ -317,7 +317,7 @@ extension RigidDeque /*where Element: Copyable*/ { where S.Element_ == Element { var it = items.makeIterableIterator_() try self.prepend(addingCount: exactCount) { (target) throws(S.Failure_) in - let span = try it.nextSpan_(maximumCount: target.freeCapacity) + let span = try it.nextSpan_(maxCount: target.freeCapacity) target._append(copying: span) } } diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift index 9fde6108..ae6bdfc6 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift @@ -316,7 +316,7 @@ extension RigidDeque where Element: ~Copyable { /// - newItemCount: The maximum number of items to insert into the deque. /// - producer: A producer that generates the items to append. /// - /// - Complexity: O(`self.count` + `maximumCount`) + /// - Complexity: O(`self.count` + `maxCount`) @_alwaysEmitIntoClient public mutating func replace< E: Error, diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift index 7922a568..a20f5dc6 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift @@ -87,21 +87,21 @@ extension UniqueDeque where Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(borrow self) - public func nextSpan(after index: inout Int, maximumCount: Int) -> Span { - _storage.nextSpan(after: &index, maximumCount: maximumCount) + public func nextSpan(after index: inout Int, maxCount: Int) -> Span { + _storage.nextSpan(after: &index, maxCount: maxCount) } @_lifetime(&self) public mutating func nextMutableSpan( - after index: inout Int, maximumCount: Int + after index: inout Int, maxCount: Int ) -> MutableSpan { - _storage.nextMutableSpan(after: &index, maximumCount: maximumCount) + _storage.nextMutableSpan(after: &index, maxCount: maxCount) } @_alwaysEmitIntoClient @_lifetime(borrow self) - public func previousSpan(before index: inout Int, maximumCount: Int) -> Span { - _storage.previousSpan(before: &index, maximumCount: maximumCount) + public func previousSpan(before index: inout Int, maxCount: Int) -> Span { + _storage.previousSpan(before: &index, maxCount: maxCount) } } diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift index 274454f7..29f6b209 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift @@ -346,7 +346,7 @@ extension UniqueDeque /*where Element: Copyable*/ { where S.Element_ == Element { var it = items.makeIterableIterator_() try self.prepend(addingCount: exactCount) { (target) throws(S.Failure_) in - let span = try it.nextSpan_(maximumCount: target.freeCapacity) + let span = try it.nextSpan_(maxCount: target.freeCapacity) target._append(copying: span) } } diff --git a/Sources/RopeModule/BigString/Views/BigString+UTF8View.swift b/Sources/RopeModule/BigString/Views/BigString+UTF8View.swift index 6d727b5d..00670bac 100644 --- a/Sources/RopeModule/BigString/Views/BigString+UTF8View.swift +++ b/Sources/RopeModule/BigString/Views/BigString+UTF8View.swift @@ -96,7 +96,7 @@ extension BigString.UTF8View.Iterator: IteratorProtocol { } public mutating func next( - maximumCount: Int, + maximumCount: Int, // FIXME: Should be `maxCount` with body: (UnsafeBufferPointer) -> (consumed: Int, result: R) ) -> R { guard _index < _base.endIndex else { diff --git a/Tests/BasicContainersTests/RigidArrayTests.swift b/Tests/BasicContainersTests/RigidArrayTests.swift index dbfe64a9..b7219bd0 100644 --- a/Tests/BasicContainersTests/RigidArrayTests.swift +++ b/Tests/BasicContainersTests/RigidArrayTests.swift @@ -1508,7 +1508,7 @@ class RigidArrayTests: CollectionTestCase { } var consumer = a.consume(0 ..< 2) - let span = consumer.drainNext(maximumCount: .max) + let span = consumer.drainNext(maxCount: .max) expectEqual(span.count, 2) expectEqual(span[0].payload, 0) diff --git a/Tests/BasicContainersTests/RigidSetTests.swift b/Tests/BasicContainersTests/RigidSetTests.swift index b8536df6..5025ccfd 100644 --- a/Tests/BasicContainersTests/RigidSetTests.swift +++ b/Tests/BasicContainersTests/RigidSetTests.swift @@ -242,7 +242,7 @@ class RigidSetTests: CollectionTestCase { func test_bucketIterator_consistency() { withEvery("capacity", in: [0, 1, 2, 3, 4, 10, 100, 200]) { capacity in - withEvery("maximumCount", in: [1, 2, 3, Int.max]) { maximumCount in + withEvery("maxCount", in: [1, 2, 3, Int.max]) { maxCount in withLifetimeTracking { tracker in var s = RigidSet>(capacity: capacity) withEvery("i", in: 0 ..< capacity) { i in @@ -250,13 +250,13 @@ class RigidSetTests: CollectionTestCase { var it = s._table.makeBucketIterator() var j = s._table.startBucket - while let next = it.nextOccupiedRegion(maximumCount: maximumCount) { + while let next = it.nextOccupiedRegion(maxCount: maxCount) { expectFalse(next.isEmpty, "Empty chunk; j: \(j), next: \(next)") expectLessThanOrEqual( next.upperBound.offset - next.lowerBound.offset, - maximumCount, + maxCount, "Overlong chunk") - if maximumCount == Int.max, j > s._table.startBucket { + if maxCount == Int.max, j > s._table.startBucket { expectGreaterThan( next.lowerBound, j, "Unnecessarily split run of occupied buckets") @@ -294,7 +294,7 @@ class RigidSetTests: CollectionTestCase { #if UnstableContainersPreview func test_borrowing_iterator() { withEvery("capacity", in: [0, 1, 2, 3, 4, 10, 100, 1000]) { capacity in - withEvery("maximumCount", in: [1, 2, 3, Int.max]) { maximumCount in + withEvery("maxCount", in: [1, 2, 3, Int.max]) { maxCount in withLifetimeTracking { tracker in var s = RigidSet>(capacity: capacity) withEvery("i", in: 0 ..< capacity) { i in @@ -303,9 +303,9 @@ class RigidSetTests: CollectionTestCase { var expected = Set(0 ... i) var it = s.makeIterableIterator_() while true { - let next = it.nextSpan_(maximumCount: maximumCount) + let next = it.nextSpan_(maxCount: maxCount) guard !next.isEmpty else { break } - expectLessThanOrEqual(next.count, maximumCount) + expectLessThanOrEqual(next.count, maxCount) for j in next.indices { let v = next[j].payload expectEqual(expected.remove(v), v, "Unexpected item \(v)") @@ -426,7 +426,7 @@ class RigidSetTests: CollectionTestCase { } } - func test_insert_drain_maximumCount() { + func test_insert_drain_maxCount() { withEvery("capacity", in: [5, 10, 100]) { capacity in withEvery("drainLength", in: [0, 1, 2, 4, 10, capacity]) { drainLength in withEvery("maxCount", in: [0, 1, 2, 3, 5]) { maxCount in @@ -440,7 +440,7 @@ class RigidSetTests: CollectionTestCase { ) { i in tracker.instance(for: i) } - s.insert(maximumCount: maxCount, from: &drain) + s.insert(addingCount: maxCount, from: &drain) expectConsistentSet(s) let expectedCount = Swift.min(maxCount, drainLength) diff --git a/Tests/ContainersTests/BorrowingSequenceTests.swift b/Tests/ContainersTests/BorrowingSequenceTests.swift index 220ed1cd..7b49da9c 100644 --- a/Tests/ContainersTests/BorrowingSequenceTests.swift +++ b/Tests/ContainersTests/BorrowingSequenceTests.swift @@ -69,7 +69,7 @@ extension Iterable_ where Self: ~Copyable & ~Escapable, Element_: Copyable { var borrowIterator = makeIterableIterator_() var result: [Element_] = [] while true { - let span = try borrowIterator.nextSpan_(maximumCount: .max) + let span = try borrowIterator.nextSpan_(maxCount: .max) if span.isEmpty { break } for i in span.indices { result.append(span[i]) diff --git a/Tests/DequeTests/RigidDequeCrashTests.swift b/Tests/DequeTests/RigidDequeCrashTests.swift index 238869b1..95615425 100644 --- a/Tests/DequeTests/RigidDequeCrashTests.swift +++ b/Tests/DequeTests/RigidDequeCrashTests.swift @@ -85,26 +85,26 @@ struct RigidDequeCrashTests { await #expect(processExitsWith: .failure) { var deque = RigidDeque(copying: [1, 2, 3]) var index = -1 - _ = deque.nextMutableSpan(after: &index, maximumCount: 1) + _ = deque.nextMutableSpan(after: &index, maxCount: 1) } await #expect(processExitsWith: .failure) { var deque = RigidDeque(copying: [1, 2, 3]) var index = 4 // valid range is 0...3 (count == 3) - _ = deque.nextMutableSpan(after: &index, maximumCount: 1) + _ = deque.nextMutableSpan(after: &index, maxCount: 1) } } - @Test("nextMutableSpan with non-positive maximumCount traps") + @Test("nextMutableSpan with non-positive maxCount traps") func nextMutableSpanNonPositiveMaximumCount() async { await #expect(processExitsWith: .failure) { var deque = RigidDeque(copying: [1, 2, 3]) var index = 0 - _ = deque.nextMutableSpan(after: &index, maximumCount: 0) + _ = deque.nextMutableSpan(after: &index, maxCount: 0) } await #expect(processExitsWith: .failure) { var deque = RigidDeque(copying: [1, 2, 3]) var index = 0 - _ = deque.nextMutableSpan(after: &index, maximumCount: -1) + _ = deque.nextMutableSpan(after: &index, maxCount: -1) } } } diff --git a/Tests/DequeTests/RigidDequeTests.swift b/Tests/DequeTests/RigidDequeTests.swift index 3e533725..b558f4c7 100644 --- a/Tests/DequeTests/RigidDequeTests.swift +++ b/Tests/DequeTests/RigidDequeTests.swift @@ -1573,15 +1573,15 @@ final class RigidDequeTests: CollectionTestCase { func test_nextMutableSpan() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in - withEvery("maximumCount", in: [1, 2, 3, 5, 100]) { maximumCount in + withEvery("maxCount", in: [1, 2, 3, 5, 100]) { maxCount in var deque = RigidDeque(layout: layout, contents: layout.valueRange) var index = deque.startIndex var totalSeen = 0 while index < deque.endIndex { let oldIndex = index - var span = deque.nextMutableSpan(after: &index, maximumCount: maximumCount) + var span = deque.nextMutableSpan(after: &index, maxCount: maxCount) expectGreaterThan(span.count, 0) - expectLessThanOrEqual(span.count, maximumCount) + expectLessThanOrEqual(span.count, maxCount) expectEqual(index, oldIndex + span.count) // Overwrite each element with its logical position in the deque. for i in 0 ..< span.count { diff --git a/Tests/_CollectionsTestSupport/AssertionContexts/Assertions+Containers.swift b/Tests/_CollectionsTestSupport/AssertionContexts/Assertions+Containers.swift index e21df0db..ca9c9a18 100644 --- a/Tests/_CollectionsTestSupport/AssertionContexts/Assertions+Containers.swift +++ b/Tests/_CollectionsTestSupport/AssertionContexts/Assertions+Containers.swift @@ -142,7 +142,7 @@ public func expectIterablePayloads< var it2 = right.makeIterator() var i = 0 while true { - let next1 = try it1.nextSpan_(maximumCount: 1) + let next1 = try it1.nextSpan_(maxCount: 1) let next2 = it2.next() switch (next1.isEmpty, next2) { case (true, nil): @@ -190,7 +190,7 @@ public func expectIterablePayloads< var it2 = right.makeIterator() var i = 0 while true { - let next1 = try it1.nextSpan_(maximumCount: 1) + let next1 = try it1.nextSpan_(maxCount: 1) let next2 = it2.next() switch (next1.isEmpty, next2) { case (true, nil): diff --git a/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift b/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift index 83b44c76..04b040ea 100644 --- a/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift +++ b/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift @@ -102,7 +102,7 @@ public func checkIterable< var pos = 0 var it = iterable.makeIterableIterator_() while true { - let span = try it.nextSpan_(maximumCount: 1) + let span = try it.nextSpan_(maxCount: 1) if span.isEmpty { break } expectEqual(span.count, 1) for i in 0 ..< span.count { @@ -119,7 +119,7 @@ public func checkIterable< var it = iterable.makeIterableIterator_() var spanIndex = 0 while true { - let span = try it.nextSpan_(maximumCount: Int.max) + let span = try it.nextSpan_(maxCount: Int.max) if span.isEmpty { break } expectEqual( span.count, spanShapes[spanIndex].count, diff --git a/Tests/_CollectionsTestSupport/MinimalTypes/CustomDrain.swift b/Tests/_CollectionsTestSupport/MinimalTypes/CustomDrain.swift index 7eb616ed..113db813 100644 --- a/Tests/_CollectionsTestSupport/MinimalTypes/CustomDrain.swift +++ b/Tests/_CollectionsTestSupport/MinimalTypes/CustomDrain.swift @@ -47,12 +47,12 @@ package struct CustomDrain: ~Copyable { @available(SwiftStdlib 5.0, *) extension CustomDrain: Drain where Element: ~Copyable { @_lifetime(&self) - package mutating func drainNext(maximumCount: Int) -> InputSpan { + package mutating func drainNext(maxCount: Int) -> InputSpan { assert(_buffer.isEmpty) if _remainder == 0 { _remainder = _chunkSize } - let c = Swift.min(maximumCount, _remainder) + let c = Swift.min(maxCount, _remainder) _remainder -= c for _ in 0 ..< c { guard _position < count else { break } diff --git a/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift b/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift index 9591b8a0..ac83ee40 100644 --- a/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift +++ b/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift @@ -58,9 +58,9 @@ package struct _StaccatoParameters { internal func endOffset( fromOffset startOffset: Int, - maximumCount: Int + maxCount: Int ) -> Int { - precondition(maximumCount > 0) + precondition(maxCount > 0) precondition(startOffset >= 0 && startOffset <= _count) var cycleOffset = startOffset % _modulus var i = 0 @@ -71,7 +71,7 @@ package struct _StaccatoParameters { i += 1 } let c = _spanCounts[i] - return Swift.min(_count, startOffset + Swift.min(c - cycleOffset, maximumCount)) + return Swift.min(_count, startOffset + Swift.min(c - cycleOffset, maxCount)) } } @@ -91,8 +91,8 @@ public struct _StaccatoBorrowingIterator: BorrowingIteratorP } @_lifetime(&self) // FIXME: Should be `@_lifetime(copy self)` - public mutating func nextSpan_(maximumCount: Int) -> Span { - let endOffset = _params.endOffset(fromOffset: _offset, maximumCount: maximumCount) + public mutating func nextSpan_(maxCount: Int) -> Span { + let endOffset = _params.endOffset(fromOffset: _offset, maxCount: maxCount) let startOffset = _offset _offset = endOffset return _contents.extracting(startOffset ..< endOffset) @@ -183,11 +183,11 @@ extension StaccatoContainer: Container where Element: ~Copyable { @_lifetime(borrow self) public func nextSpan( - after index: inout Index, maximumCount: Int + after index: inout Index, maxCount: Int ) -> Span { precondition(_isValid(index)) let startOffset = index._offset - let endOffset = _params.endOffset(fromOffset: index._offset, maximumCount: maximumCount) + let endOffset = _params.endOffset(fromOffset: index._offset, maxCount: maxCount) index._offset = endOffset return _contents.span.extracting(startOffset ..< endOffset) } diff --git a/Xcode/Collections.xcodeproj/project.pbxproj b/Xcode/Collections.xcodeproj/project.pbxproj index 89720ff8..ffc840f3 100644 --- a/Xcode/Collections.xcodeproj/project.pbxproj +++ b/Xcode/Collections.xcodeproj/project.pbxproj @@ -7,7 +7,9 @@ objects = { /* Begin PBXBuildFile section */ - 7D12E33D2FF5CC2A003050AB /* OutputSpan+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D12E33C2FF5CC2A003050AB /* OutputSpan+Extras.swift */; }; + 7D12E33D2FF5CC2A003050AB /* OutputSpan+Helpers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D12E33C2FF5CC2A003050AB /* OutputSpan+Helpers.swift */; }; + 7D12E33F2FF5DAE4003050AB /* _HTable+Deprecated.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D12E33E2FF5DADE003050AB /* _HTable+Deprecated.swift */; }; + 7D12E3412FF5DD0B003050AB /* RigidSet+Deprecated.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D12E3402FF5DD07003050AB /* RigidSet+Deprecated.swift */; }; 7D24E3ED2FAD4C37005A55EB /* RigidArray+Formatter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D24E3EC2FAD4C37005A55EB /* RigidArray+Formatter.swift */; }; 7D2A77262F27F1D1005780C7 /* Span+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77252F27F1D1005780C7 /* Span+Extras.swift */; }; 7D2A77392F27F1E4005780C7 /* UniqueBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77332F27F1E4005780C7 /* UniqueBox.swift */; }; @@ -154,6 +156,7 @@ 7D77E6122FCF810E003FA63B /* CountedProducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D77E6112FCF810E003FA63B /* CountedProducer.swift */; }; 7D77E6252FD0F880003FA63B /* UnsafePointer+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D77E6242FD0F87B003FA63B /* UnsafePointer+Extras.swift */; }; 7D77E6272FD0F94B003FA63B /* UnsafeMutablePointer+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D77E6262FD0F940003FA63B /* UnsafeMutablePointer+Extras.swift */; }; + 7D945E6B2FF5E0D1001041A6 /* UniqueSet+Deprecations.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D945E6A2FF5E0CB001041A6 /* UniqueSet+Deprecations.swift */; }; 7D9748D42E9748930098631A /* BigString+Chunk+UTF16.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9748D32E9748930098631A /* BigString+Chunk+UTF16.swift */; }; 7D9748D52E9748930098631A /* BigString+Chunk+UnicodeScalar.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9748D12E9748930098631A /* BigString+Chunk+UnicodeScalar.swift */; }; 7D9748D62E9748930098631A /* BigString+Chunk+Character.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9748CF2E9748930098631A /* BigString+Chunk+Character.swift */; }; @@ -616,7 +619,9 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ - 7D12E33C2FF5CC2A003050AB /* OutputSpan+Extras.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "OutputSpan+Extras.swift"; sourceTree = ""; }; + 7D12E33C2FF5CC2A003050AB /* OutputSpan+Helpers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "OutputSpan+Helpers.swift"; sourceTree = ""; }; + 7D12E33E2FF5DADE003050AB /* _HTable+Deprecated.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "_HTable+Deprecated.swift"; sourceTree = ""; }; + 7D12E3402FF5DD07003050AB /* RigidSet+Deprecated.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidSet+Deprecated.swift"; sourceTree = ""; }; 7D24E3EC2FAD4C37005A55EB /* RigidArray+Formatter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidArray+Formatter.swift"; sourceTree = ""; }; 7D24E9862FAD53E1005A55EB /* RigidArray_Fixture.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RigidArray_Fixture.swift; sourceTree = ""; }; 7D24E9882FAD53E1005A55EB /* Package.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Package.swift; sourceTree = ""; }; @@ -777,6 +782,7 @@ 7D77E6112FCF810E003FA63B /* CountedProducer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CountedProducer.swift; sourceTree = ""; }; 7D77E6242FD0F87B003FA63B /* UnsafePointer+Extras.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UnsafePointer+Extras.swift"; sourceTree = ""; }; 7D77E6262FD0F940003FA63B /* UnsafeMutablePointer+Extras.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UnsafeMutablePointer+Extras.swift"; sourceTree = ""; }; + 7D945E6A2FF5E0CB001041A6 /* UniqueSet+Deprecations.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueSet+Deprecations.swift"; sourceTree = ""; }; 7D9748CF2E9748930098631A /* BigString+Chunk+Character.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BigString+Chunk+Character.swift"; sourceTree = ""; }; 7D9748D02E9748930098631A /* BigString+Chunk+Index.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BigString+Chunk+Index.swift"; sourceTree = ""; }; 7D9748D12E9748930098631A /* BigString+Chunk+UnicodeScalar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BigString+Chunk+UnicodeScalar.swift"; sourceTree = ""; }; @@ -1354,7 +1360,7 @@ children = ( 7D2A77332F27F1E4005780C7 /* UniqueBox.swift */, 7DC037C82FE3792300CF0CB8 /* MutableRef.swift */, - 7D12E33C2FF5CC2A003050AB /* OutputSpan+Extras.swift */, + 7D12E33C2FF5CC2A003050AB /* OutputSpan+Helpers.swift */, 7D2A77352F27F1E4005780C7 /* InputSpan.swift */, 7D2A77362F27F1E4005780C7 /* Shared.swift */, 7DACFA112F75FBF100291F2E /* SpanIterator.swift */, @@ -1432,6 +1438,7 @@ 7D479CCC2F46D23400A8CB59 /* UniqueSet+BorrowingSequence.swift */, 7D479CC42F46D20400A8CB59 /* UniqueSet+Consumption.swift */, 7D479CBA2F46A71500A8CB59 /* UniqueSet+Debugging.swift */, + 7D945E6A2FF5E0CB001041A6 /* UniqueSet+Deprecations.swift */, 7DEB31532F4E75AF00F9AF28 /* UniqueSet+Equatable.swift */, 7DEB31552F4E75B800F9AF28 /* UniqueSet+Hashable.swift */, 7DEB31652F52268100F9AF28 /* UniqueSet+Index.swift */, @@ -1525,6 +1532,7 @@ 7D72467C2F3D9DDB00112FD0 /* _HTable+Bucket.swift */, 7D479CE62F47D88000A8CB59 /* _HTable+Consumption.swift */, 7D9B75762F3E65DB0048157E /* _HTable+Debug.swift */, + 7D12E33E2FF5DADE003050AB /* _HTable+Deprecated.swift */, 7D72467E2F3D9DDB00112FD0 /* _HTable+Find.swift */, 7D72467F2F3D9DDB00112FD0 /* _HTable+Insert.swift */, 7D7246802F3D9DDB00112FD0 /* _HTable+Iteration.swift */, @@ -1562,6 +1570,7 @@ 7D479CAF2F450E3F00A8CB59 /* RigidSet+BorrowingSequence.swift */, 7D479CC02F46D14800A8CB59 /* RigidSet+Consumption.swift */, 7D479CB82F46A6D700A8CB59 /* RigidSet+Debugging.swift */, + 7D12E3402FF5DD07003050AB /* RigidSet+Deprecated.swift */, 7D479CFE2F4E487700A8CB59 /* RigidSet+Equatable.swift */, 7DEB31512F4E720500F9AF28 /* RigidSet+Hashable.swift */, 7DEB31632F5218A600F9AF28 /* RigidSet+Index.swift */, @@ -2714,9 +2723,10 @@ 7D2A77952F27F2BF005780C7 /* Deque+Codable.swift in Sources */, 7D2A77962F27F2BF005780C7 /* RigidDeque+Experimental.swift in Sources */, 7D2A77972F27F2BF005780C7 /* Deque+Testing.swift in Sources */, - 7D12E33D2FF5CC2A003050AB /* OutputSpan+Extras.swift in Sources */, + 7D12E33D2FF5CC2A003050AB /* OutputSpan+Helpers.swift in Sources */, 7D2A77982F27F2BF005780C7 /* RigidDeque+Replacements.swift in Sources */, 7D7246872F3D9DDB00112FD0 /* _HTable+Iteration.swift in Sources */, + 7D945E6B2FF5E0D1001041A6 /* UniqueSet+Deprecations.swift in Sources */, 7D7246882F3D9DDB00112FD0 /* RigidDictionary.swift in Sources */, 7D7246892F3D9DDB00112FD0 /* _HTable+Find.swift in Sources */, 7D72468A2F3D9DDB00112FD0 /* _HTable.swift in Sources */, @@ -2901,6 +2911,7 @@ 7DAD899E2E8B09C300DD5786 /* UInt+first and last set bit.swift in Sources */, 7DAD899F2E8B09C300DD5786 /* UInt+reversed.swift in Sources */, 7DAD89A02E8B09C300DD5786 /* FixedWidthInteger+roundUpToPowerOfTwo.swift in Sources */, + 7D12E3412FF5DD0B003050AB /* RigidSet+Deprecated.swift in Sources */, 7DAD89A12E8B09C300DD5786 /* Integer rank.swift in Sources */, 7DE9207429CA70F4004483EB /* BigString+ReplaceSubrange.swift in Sources */, 7DE920DC29CA70F4004483EB /* BitSet+Invariants.swift in Sources */, @@ -2996,6 +3007,7 @@ 7DE9215529CA70F4004483EB /* _RawHashNode+UnsafeHandle.swift in Sources */, 7D2A77392F27F1E4005780C7 /* UniqueBox.swift in Sources */, 7D2A773A2F27F1E4005780C7 /* Drain.swift in Sources */, + 7D12E33F2FF5DAE4003050AB /* _HTable+Deprecated.swift in Sources */, 7D479CC32F46D19600A8CB59 /* RigidSet+Resizing.swift in Sources */, 7D57A2D02F353946002543BD /* RigidArray+Deprecated.swift in Sources */, 7D2A77432F27F1E4005780C7 /* Shared.swift in Sources */, From c54ce4c368a50863b0d9f69cd9f658566834ee03 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 1 Jul 2026 17:46:47 -0700 Subject: [PATCH 21/50] Make sure UnstableHashedContainers builds without UnstableContainersPreview --- .../BasicContainers/RigidSet/RigidSet+Deprecated.swift | 4 ++++ .../BasicContainers/RigidSet/RigidSet+Equatable.swift | 10 +++++++++- Tests/BasicContainersTests/RigidDictionaryTests.swift | 2 ++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/Sources/BasicContainers/RigidSet/RigidSet+Deprecated.swift b/Sources/BasicContainers/RigidSet/RigidSet+Deprecated.swift index 9e118d5c..e328f5e0 100644 --- a/Sources/BasicContainers/RigidSet/RigidSet+Deprecated.swift +++ b/Sources/BasicContainers/RigidSet/RigidSet+Deprecated.swift @@ -25,6 +25,7 @@ extension RigidSet where Element: ~Copyable { try self.insert(addingCount: maximumCount, initializingWith: initializer) } + #if UnstableContainersPreview @available(*, deprecated, renamed: "insert(addingCount:from:)") @_alwaysEmitIntoClient public mutating func insert< @@ -38,7 +39,9 @@ extension RigidSet where Element: ~Copyable { { try self.insert(addingCount: maximumCount, from: &producer) } + #endif +#if UnstableContainersPreview @available(*, deprecated, renamed: "insert(addingCount:from:)") @_alwaysEmitIntoClient public mutating func insert< @@ -57,6 +60,7 @@ extension RigidSet where Element: ~Copyable { } } } + #endif } #endif diff --git a/Sources/BasicContainers/RigidSet/RigidSet+Equatable.swift b/Sources/BasicContainers/RigidSet/RigidSet+Equatable.swift index c23b84bf..0a3f4a69 100644 --- a/Sources/BasicContainers/RigidSet/RigidSet+Equatable.swift +++ b/Sources/BasicContainers/RigidSet/RigidSet+Equatable.swift @@ -38,7 +38,8 @@ extension RigidSet where Element: ~Copyable { if left.isTriviallyIdentical(to: right) { return true } guard left.count == right.count else { return false } - + + #if UnstableContainersPreview var lit = left.makeIterableIterator_() while true { let l = lit.nextSpan_() @@ -49,6 +50,13 @@ extension RigidSet where Element: ~Copyable { i &+= 1 } } + #else + var i = left.startIndex + while i != left.endIndex { + guard right.contains(left[i]) else { return false } + i = left.index(after: i) + } + #endif return true } } diff --git a/Tests/BasicContainersTests/RigidDictionaryTests.swift b/Tests/BasicContainersTests/RigidDictionaryTests.swift index eee55a12..f85d2e6d 100644 --- a/Tests/BasicContainersTests/RigidDictionaryTests.swift +++ b/Tests/BasicContainersTests/RigidDictionaryTests.swift @@ -307,6 +307,7 @@ class RigidDictionaryTests: CollectionTestCase { } } + #if UnstableContainersPreview @available(SwiftStdlib 6.4, *) func test_iteration_indices() { typealias Key = LifetimeTracked @@ -342,6 +343,7 @@ class RigidDictionaryTests: CollectionTestCase { } } } + #endif func test_updateValue_with_remove() { typealias Key = LifetimeTracked From d0b4c4c21544ac5d5761fd8a81ca8cd4f8ccfa29 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 1 Jul 2026 17:49:44 -0700 Subject: [PATCH 22/50] =?UTF-8?q?IterableIterator=5F=20=E2=86=92=20Borrowi?= =?UTF-8?q?ngIterator=5F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../RigidArray/RigidArray+Container.swift | 4 +-- .../RigidArray/RigidArray+Replacements.swift | 2 +- .../RigidDictionary+Indices.swift | 8 ++--- .../RigidSet/RigidSet+BorrowingSequence.swift | 6 ++-- .../RigidSet/RigidSet+Equatable.swift | 2 +- .../RigidSet/RigidSet+Hashable.swift | 2 +- .../RigidSet/RigidSet+Insertions.swift | 2 +- .../UniqueArray/UniqueArray+Append.swift | 2 +- .../UniqueArray/UniqueArray+Container.swift | 6 ++-- .../UniqueSet+BorrowingSequence.swift | 6 ++-- .../UniqueSet/UniqueSet+Insertions.swift | 2 +- ...rowingIteratorProtocol+ElementsEqual.swift | 8 ++--- .../Container/ContainerIterator.swift | 4 +-- .../Container/RangeReplaceableContainer.swift | 4 +-- .../Protocols/Iterable+Algorithms.swift | 12 +++---- .../Iterable+Standard Conformances.swift | 36 +++++++++---------- .../Protocols/Iterable+Utilities.swift | 2 +- .../Protocols/Iterable.swift | 6 ++-- .../RigidDeque/RigidDeque+Append.swift | 2 +- .../RigidDeque/RigidDeque+Container.swift | 2 +- .../RigidDeque/RigidDeque+Insertions.swift | 2 +- .../RigidDeque/RigidDeque+Prepend.swift | 2 +- .../RigidDeque/RigidDeque+Replacements.swift | 2 +- .../UniqueDeque/UniqueDeque+Append.swift | 2 +- .../UniqueDeque/UniqueDeque+Container.swift | 2 +- .../UniqueDeque/UniqueDeque+Insertions.swift | 2 +- .../UniqueDeque/UniqueDeque+Prepend.swift | 2 +- .../UniqueDeque+Replacements.swift | 2 +- .../RigidArrayTests.swift | 4 +-- .../RigidDictionaryTests.swift | 4 +-- .../BasicContainersTests/RigidSetTests.swift | 2 +- .../UniqueDictionaryTests.swift | 4 +-- .../BorrowingSequenceTests.swift | 2 +- .../Assertions+Containers.swift | 8 ++--- .../ConformanceCheckers/CheckContainer.swift | 8 ++--- .../MinimalTypes/StaccatoContainer.swift | 6 ++-- 36 files changed, 86 insertions(+), 86 deletions(-) diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Container.swift b/Sources/BasicContainers/RigidArray/RigidArray+Container.swift index 8b825fe2..ab074f8e 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Container.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Container.swift @@ -21,10 +21,10 @@ import ContainersPreview #if compiler(>=6.4) && UnstableContainersPreview @available(SwiftStdlib 5.0, *) extension RigidArray: Iterable_ where Element: ~Copyable { - public typealias IterableIterator_ = SpanIterator + public typealias BorrowingIterator_ = SpanIterator @_alwaysEmitIntoClient @inline(__always) - public func makeIterableIterator_() -> IterableIterator_ { + public func makeBorrowingIterator_() -> BorrowingIterator_ { SpanIterator(self.span) } } diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Replacements.swift b/Sources/BasicContainers/RigidArray/RigidArray+Replacements.swift index 99085eec..ba99611c 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Replacements.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Replacements.swift @@ -591,7 +591,7 @@ extension RigidArray { copyingContainer items: borrowing C, newCount: Int ) { - var it = items.makeIterableIterator_() + var it = items.makeBorrowingIterator_() self.replace(removing: subrange, addingCount: newCount) { target in while !target.isFull { let source = it.nextSpan_(maxCount: target.freeCapacity) diff --git a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Indices.swift b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Indices.swift index c8e933cf..de7e2951 100644 --- a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Indices.swift +++ b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Indices.swift @@ -50,7 +50,7 @@ where Key: ~Copyable, Value: ~Copyable public typealias Element_ = Element @frozen - public struct IterableIterator_: ~Escapable { + public struct BorrowingIterator_: ~Escapable { public typealias Element = RigidDictionary.Index @usableFromInline @@ -73,16 +73,16 @@ where Key: ~Copyable, Value: ~Copyable public var underestimatedCount_: Int { self._base.value.count } @_lifetime(borrow self) // FIXME: Should be @_lifetime(copy self) - public func makeIterableIterator_() -> IterableIterator_ { + public func makeBorrowingIterator_() -> BorrowingIterator_ { let bit = self._base.value.makeBucketIterator() // FIXME: This override really should not be necessary. Check if the real `struct Borrow` fixes it. let override = _overrideLifetime(bit, copying: self) - return IterableIterator_(_it: override) + return BorrowingIterator_(_it: override) } } @available(SwiftStdlib 6.4, *) -extension RigidDictionary.Indices.IterableIterator_: BorrowingIteratorProtocol_ +extension RigidDictionary.Indices.BorrowingIterator_: BorrowingIteratorProtocol_ where Key: ~Copyable, Value: ~Copyable { public typealias Element_ = Element diff --git a/Sources/BasicContainers/RigidSet/RigidSet+BorrowingSequence.swift b/Sources/BasicContainers/RigidSet/RigidSet+BorrowingSequence.swift index 14884934..a62eb9bb 100644 --- a/Sources/BasicContainers/RigidSet/RigidSet+BorrowingSequence.swift +++ b/Sources/BasicContainers/RigidSet/RigidSet+BorrowingSequence.swift @@ -33,12 +33,12 @@ extension RigidSet: Iterable_ where Element: ~Copyable { @inlinable @_lifetime(borrow self) - public borrowing func makeIterableIterator_() -> IterableIterator_ { - IterableIterator_(_set: self) + public borrowing func makeBorrowingIterator_() -> BorrowingIterator_ { + BorrowingIterator_(_set: self) } @frozen - public struct IterableIterator_: + public struct BorrowingIterator_: BorrowingIteratorProtocol_, ~Copyable, ~Escapable diff --git a/Sources/BasicContainers/RigidSet/RigidSet+Equatable.swift b/Sources/BasicContainers/RigidSet/RigidSet+Equatable.swift index 0a3f4a69..5deb0e5a 100644 --- a/Sources/BasicContainers/RigidSet/RigidSet+Equatable.swift +++ b/Sources/BasicContainers/RigidSet/RigidSet+Equatable.swift @@ -40,7 +40,7 @@ extension RigidSet where Element: ~Copyable { guard left.count == right.count else { return false } #if UnstableContainersPreview - var lit = left.makeIterableIterator_() + var lit = left.makeBorrowingIterator_() while true { let l = lit.nextSpan_() if l.isEmpty { break } diff --git a/Sources/BasicContainers/RigidSet/RigidSet+Hashable.swift b/Sources/BasicContainers/RigidSet/RigidSet+Hashable.swift index f711eb3a..058032a7 100644 --- a/Sources/BasicContainers/RigidSet/RigidSet+Hashable.swift +++ b/Sources/BasicContainers/RigidSet/RigidSet+Hashable.swift @@ -37,7 +37,7 @@ extension RigidSet where Element: ~Copyable { public func _rawHashValue(seed: Int) -> Int { #if UnstableContainersPreview var hash = 0 - var it = self.makeIterableIterator_() + var it = self.makeBorrowingIterator_() while true { let next = it.nextSpan_() var i = 0 diff --git a/Sources/BasicContainers/RigidSet/RigidSet+Insertions.swift b/Sources/BasicContainers/RigidSet/RigidSet+Insertions.swift index b103301c..0f64bdc7 100644 --- a/Sources/BasicContainers/RigidSet/RigidSet+Insertions.swift +++ b/Sources/BasicContainers/RigidSet/RigidSet+Insertions.swift @@ -242,7 +242,7 @@ extension RigidSet /* where Element: Copyable */ { copying items: borrowing S ) throws(S.Failure_) where S.Element_ == Element { - var it = items.makeIterableIterator_() + var it = items.makeBorrowingIterator_() while true { let span = try it.nextSpan_() guard !span.isEmpty else { break } diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Append.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Append.swift index bb48b11f..b80ed3bc 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Append.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Append.swift @@ -266,7 +266,7 @@ extension UniqueArray { ) throws(Source.Failure_) where Source.Element_ == Element { _ensureFreeCapacity(newElements.underestimatedCount_) - var it = newElements.makeIterableIterator_() + var it = newElements.makeBorrowingIterator_() while true { let span = try it.nextSpan_() if span.isEmpty { break } diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift index 39ca060c..2b5e4e87 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift @@ -21,15 +21,15 @@ import ContainersPreview #if compiler(>=6.4) && UnstableContainersPreview @available(SwiftStdlib 5.0, *) extension UniqueArray: Iterable_ where Element: ~Copyable { - public typealias IterableIterator_ = RigidArray.IterableIterator_ + public typealias BorrowingIterator_ = RigidArray.BorrowingIterator_ @inlinable public var underestimatedCount_: Int { count } @_alwaysEmitIntoClient @inline(__always) - public func makeIterableIterator_() -> IterableIterator_ { - self._storage.makeIterableIterator_() + public func makeBorrowingIterator_() -> BorrowingIterator_ { + self._storage.makeBorrowingIterator_() } } #endif diff --git a/Sources/BasicContainers/UniqueSet/UniqueSet+BorrowingSequence.swift b/Sources/BasicContainers/UniqueSet/UniqueSet+BorrowingSequence.swift index 549c415e..9cc21b7a 100644 --- a/Sources/BasicContainers/UniqueSet/UniqueSet+BorrowingSequence.swift +++ b/Sources/BasicContainers/UniqueSet/UniqueSet+BorrowingSequence.swift @@ -21,7 +21,7 @@ import ContainersPreview @available(SwiftStdlib 5.0, *) extension UniqueSet: Iterable_ where Element: ~Copyable { public typealias Element_ = Element - public typealias IterableIterator_ = RigidSet.IterableIterator_ + public typealias BorrowingIterator_ = RigidSet.BorrowingIterator_ @inlinable public var underestimatedCount_: Int { count } @@ -35,8 +35,8 @@ extension UniqueSet: Iterable_ where Element: ~Copyable { @inlinable @_lifetime(borrow self) - public borrowing func makeIterableIterator_() -> IterableIterator_ { - IterableIterator_(_set: _storage) + public borrowing func makeBorrowingIterator_() -> BorrowingIterator_ { + BorrowingIterator_(_set: _storage) } } #endif diff --git a/Sources/BasicContainers/UniqueSet/UniqueSet+Insertions.swift b/Sources/BasicContainers/UniqueSet/UniqueSet+Insertions.swift index 162de94b..6686459b 100644 --- a/Sources/BasicContainers/UniqueSet/UniqueSet+Insertions.swift +++ b/Sources/BasicContainers/UniqueSet/UniqueSet+Insertions.swift @@ -139,7 +139,7 @@ extension UniqueSet /* where Element: Copyable */ { ) throws(S.Failure_) where S.Element_ == Element { _ensureFreeCapacity(items.underestimatedCount_) - var it = items.makeIterableIterator_() + var it = items.makeBorrowingIterator_() while true { let span = try it.nextSpan_() guard !span.isEmpty else { break } diff --git a/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+ElementsEqual.swift b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+ElementsEqual.swift index fd321645..c947c90a 100644 --- a/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+ElementsEqual.swift +++ b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+ElementsEqual.swift @@ -31,8 +31,8 @@ where ) throws(Failure_) -> Bool where Other.Element_: ~Copyable { - let it1 = self.makeIterableIterator_() - let it2 = other.makeIterableIterator_() + let it1 = self.makeBorrowingIterator_() + let it2 = other.makeBorrowingIterator_() return try it1.elementsEqual(it2) } } @@ -73,8 +73,8 @@ where ) throws(Failure_) -> Bool where Other.Element_: ~Copyable, Other.Failure_ == Failure_ { - let it1 = self.makeIterableIterator_() - let it2 = other.makeIterableIterator_() + let it1 = self.makeBorrowingIterator_() + let it2 = other.makeBorrowingIterator_() return try it1.elementsEqual(it2, by: areEquivalent) } } diff --git a/Sources/ContainersPreview/Protocols/Container/ContainerIterator.swift b/Sources/ContainersPreview/Protocols/Container/ContainerIterator.swift index bc0bc204..1e296def 100644 --- a/Sources/ContainersPreview/Protocols/Container/ContainerIterator.swift +++ b/Sources/ContainersPreview/Protocols/Container/ContainerIterator.swift @@ -18,11 +18,11 @@ extension Container where Self: ~Copyable /*FIXME: & ~Escapable*/, Element: ~Copyable, - IterableIterator_ == ContainerIterator + BorrowingIterator_ == ContainerIterator { @_alwaysEmitIntoClient @_lifetime(borrow self) - public func makeIterableIterator_() -> IterableIterator_ { + public func makeBorrowingIterator_() -> BorrowingIterator_ { ContainerIterator(_borrowing: self, from: self.startIndex) } } diff --git a/Sources/ContainersPreview/Protocols/Container/RangeReplaceableContainer.swift b/Sources/ContainersPreview/Protocols/Container/RangeReplaceableContainer.swift index c58d1aea..3b93a057 100644 --- a/Sources/ContainersPreview/Protocols/Container/RangeReplaceableContainer.swift +++ b/Sources/ContainersPreview/Protocols/Container/RangeReplaceableContainer.swift @@ -692,7 +692,7 @@ where copying items: borrowing C, at index: Index ) { - var it = items.makeIterableIterator_() + var it = items.makeBorrowingIterator_() insert(addingCount: newCount, at: index) { target in while !target.isFull { let source = it.nextSpan_(maxCount: target.freeCapacity) @@ -818,7 +818,7 @@ where copying items: borrowing S ) throws(S.Failure_) where S.Element_ == Element { - var it = items.makeIterableIterator_() + var it = items.makeBorrowingIterator_() while true { let span = try it.nextSpan_() guard !span.isEmpty else { break } diff --git a/Sources/ContainersPreview/Protocols/Iterable+Algorithms.swift b/Sources/ContainersPreview/Protocols/Iterable+Algorithms.swift index 85330318..92ecd192 100644 --- a/Sources/ContainersPreview/Protocols/Iterable+Algorithms.swift +++ b/Sources/ContainersPreview/Protocols/Iterable+Algorithms.swift @@ -23,7 +23,7 @@ extension Iterable_ _ nextPartialResult: (_ partialResult: consuming Result, borrowing Element_) throws(Failure_) -> Result ) throws(Failure_) -> Result { - try makeIterableIterator_().reduce(initialResult, nextPartialResult) + try makeBorrowingIterator_().reduce(initialResult, nextPartialResult) } @inlinable @@ -32,7 +32,7 @@ extension Iterable_ _ updateAccumulatingResult: (_ partialResult: inout Result, borrowing Element_) throws(Failure_) -> () ) throws(Failure_) -> Result { - try makeIterableIterator_().reduce(into: initialResult, updateAccumulatingResult) + try makeBorrowingIterator_().reduce(into: initialResult, updateAccumulatingResult) } } @@ -44,7 +44,7 @@ extension Sequence where Self: Iterable_ { _ nextPartialResult: (_ partialResult: consuming Result, borrowing Element_) throws(Failure_) -> Result ) throws(Failure_) -> Result { - try makeIterableIterator_().reduce(initialResult, nextPartialResult) + try makeBorrowingIterator_().reduce(initialResult, nextPartialResult) } @inlinable @@ -53,7 +53,7 @@ extension Sequence where Self: Iterable_ { _ updateAccumulatingResult: (_ partialResult: inout Result, borrowing Element_) throws(Failure_) -> () ) throws(Failure_) -> Result { - try makeIterableIterator_().reduce(into: initialResult, updateAccumulatingResult) + try makeBorrowingIterator_().reduce(into: initialResult, updateAccumulatingResult) } } @@ -69,8 +69,8 @@ extension Iterable_ where OtherSequence: ~Copyable & ~Escapable, OtherSequence.Element_: ~Copyable, OtherSequence.Failure_ == Failure_ { // FIXME: Forward to the iterator's implementation of same - var iter1 = makeIterableIterator_() - var iter2 = other.makeIterableIterator_() + var iter1 = makeBorrowingIterator_() + var iter2 = other.makeBorrowingIterator_() while true { var el1 = try iter1.nextSpan_() diff --git a/Sources/ContainersPreview/Protocols/Iterable+Standard Conformances.swift b/Sources/ContainersPreview/Protocols/Iterable+Standard Conformances.swift index 045679a8..46d5a7a8 100644 --- a/Sources/ContainersPreview/Protocols/Iterable+Standard Conformances.swift +++ b/Sources/ContainersPreview/Protocols/Iterable+Standard Conformances.swift @@ -15,7 +15,7 @@ @available(SwiftStdlib 5.0, *) extension Span: Iterable_ where Element: ~Copyable { - public typealias IterableIterator_ = SpanIterator + public typealias BorrowingIterator_ = SpanIterator public typealias Element_ = Element @inlinable @@ -23,21 +23,21 @@ extension Span: Iterable_ where Element: ~Copyable { @_lifetime(borrow self) @inlinable - public func makeIterableIterator_() -> SpanIterator { + public func makeBorrowingIterator_() -> SpanIterator { SpanIterator(self) } } @available(SwiftStdlib 5.0, *) extension MutableSpan: Iterable_ where Element: ~Copyable { - public typealias IterableIterator_ = SpanIterator + public typealias BorrowingIterator_ = SpanIterator @inlinable public var underestimatedCount_: Int { count } @_lifetime(borrow self) @inlinable - public func makeIterableIterator_() -> SpanIterator { + public func makeBorrowingIterator_() -> SpanIterator { // FIXME: This should be declared to return BorrowingIterator, but it // clashes with the stdlib's alternate definition: // error: 'BorrowingIterator' is ambiguous for type lookup in this context @@ -48,56 +48,56 @@ extension MutableSpan: Iterable_ where Element: ~Copyable { @available(SwiftStdlib 5.0, *) extension OutputSpan: Iterable_ where Element: ~Copyable { - public typealias IterableIterator_ = SpanIterator + public typealias BorrowingIterator_ = SpanIterator @inlinable public var underestimatedCount_: Int { count } @_lifetime(borrow self) @inlinable - public func makeIterableIterator_() -> IterableIterator_ { + public func makeBorrowingIterator_() -> BorrowingIterator_ { SpanIterator(self.span) } } @available(SwiftStdlib 5.0, *) extension InputSpan: Iterable_ where Element: ~Copyable { - public typealias IterableIterator_ = SpanIterator + public typealias BorrowingIterator_ = SpanIterator @inlinable public var underestimatedCount_: Int { count } @_lifetime(borrow self) @inlinable - public func makeIterableIterator_() -> IterableIterator_ { + public func makeBorrowingIterator_() -> BorrowingIterator_ { SpanIterator(self.span) } } @available(SwiftStdlib 6.2, *) extension Array: Iterable_ { - public typealias IterableIterator_ = SpanIterator + public typealias BorrowingIterator_ = SpanIterator @inlinable public var underestimatedCount_: Int { count } @_lifetime(borrow self) @inlinable - public func makeIterableIterator_() -> IterableIterator_ { + public func makeBorrowingIterator_() -> BorrowingIterator_ { SpanIterator(self.span) } } @available(SwiftStdlib 6.2, *) extension InlineArray: Iterable_ where Element: ~Copyable { - public typealias IterableIterator_ = SpanIterator + public typealias BorrowingIterator_ = SpanIterator @inlinable public var underestimatedCount_: Int { count } @_lifetime(borrow self) @inlinable - public func makeIterableIterator_() -> SpanIterator { + public func makeBorrowingIterator_() -> SpanIterator { // FIXME: This should be declared to return BorrowingIterator, but it // clashes with the stdlib's alternate definition: // error: 'BorrowingIterator' is ambiguous for type lookup in this context @@ -113,7 +113,7 @@ where Bound: Strideable, Bound.Stride: SignedInteger public typealias Element = Bound @frozen - public struct IterableIterator_: BorrowingIteratorProtocol_, ~Copyable { + public struct BorrowingIterator_: BorrowingIteratorProtocol_, ~Copyable { @usableFromInline internal var _current: InlineArray<1, Bound> @@ -157,8 +157,8 @@ where Bound: Strideable, Bound.Stride: SignedInteger public var underestimatedCount_: Int { _borrowingUnderestimatedCount } @inlinable - public func makeIterableIterator_() -> IterableIterator_ { - IterableIterator_(self) + public func makeBorrowingIterator_() -> BorrowingIterator_ { + BorrowingIterator_(self) } } @@ -169,7 +169,7 @@ where Bound: Strideable, Bound.Stride: SignedInteger public typealias Element = Bound @frozen - public struct IterableIterator_: BorrowingIteratorProtocol_, ~Copyable { + public struct BorrowingIterator_: BorrowingIteratorProtocol_, ~Copyable { @usableFromInline internal var _current: InlineArray<1, Bound> @@ -214,8 +214,8 @@ where Bound: Strideable, Bound.Stride: SignedInteger public var underestimatedCount_: Int { _borrowingUnderestimatedCount } @inlinable - public func makeIterableIterator_() -> IterableIterator_ { - IterableIterator_(self) + public func makeBorrowingIterator_() -> BorrowingIterator_ { + BorrowingIterator_(self) } } diff --git a/Sources/ContainersPreview/Protocols/Iterable+Utilities.swift b/Sources/ContainersPreview/Protocols/Iterable+Utilities.swift index 16fb1c8f..f2cb3053 100644 --- a/Sources/ContainersPreview/Protocols/Iterable+Utilities.swift +++ b/Sources/ContainersPreview/Protocols/Iterable+Utilities.swift @@ -24,7 +24,7 @@ extension Iterable_ where Self: ~Copyable & ~Escapable, Element_: Copyable { intoPrefixOf buffer: UnsafeMutableBufferPointer ) throws(Failure_) -> Int { var target = buffer - var it = self.makeIterableIterator_() + var it = self.makeBorrowingIterator_() while target.count != 0 { let span = try it.nextSpan_(maxCount: target.count) if span.isEmpty { diff --git a/Sources/ContainersPreview/Protocols/Iterable.swift b/Sources/ContainersPreview/Protocols/Iterable.swift index 36e3db27..f6b22e8b 100644 --- a/Sources/ContainersPreview/Protocols/Iterable.swift +++ b/Sources/ContainersPreview/Protocols/Iterable.swift @@ -18,12 +18,12 @@ public protocol Iterable_: ~Copyable, ~Escapable { associatedtype Element_: ~Copyable associatedtype Failure_: Error = Never - associatedtype IterableIterator_: BorrowingIteratorProtocol_ & ~Copyable & ~Escapable + associatedtype BorrowingIterator_: BorrowingIteratorProtocol_ & ~Copyable & ~Escapable var underestimatedCount_: Int { get } @_lifetime(borrow self) - borrowing func makeIterableIterator_() -> IterableIterator_ + borrowing func makeBorrowingIterator_() -> BorrowingIterator_ func _customContainsEquatableElement_( _ element: borrowing Element_ @@ -63,7 +63,7 @@ where public func _borrowingForEach( _ body: (borrowing Element_) throws(Failure_) -> Void ) throws(Failure_) -> Void { - var it = makeIterableIterator_() + var it = makeBorrowingIterator_() while true { let span = try it.nextSpan_() if span.isEmpty { break } diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Append.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Append.swift index 535f0b92..229e31a8 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Append.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Append.swift @@ -316,7 +316,7 @@ extension RigidDeque /*where Element: Copyable*/ { S: Iterable_ & ~Copyable & ~Escapable >(copying items: borrowing S) throws(S.Failure_) where S.Element_ == Element { - var it = items.makeIterableIterator_() + var it = items.makeBorrowingIterator_() while true { let span = try it.nextSpan_() if span.isEmpty { break } diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift index 6f671115..fcd287dc 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift @@ -60,7 +60,7 @@ extension RigidDeque where Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(borrow self) - public borrowing func makeIterableIterator_() -> BorrowingIterator { + public borrowing func makeBorrowingIterator_() -> BorrowingIterator { BorrowingIterator(_deque: self) } #endif diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift index 484cec12..f68a6235 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift @@ -365,7 +365,7 @@ extension RigidDeque /* where Element: Copyable */ { newCount: Int ) { let expectedCount = self.count + newCount - var it = items.makeIterableIterator_() + var it = items.makeBorrowingIterator_() insert(addingCount: newCount, at: index) { target in it._copyContents_(into: &target) } diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift index 47c5227a..c31d5496 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift @@ -315,7 +315,7 @@ extension RigidDeque /*where Element: Copyable*/ { exactCount: Int ) throws(S.Failure_) where S.Element_ == Element { - var it = items.makeIterableIterator_() + var it = items.makeBorrowingIterator_() try self.prepend(addingCount: exactCount) { (target) throws(S.Failure_) in let span = try it.nextSpan_(maxCount: target.freeCapacity) target._append(copying: span) diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift index ae6bdfc6..ad64df6a 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift @@ -466,7 +466,7 @@ extension RigidDeque /* where Element: Copyable */ { ) { let expectedCount = self.count - subrange.count + newCount - var it = items.makeIterableIterator_() + var it = items.makeBorrowingIterator_() self.replace(removing: subrange, addingCount: newCount) { target in it._copyContents_(into: &target) } diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Append.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Append.swift index e5a58033..58ced3b3 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Append.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Append.swift @@ -303,7 +303,7 @@ extension UniqueDeque /*where Element: Copyable*/ { copying items: borrowing S ) throws(S.Failure_) where S.Element_ == Element { - var it = items.makeIterableIterator_() + var it = items.makeBorrowingIterator_() while true { let span = try it.nextSpan_() if span.isEmpty { break } diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift index a20f5dc6..4b556154 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift @@ -26,7 +26,7 @@ extension UniqueDeque where Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(borrow self) - public borrowing func makeIterableIterator_() -> BorrowingIterator { + public borrowing func makeBorrowingIterator_() -> BorrowingIterator { BorrowingIterator(_deque: self._storage) } #endif diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Insertions.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Insertions.swift index a4bf1781..c452c931 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Insertions.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Insertions.swift @@ -383,7 +383,7 @@ extension UniqueDeque /* where Element: Copyable */ { newCount: Int ) { let expectedCount = self.count + newCount - var it = items.makeIterableIterator_() + var it = items.makeBorrowingIterator_() insert(addingCount: newCount, at: index) { target in it._copyContents_(into: &target) } diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift index 29f6b209..62aa8de1 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift @@ -344,7 +344,7 @@ extension UniqueDeque /*where Element: Copyable*/ { exactCount: Int ) throws(S.Failure_) where S.Element_ == Element { - var it = items.makeIterableIterator_() + var it = items.makeBorrowingIterator_() try self.prepend(addingCount: exactCount) { (target) throws(S.Failure_) in let span = try it.nextSpan_(maxCount: target.freeCapacity) target._append(copying: span) diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Replacements.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Replacements.swift index b66e2feb..75d6d47f 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Replacements.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Replacements.swift @@ -475,7 +475,7 @@ extension UniqueDeque /* where Element: Copyable */ { ) { let expectedCount = self.count - subrange.count + newCount - var it = items.makeIterableIterator_() + var it = items.makeBorrowingIterator_() self.replace(removing: subrange, addingCount: newCount) { target in it._copyContents_(into: &target) } diff --git a/Tests/BasicContainersTests/RigidArrayTests.swift b/Tests/BasicContainersTests/RigidArrayTests.swift index b7219bd0..01a7cc96 100644 --- a/Tests/BasicContainersTests/RigidArrayTests.swift +++ b/Tests/BasicContainersTests/RigidArrayTests.swift @@ -1473,7 +1473,7 @@ class RigidArrayTests: CollectionTestCase { func test_borrowing_map() { let c = 100 let items = RigidArray(capacity: c, copying: 0 ..< c) - let transformed = items.makeIterableIterator_() + let transformed = items.makeBorrowingIterator_() .map { 2 * $0 } .collect(into: UniqueArray.self) expectEqual(transformed.count, c) @@ -1487,7 +1487,7 @@ class RigidArrayTests: CollectionTestCase { func test_borrowing_filter() { let c = 100 let items = RigidArray(capacity: c, copying: 0 ..< c) - let transformed = items.makeIterableIterator_() + let transformed = items.makeBorrowingIterator_() .filter { !$0.isMultiple(of: 6) } .copy() .collect(into: UniqueArray.self) diff --git a/Tests/BasicContainersTests/RigidDictionaryTests.swift b/Tests/BasicContainersTests/RigidDictionaryTests.swift index f85d2e6d..704e4155 100644 --- a/Tests/BasicContainersTests/RigidDictionaryTests.swift +++ b/Tests/BasicContainersTests/RigidDictionaryTests.swift @@ -257,7 +257,7 @@ class RigidDictionaryTests: CollectionTestCase { expectEqual(keys.count, i + 1) expectEqual(keys.capacity, capacity) #if compiler(>=6.4) && UnstableContainersPreview - var it = keys.makeIterableIterator_() + var it = keys.makeBorrowingIterator_() var actual: Set = [] while true { let next = it.nextSpan_() @@ -322,7 +322,7 @@ class RigidDictionaryTests: CollectionTestCase { var seen: Set = [] let indices = d.indices - var it = indices.makeIterableIterator_() + var it = indices.makeBorrowingIterator_() while true { let next = it.nextSpan_() if next.isEmpty { break } diff --git a/Tests/BasicContainersTests/RigidSetTests.swift b/Tests/BasicContainersTests/RigidSetTests.swift index 5025ccfd..bfc8bc44 100644 --- a/Tests/BasicContainersTests/RigidSetTests.swift +++ b/Tests/BasicContainersTests/RigidSetTests.swift @@ -301,7 +301,7 @@ class RigidSetTests: CollectionTestCase { s.insert(tracker.instance(for: i)) var expected = Set(0 ... i) - var it = s.makeIterableIterator_() + var it = s.makeBorrowingIterator_() while true { let next = it.nextSpan_(maxCount: maxCount) guard !next.isEmpty else { break } diff --git a/Tests/BasicContainersTests/UniqueDictionaryTests.swift b/Tests/BasicContainersTests/UniqueDictionaryTests.swift index a8d686ca..42366881 100644 --- a/Tests/BasicContainersTests/UniqueDictionaryTests.swift +++ b/Tests/BasicContainersTests/UniqueDictionaryTests.swift @@ -146,7 +146,7 @@ class UniqueDictionaryTests: CollectionTestCase { expectEqual(keys.count, i + 1) expectEqual(keys.capacity, capacity) #if compiler(>=6.4) && UnstableContainersPreview - var it = keys.makeIterableIterator_() + var it = keys.makeBorrowingIterator_() var actual: Set = [] while true { let next = it.nextSpan_() @@ -210,7 +210,7 @@ class UniqueDictionaryTests: CollectionTestCase { var seen: Set = [] let indices = d.indices - var it = indices.makeIterableIterator_() + var it = indices.makeBorrowingIterator_() while true { let next = it.nextSpan_() if next.isEmpty { break } diff --git a/Tests/ContainersTests/BorrowingSequenceTests.swift b/Tests/ContainersTests/BorrowingSequenceTests.swift index 7b49da9c..bafe236c 100644 --- a/Tests/ContainersTests/BorrowingSequenceTests.swift +++ b/Tests/ContainersTests/BorrowingSequenceTests.swift @@ -66,7 +66,7 @@ final class IterableTests: XCTestCase { @available(SwiftStdlib 5.0, *) extension Iterable_ where Self: ~Copyable & ~Escapable, Element_: Copyable { func collectViaBorrowing() throws(Failure_) -> [Element_] { - var borrowIterator = makeIterableIterator_() + var borrowIterator = makeBorrowingIterator_() var result: [Element_] = [] while true { let span = try borrowIterator.nextSpan_(maxCount: .max) diff --git a/Tests/_CollectionsTestSupport/AssertionContexts/Assertions+Containers.swift b/Tests/_CollectionsTestSupport/AssertionContexts/Assertions+Containers.swift index ca9c9a18..929ac9e5 100644 --- a/Tests/_CollectionsTestSupport/AssertionContexts/Assertions+Containers.swift +++ b/Tests/_CollectionsTestSupport/AssertionContexts/Assertions+Containers.swift @@ -138,7 +138,7 @@ public func expectIterablePayloads< file: StaticString = #filePath, line: UInt = #line ) throws(E) where E1.Element_: ~Copyable { - var it1 = left.makeIterableIterator_() + var it1 = left.makeBorrowingIterator_() var it2 = right.makeIterator() var i = 0 while true { @@ -186,7 +186,7 @@ public func expectIterablePayloads< file: StaticString = #filePath, line: UInt = #line ) throws(E) { - var it1 = left.makeIterableIterator_() + var it1 = left.makeBorrowingIterator_() var it2 = right.makeIterator() var i = 0 while true { @@ -284,7 +284,7 @@ public func expectIterableContents< file: StaticString = #filePath, line: UInt = #line ) throws(E) { - var it1 = left.makeIterableIterator_() + var it1 = left.makeBorrowingIterator_() var it2 = right.makeIterator() while true { let span = try it1.nextSpan_() @@ -327,7 +327,7 @@ public func expectIterableContents< file: StaticString = #filePath, line: UInt = #line ) throws(S1.Failure_) where S1.Element_: ~Copyable { - var it1 = left.makeIterableIterator_() + var it1 = left.makeBorrowingIterator_() var it2 = right.makeIterator() var offset = 0 while true { diff --git a/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift b/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift index 04b040ea..e922a6c6 100644 --- a/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift +++ b/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift @@ -60,7 +60,7 @@ public func checkIterable< let spanShapes: [Range] = try { () throws(S.Failure_) in var r: [Range] = [] var pos = 0 - var it = iterable.makeIterableIterator_() + var it = iterable.makeBorrowingIterator_() while true { let origPos = pos let span = try it.nextSpan_() @@ -79,7 +79,7 @@ public func checkIterable< // Check that the spans have stable sizes and the expected contents. do { var pos = 0 - var it = iterable.makeIterableIterator_() + var it = iterable.makeBorrowingIterator_() var spanIndex = 0 while true { let span = try it.nextSpan_() @@ -100,7 +100,7 @@ public func checkIterable< // Check that we can iterate one by one. do { var pos = 0 - var it = iterable.makeIterableIterator_() + var it = iterable.makeBorrowingIterator_() while true { let span = try it.nextSpan_(maxCount: 1) if span.isEmpty { break } @@ -116,7 +116,7 @@ public func checkIterable< // Check that we can iterate with huge maximum counts do { var pos = 0 - var it = iterable.makeIterableIterator_() + var it = iterable.makeBorrowingIterator_() var spanIndex = 0 while true { let span = try it.nextSpan_(maxCount: Int.max) diff --git a/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift b/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift index ac83ee40..7e20eb98 100644 --- a/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift +++ b/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift @@ -117,12 +117,12 @@ public struct _StaccatoIndex: Comparable { @available(SwiftStdlib 5.0, *) extension StaccatoContainer: Iterable_ where Element: ~Copyable { - public typealias IterableIterator_ = _StaccatoBorrowingIterator // FIXME rdar://150240032 + public typealias BorrowingIterator_ = _StaccatoBorrowingIterator // FIXME rdar://150240032 public var underestimatedCount_: Int { count } - public func makeIterableIterator_() -> IterableIterator_ { - IterableIterator_(contents: _contents.span, params: _params) + public func makeBorrowingIterator_() -> BorrowingIterator_ { + BorrowingIterator_(contents: _contents.span, params: _params) } } From 721b5bce414d3c88b9ada54ecbb6b6e524ba8a4b Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 2 Jul 2026 10:24:27 -0700 Subject: [PATCH 23/50] Iterable_: Define an ambiguity resolver for the default `underEstimatedCount` --- .../Protocols/Iterable.swift | 27 +++---------------- 1 file changed, 3 insertions(+), 24 deletions(-) diff --git a/Sources/ContainersPreview/Protocols/Iterable.swift b/Sources/ContainersPreview/Protocols/Iterable.swift index f6b22e8b..380262d9 100644 --- a/Sources/ContainersPreview/Protocols/Iterable.swift +++ b/Sources/ContainersPreview/Protocols/Iterable.swift @@ -46,34 +46,13 @@ where @available(SwiftStdlib 5.0, *) extension Iterable_ where Self: Sequence { + @inlinable + public var underestimatedCount_: Int { 0 } + @inlinable public func _customContainsEquatableElement_(_ element: borrowing Element) -> Bool? { nil } } -@available(SwiftStdlib 5.0, *) -extension Iterable_ -where - Self: ~Copyable & ~Escapable, - Element_: ~Copyable -{ - /// Implementation demo of what borrowing for-in loops would need to expand into. - @inlinable - public func _borrowingForEach( - _ body: (borrowing Element_) throws(Failure_) -> Void - ) throws(Failure_) -> Void { - var it = makeBorrowingIterator_() - while true { - let span = try it.nextSpan_() - if span.isEmpty { break } - var i = 0 - while i < span.count { - try body(span[unchecked: i]) - i &+= 1 - } - } - } -} - #endif From a80c9d12570a8062aefde295f09562f5708ab182 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 2 Jul 2026 15:02:43 -0700 Subject: [PATCH 24/50] Container: Add `makeBorrowingIterator(from:)` and `currentIndex(of:)` requirements --- .../RigidArray/RigidArray+Container.swift | 27 +++++++++++- .../UniqueArray/UniqueArray+Container.swift | 15 ++++++- .../Conformances/InputSpan+Container.swift | 16 +++++++ .../Conformances/MutableSpan+Container.swift | 21 +++++++++ .../Conformances/OutputSpan+Container.swift | 16 +++++++ .../Conformances/Span+Container.swift | 24 ++++++++++ .../Protocols/BorrowingIteratorProtocol.swift | 17 ++++--- .../Protocols/Container/Container.swift | 4 ++ .../Iterable+Standard Conformances.swift | 5 ++- .../ContainersPreview/Types/InputSpan.swift | 1 + .../RigidDeque/RigidDeque+Container.swift | 44 +++++++++++++++++-- .../UniqueDeque/UniqueDeque+Container.swift | 15 ++++++- 12 files changed, 186 insertions(+), 19 deletions(-) diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Container.swift b/Sources/BasicContainers/RigidArray/RigidArray+Container.swift index ab074f8e..4b6c7167 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Container.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Container.swift @@ -22,17 +22,40 @@ import ContainersPreview @available(SwiftStdlib 5.0, *) extension RigidArray: Iterable_ where Element: ~Copyable { public typealias BorrowingIterator_ = SpanIterator + @_alwaysEmitIntoClient @inline(__always) public func makeBorrowingIterator_() -> BorrowingIterator_ { - SpanIterator(self.span) + let span = self.span + let it = span.makeBorrowingIterator_() + // FIXME: `it` is borrowing `span`, not self + return _overrideLifetime(it, borrowing: self) } } #endif #if compiler(>=6.4) && UnstableContainersPreview @available(SwiftStdlib 5.0, *) -extension RigidArray: Container where Element: ~Copyable {} +extension RigidArray: Container where Element: ~Copyable { + @_alwaysEmitIntoClient + @_lifetime(borrow self) + public func makeBorrowingIterator( + from start: Index + ) -> BorrowingIterator_ { + let span = self.span + let it = span.makeBorrowingIterator(from: start) + // FIXME: `it` is borrowing `span`, not self + return _overrideLifetime(it, borrowing: self) + } + + @_alwaysEmitIntoClient + public func currentIndex(of iterator: borrowing BorrowingIterator_) -> Index { + precondition( + iterator._span.isTriviallyIdentical(to: self.span), + "Invalid iterator instance") + return iterator._start + } +} @available(SwiftStdlib 5.0, *) extension RigidArray: BidirectionalContainer where Element: ~Copyable {} diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift index 2b5e4e87..6d158025 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift @@ -36,7 +36,20 @@ extension UniqueArray: Iterable_ where Element: ~Copyable { #if compiler(>=6.4) && UnstableContainersPreview @available(SwiftStdlib 5.0, *) -extension UniqueArray: Container where Element: ~Copyable {} +extension UniqueArray: Container where Element: ~Copyable { + @_alwaysEmitIntoClient + @_lifetime(borrow self) + public func makeBorrowingIterator( + from start: Index + ) -> BorrowingIterator_ { + _storage.makeBorrowingIterator(from: start) + } + + @_alwaysEmitIntoClient + public func currentIndex(of iterator: borrowing BorrowingIterator_) -> Index { + _storage.currentIndex(of: iterator) + } +} @available(SwiftStdlib 5.0, *) extension UniqueArray: BidirectionalContainer where Element: ~Copyable {} diff --git a/Sources/ContainersPreview/Conformances/InputSpan+Container.swift b/Sources/ContainersPreview/Conformances/InputSpan+Container.swift index 805907ce..24bd2cc4 100644 --- a/Sources/ContainersPreview/Conformances/InputSpan+Container.swift +++ b/Sources/ContainersPreview/Conformances/InputSpan+Container.swift @@ -21,6 +21,22 @@ import InternalCollectionsUtilities extension InputSpan: RandomAccessContainer, MutableContainer where Element: ~Copyable { + @_alwaysEmitIntoClient + @_lifetime(borrow self) + public func makeBorrowingIterator( + from start: Index + ) -> BorrowingIterator_ { + let span = self.span + let it = span.makeBorrowingIterator(from: start) + // FIXME: `it` is borrowing `span`, not self + return _overrideLifetime(it, borrowing: self) + } + + @_alwaysEmitIntoClient + public func currentIndex(of iterator: borrowing BorrowingIterator_) -> Index { + self.span.currentIndex(of: iterator) + } + @_alwaysEmitIntoClient @inline(__always) public var startIndex: Index { 0 } diff --git a/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift b/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift index 4b524e46..52d2723c 100644 --- a/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift +++ b/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift @@ -18,6 +18,27 @@ import InternalCollectionsUtilities #endif extension MutableSpan: RandomAccessContainer where Element: ~Copyable { + @_alwaysEmitIntoClient + @_lifetime(borrow self) + public func makeBorrowingIterator(from start: Int) -> SpanIterator { + var it = SpanIterator(self.span) + var remainder = start + while remainder > 0 { + let d = it.skip_(by: remainder) + precondition(d > 0) + remainder &-= d + } + return it + } + + @_alwaysEmitIntoClient + public func currentIndex(of iterator: borrowing SpanIterator) -> Int { + precondition( + self.span.isTriviallyIdentical(to: iterator._span), + "Invalid iterator") + return iterator._start + } + @_alwaysEmitIntoClient public var startIndex: Int { 0 diff --git a/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift b/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift index d3f5ceb8..2368855b 100644 --- a/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift +++ b/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift @@ -20,6 +20,22 @@ import InternalCollectionsUtilities extension OutputSpan: RandomAccessContainer, MutableContainer where Element: ~Copyable { + @_alwaysEmitIntoClient + @_lifetime(borrow self) + public func makeBorrowingIterator( + from start: Index + ) -> BorrowingIterator_ { + let span = self.span + let it = span.makeBorrowingIterator(from: start) + // FIXME: `it` is borrowing `span`, not self + return _overrideLifetime(it, borrowing: self) + } + + @_alwaysEmitIntoClient + public func currentIndex(of iterator: borrowing BorrowingIterator_) -> Index { + self.span.currentIndex(of: iterator) + } + @_alwaysEmitIntoClient @inline(__always) public var startIndex: Index { 0 } diff --git a/Sources/ContainersPreview/Conformances/Span+Container.swift b/Sources/ContainersPreview/Conformances/Span+Container.swift index 4d5c81d5..9276491d 100644 --- a/Sources/ContainersPreview/Conformances/Span+Container.swift +++ b/Sources/ContainersPreview/Conformances/Span+Container.swift @@ -14,6 +14,30 @@ #if compiler(>=6.4) && UnstableContainersPreview extension Span: RandomAccessContainer where Element: ~Copyable { + @_alwaysEmitIntoClient + @_lifetime(borrow self) + public func makeBorrowingIterator(from start: Int) -> SpanIterator { + precondition(start >= 0 && start <= self.count, "Index out of bounds") + // FIXME: SpanIterator needs to have a direct initializer that takes `start` + var it = SpanIterator(self) + var remainder = start + while remainder > 0 { + let d = it.skip_(by: remainder) + precondition(d > 0) + remainder &-= d + } + return it + } + + @_alwaysEmitIntoClient + public func currentIndex(of iterator: borrowing SpanIterator) -> Int { + // FIXME: SpanIterator needs to have public `base` and `position` properties + precondition( + self.isTriviallyIdentical(to: iterator._span), + "Invalid iterator") + return iterator._start + } + @_alwaysEmitIntoClient public var startIndex: Int { 0 diff --git a/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol.swift b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol.swift index ea33fd18..b8009880 100644 --- a/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol.swift +++ b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol.swift @@ -101,28 +101,28 @@ extension BorrowingIteratorProtocol_ where Self: ~Copyable & ~Escapable, Element_: ~Copyable { @_lifetime(self: copy self) @inlinable - public mutating func skip_(by offset: Int) throws(Failure_) -> Int { - var remainder = offset + public mutating func skip_(by maxDistance: Int) throws(Failure_) -> Int { + var remainder = maxDistance while remainder > 0 { let span = try nextSpan_(maxCount: remainder) if span.isEmpty { break } remainder &-= span.count } - return offset &- remainder + return maxDistance &- remainder } } @available(SwiftStdlib 5.0, *) extension BorrowingIteratorProtocol_ where Self: ~Copyable & ~Escapable { -#if false // FIXME: This doesn't work, but it should? + @available(SwiftStdlib 6.4, *) + @_unsafeNonescapableResult // FIXME: Eep; _overrideLifetime(_:mutating:) doesn't work @_lifetime(&self) @_lifetime(self: copy self) - public mutating func next() -> Ref? { - let span = nextSpan(maxCount: 1) + public mutating func next() throws(Failure_) -> Ref? { + let span = try nextSpan_(maxCount: 1) guard !span.isEmpty else { return nil } - return Ref(_borrowing: span[unchecked: 0]) + return Ref(span[unchecked: 0]) } -#endif } @available(SwiftStdlib 5.0, *) @@ -145,5 +145,4 @@ extension BorrowingIteratorProtocol_ } } - #endif diff --git a/Sources/ContainersPreview/Protocols/Container/Container.swift b/Sources/ContainersPreview/Protocols/Container/Container.swift index dd45a270..ed7be60c 100644 --- a/Sources/ContainersPreview/Protocols/Container/Container.swift +++ b/Sources/ContainersPreview/Protocols/Container/Container.swift @@ -29,6 +29,10 @@ public protocol Container: // somewhere -- `RandomAccessContainer` or `BidirectionalContainer` would be // the obvious candidates. + @_lifetime(borrow self) + func makeBorrowingIterator(from start: Index) -> BorrowingIterator_ + func currentIndex(of iterator: borrowing BorrowingIterator_) -> Index + var isEmpty: Bool { get } var count: Int { get } diff --git a/Sources/ContainersPreview/Protocols/Iterable+Standard Conformances.swift b/Sources/ContainersPreview/Protocols/Iterable+Standard Conformances.swift index 46d5a7a8..6fd17844 100644 --- a/Sources/ContainersPreview/Protocols/Iterable+Standard Conformances.swift +++ b/Sources/ContainersPreview/Protocols/Iterable+Standard Conformances.swift @@ -15,8 +15,8 @@ @available(SwiftStdlib 5.0, *) extension Span: Iterable_ where Element: ~Copyable { - public typealias BorrowingIterator_ = SpanIterator - public typealias Element_ = Element + public typealias BorrowingIterator_ = SpanIterator + public typealias Element_ = Element @inlinable public var underestimatedCount_: Int { count } @@ -31,6 +31,7 @@ extension Span: Iterable_ where Element: ~Copyable { @available(SwiftStdlib 5.0, *) extension MutableSpan: Iterable_ where Element: ~Copyable { public typealias BorrowingIterator_ = SpanIterator + public typealias Element_ = Element @inlinable public var underestimatedCount_: Int { count } diff --git a/Sources/ContainersPreview/Types/InputSpan.swift b/Sources/ContainersPreview/Types/InputSpan.swift index 1c09bd20..1bc52c51 100644 --- a/Sources/ContainersPreview/Types/InputSpan.swift +++ b/Sources/ContainersPreview/Types/InputSpan.swift @@ -465,6 +465,7 @@ extension InputSpan where Element: ~Copyable { /// Borrow the underlying initialized memory for read-only access. @available(SwiftStdlib 5.0, *) @_alwaysEmitIntoClient + @_transparent public var span: Span { @_lifetime(borrow self) borrowing get { diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift index fcd287dc..6377acb5 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift @@ -31,7 +31,10 @@ extension RigidDeque where Element: ~Copyable { @usableFromInline internal var _nextSegment: Span - + + @usableFromInline + internal var _position: Int + @_alwaysEmitIntoClient @_lifetime(borrow _deque) internal init(_deque: borrowing RigidDeque) { @@ -43,10 +46,28 @@ extension RigidDeque where Element: ~Copyable { Span( _unsafeElements: segments.second ?? UnsafeBufferPointer._empty), borrowing: _deque) + self._position = 0 } - + @_alwaysEmitIntoClient - @_lifetime(&self) // FIXME: This should be `@_lifetime(copy self)` + @_lifetime(borrow _deque) + internal init( + _deque: borrowing RigidDeque, + from start: Int + ) { + precondition(start >= 0 && start <= _deque.count, "Index out of bounds") + self.init(_deque: _deque) + var remainder = start + while remainder > 0 { + let d = self.skip_(by: remainder) + precondition(d > 0) + remainder &-= d + } + self._position = start + } + + @_alwaysEmitIntoClient + @_lifetime(&self) @_lifetime(self: copy self) public mutating func nextSpan_(maxCount: Int) -> Span { let result = _currentSegment._trim(first: maxCount) @@ -54,6 +75,7 @@ extension RigidDeque where Element: ~Copyable { _currentSegment = _nextSegment _nextSegment = Span() } + _position &+= result.count return result } } @@ -68,7 +90,21 @@ extension RigidDeque where Element: ~Copyable { #if compiler(>=6.4) && UnstableContainersPreview @available(SwiftStdlib 5.0, *) -extension RigidDeque: Container where Element: ~Copyable {} +extension RigidDeque: Container where Element: ~Copyable { + @_alwaysEmitIntoClient + @_lifetime(borrow self) + public func makeBorrowingIterator( + from start: Index + ) -> BorrowingIterator_ { + BorrowingIterator(_deque: self, from: start) + } + + @_alwaysEmitIntoClient + public func currentIndex(of iterator: borrowing BorrowingIterator_) -> Index { + // FIXME: This should validate that the iterator belongs to this deque. + return iterator._position + } +} @available(SwiftStdlib 5.0, *) extension RigidDeque: BidirectionalContainer where Element: ~Copyable {} diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift index 4b556154..d5527471 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift @@ -34,7 +34,20 @@ extension UniqueDeque where Element: ~Copyable { #if compiler(>=6.4) && UnstableContainersPreview @available(SwiftStdlib 5.0, *) -extension UniqueDeque: Container where Element: ~Copyable {} +extension UniqueDeque: Container where Element: ~Copyable { + @_alwaysEmitIntoClient + @_lifetime(borrow self) + public func makeBorrowingIterator( + from start: Index + ) -> BorrowingIterator_ { + _storage.makeBorrowingIterator(from: start) + } + + @_alwaysEmitIntoClient + public func currentIndex(of iterator: borrowing BorrowingIterator_) -> Index { + _storage.currentIndex(of: iterator) + } +} @available(SwiftStdlib 5.0, *) extension UniqueDeque: BidirectionalContainer where Element: ~Copyable {} From ff695132eda9ef3453cb4e911d71b7de78197a2a Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 7 Jul 2026 14:10:26 -0700 Subject: [PATCH 25/50] Bump availability of Iterable_ and Container protocols to SwiftStdlib 6.4 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This is preparing for switching over to the stdlib’s definition of `protocol Iterable`, assuming it will land with macOS 27/iOS 27 etc availability; `Container` is refining `Iterable`, so it needs matching availability. If `Iterable` won’t ship in Swift 6.4, then we’ll need to bump this again. --- .../RigidArray/RigidArray+Append.swift | 3 + .../RigidArray/RigidArray+Container.swift | 14 +- .../RigidArray/RigidArray+Initializers.swift | 2 + .../RigidArray/RigidArray+Insertions.swift | 7 +- .../RigidArray/RigidArray+Removals.swift | 2 - .../RigidArray/RigidArray+Replacements.swift | 3 + .../RigidSet/RigidSet+Initializers.swift | 3 + .../RigidSet/RigidSet+Insertions.swift | 3 + .../UniqueArray/UniqueArray+Append.swift | 3 + .../UniqueArray/UniqueArray+Container.swift | 16 +- .../UniqueArray+Initializers.swift | 2 + .../UniqueArray/UniqueArray+Removals.swift | 2 - .../UniqueArray+Replacements.swift | 2 + .../UniqueSet/UniqueSet+Initializers.swift | 2 + .../UniqueSet/UniqueSet+Insertions.swift | 3 + Sources/ContainersPreview/CMakeLists.txt | 10 +- .../Conformances/Array+Iterable.swift | 31 +++ .../Conformances/ClosedRange+Iterable.swift | 69 ++++++ .../Conformances/InlineArray+Iterable.swift | 31 +++ .../Conformances/InputSpan+Container.swift | 2 +- .../Conformances/InputSpan+Iterable.swift | 30 +++ .../Conformances/MutableSpan+Container.swift | 12 +- .../Conformances/MutableSpan+Iterable.swift | 35 +++ .../Conformances/OutputSpan+Container.swift | 2 +- .../Conformances/OutputSpan+Iterable.swift | 31 +++ .../Conformances/Range+Iterable.swift | 68 ++++++ .../Conformances/Span+Container.swift | 7 +- .../Conformances/Span+Iterable.swift | 79 +++++++ ...rowingIteratorProtocol+ElementsEqual.swift | 8 +- .../Container/BidirectionalContainer.swift | 4 +- .../Container/Container+SpanwiseZip.swift | 2 +- .../Protocols/Container/Container.swift | 8 +- .../Container/DynamicContainer.swift | 6 +- .../Container/MutableContainer.swift | 4 +- .../Container/PermutableContainer.swift | 2 +- .../Container/RandomAccessContainer.swift | 8 +- .../Container/RangeExpression2.swift | 12 +- .../Container/RangeReplaceableContainer.swift | 22 +- .../Protocols/Iterable+Algorithms.swift | 8 +- .../Iterable+Standard Conformances.swift | 223 ------------------ .../Protocols/Iterable+Utilities.swift | 2 +- .../Protocols/Iterable.swift | 12 +- .../Protocols/Producer+Collect.swift | 3 + .../Types/SpanIterator.swift | 61 ----- .../RigidDeque/RigidDeque+Append.swift | 3 + .../RigidDeque/RigidDeque+Equatable.swift | 7 +- .../RigidDeque/RigidDeque+Initializers.swift | 5 + .../RigidDeque/RigidDeque+Insertions.swift | 3 + .../RigidDeque/RigidDeque+Prepend.swift | 8 + .../RigidDeque/RigidDeque+Removals.swift | 4 +- .../RigidDeque/RigidDeque+Replacements.swift | 3 + .../UniqueDeque/UniqueDeque+Append.swift | 3 + .../UniqueDeque+Initializers.swift | 3 + .../UniqueDeque/UniqueDeque+Insertions.swift | 3 + .../UniqueDeque/UniqueDeque+Prepend.swift | 8 + .../UniqueDeque/UniqueDeque+Removals.swift | 4 +- .../UniqueDeque+Replacements.swift | 3 + .../RigidArrayTests.swift | 6 +- .../UniqueArrayTests.swift | 4 +- .../BorrowingSequenceTests.swift | 4 +- Tests/DequeTests/RigidDequeTests.swift | 28 ++- Tests/DequeTests/UniqueDequeTests.swift | 24 +- .../Assertions+Containers.swift | 12 +- .../ConformanceCheckers/CheckContainer.swift | 4 +- .../MinimalTypes/StaccatoContainer.swift | 25 +- Xcode/Collections.xcodeproj/project.pbxproj | 40 +++- 66 files changed, 645 insertions(+), 418 deletions(-) create mode 100644 Sources/ContainersPreview/Conformances/Array+Iterable.swift create mode 100644 Sources/ContainersPreview/Conformances/ClosedRange+Iterable.swift create mode 100644 Sources/ContainersPreview/Conformances/InlineArray+Iterable.swift create mode 100644 Sources/ContainersPreview/Conformances/InputSpan+Iterable.swift create mode 100644 Sources/ContainersPreview/Conformances/MutableSpan+Iterable.swift create mode 100644 Sources/ContainersPreview/Conformances/OutputSpan+Iterable.swift create mode 100644 Sources/ContainersPreview/Conformances/Range+Iterable.swift create mode 100644 Sources/ContainersPreview/Conformances/Span+Iterable.swift delete mode 100644 Sources/ContainersPreview/Protocols/Iterable+Standard Conformances.swift delete mode 100644 Sources/ContainersPreview/Types/SpanIterator.swift diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Append.swift b/Sources/BasicContainers/RigidArray/RigidArray+Append.swift index e1a78649..f0df517b 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Append.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Append.swift @@ -253,6 +253,7 @@ extension RigidArray { } #if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) @inlinable internal mutating func _append< Source: Iterable_ & ~Copyable & ~Escapable @@ -275,6 +276,7 @@ extension RigidArray { /// - newElements: A container whose contents to copy into the array. /// /// - Complexity: O(`newElements.count`) + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient @inline(__always) public mutating func append< @@ -318,6 +320,7 @@ extension RigidArray { /// - newElements: The new elements to copy into the array. /// /// - Complexity: O(*m*), where *m* is the length of `newElements`. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient @inline(__always) public mutating func append< diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Container.swift b/Sources/BasicContainers/RigidArray/RigidArray+Container.swift index 4b6c7167..6aa3b7e4 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Container.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Container.swift @@ -19,9 +19,9 @@ import ContainersPreview #if compiler(>=6.2) #if compiler(>=6.4) && UnstableContainersPreview -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension RigidArray: Iterable_ where Element: ~Copyable { - public typealias BorrowingIterator_ = SpanIterator + public typealias BorrowingIterator_ = Span.BorrowingIterator_ @_alwaysEmitIntoClient @inline(__always) @@ -35,7 +35,7 @@ extension RigidArray: Iterable_ where Element: ~Copyable { #endif #if compiler(>=6.4) && UnstableContainersPreview -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension RigidArray: Container where Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(borrow self) @@ -57,17 +57,17 @@ extension RigidArray: Container where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension RigidArray: BidirectionalContainer where Element: ~Copyable {} -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension RigidArray: RandomAccessContainer where Element: ~Copyable {} #if compiler(>=6.4) -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension RigidArray: MutableContainer where Element: ~Copyable {} -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension RigidArray: RangeReplaceableContainer where Element: ~Copyable {} #endif #endif diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Initializers.swift b/Sources/BasicContainers/RigidArray/RigidArray+Initializers.swift index 62976415..c06037db 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Initializers.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Initializers.swift @@ -122,6 +122,7 @@ extension RigidArray /*where Element: Copyable*/ { /// just enough capacity to store the contents. /// - contents: The container whose contents to copy into the new array. /// The container must not contain more than `capacity` elements. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient @inline(__always) public init( @@ -144,6 +145,7 @@ extension RigidArray /*where Element: Copyable*/ { /// just enough capacity to store the contents. /// - contents: The container whose contents to copy into the new array. /// The container must not contain more than `capacity` elements. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient @inline(__always) public init>( diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Insertions.swift b/Sources/BasicContainers/RigidArray/RigidArray+Insertions.swift index 980a0460..80599107 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Insertions.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Insertions.swift @@ -330,13 +330,14 @@ extension RigidArray { } } -#if !UnstableContainersPreview @_alwaysEmitIntoClient package mutating func _insertCollection( addingCount newCount: Int, copying items: some Collection, at index: Index ) { + // FIXME: Remove this -- RangeReplaceContainer already has this algorithm, + // albeit with stricter availability. let done: Void? = items.withContiguousStorageIfAvailable { buffer in precondition(buffer.count == newCount, "Broken Collection: mismatching count") self.insert(addingCount: buffer.count, at: index) { target in @@ -353,7 +354,6 @@ extension RigidArray { } precondition(it.next() == nil, "Broken Collection") } -#endif /// Copies the elements of a collection into this array at the specified /// position. @@ -379,9 +379,6 @@ extension RigidArray { public mutating func insert( copying items: some Collection, at index: Int ) { - // FIXME: Remove this -- RangeReplaceContainer already has this algorithm. - // (Note that this would be source breaking while RRC lives in the separate - // ContainersPreview module.) _insertCollection(addingCount: items.count, copying: items, at: index) } } diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Removals.swift b/Sources/BasicContainers/RigidArray/RigidArray+Removals.swift index 1d502fe6..1b41f517 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Removals.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Removals.swift @@ -121,7 +121,6 @@ extension RigidArray where Element: ~Copyable { @available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { -#if !UnstableContainersPreview /// Removes and returns the last element of the array, if there is one. /// /// - Returns: The last element of the array if the array is not empty; @@ -134,7 +133,6 @@ extension RigidArray where Element: ~Copyable { if isEmpty { return nil } return removeLast() } -#endif } #endif diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Replacements.swift b/Sources/BasicContainers/RigidArray/RigidArray+Replacements.swift index ba99611c..b193c14e 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Replacements.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Replacements.swift @@ -583,6 +583,7 @@ extension RigidArray { } #if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) @inlinable internal mutating func _replace< C: Container & ~Copyable & ~Escapable @@ -661,6 +662,7 @@ extension RigidArray { /// - newElements: The new elements to copy into the collection. /// /// - Complexity: O(`self.count` + `newElements.count`) + @available(SwiftStdlib 6.4, *) @inlinable @inline(__always) public mutating func replace< @@ -742,6 +744,7 @@ extension RigidArray { /// /// - Complexity: O(*n* + *m*), where *n* is count of this array and /// *m* is the count of `newElements`. + @available(SwiftStdlib 6.4, *) @inlinable @inline(__always) public mutating func replace< diff --git a/Sources/BasicContainers/RigidSet/RigidSet+Initializers.swift b/Sources/BasicContainers/RigidSet/RigidSet+Initializers.swift index d7bc1cf8..4bb4f0dd 100644 --- a/Sources/BasicContainers/RigidSet/RigidSet+Initializers.swift +++ b/Sources/BasicContainers/RigidSet/RigidSet+Initializers.swift @@ -82,6 +82,7 @@ extension RigidSet where Element: ~Copyable { @available(SwiftStdlib 5.0, *) extension RigidSet /* where Element: Copyable */ { #if UnstableContainersPreview + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient @inline(__always) public init< @@ -117,6 +118,7 @@ extension RigidSet /* where Element: Copyable */ { } #if UnstableContainersPreview + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient @inline(__always) public init< @@ -130,6 +132,7 @@ extension RigidSet /* where Element: Copyable */ { try self._insert(copying: contents) } + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient @inline(__always) public init< diff --git a/Sources/BasicContainers/RigidSet/RigidSet+Insertions.swift b/Sources/BasicContainers/RigidSet/RigidSet+Insertions.swift index 0f64bdc7..1415bfd9 100644 --- a/Sources/BasicContainers/RigidSet/RigidSet+Insertions.swift +++ b/Sources/BasicContainers/RigidSet/RigidSet+Insertions.swift @@ -235,6 +235,7 @@ extension RigidSet /* where Element: Copyable */ { } #if UnstableContainersPreview + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient package mutating func _insert< S: Iterable_ & ~Copyable & ~Escapable @@ -252,6 +253,7 @@ extension RigidSet /* where Element: Copyable */ { #endif #if UnstableContainersPreview + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient @inline(__always) public mutating func insert< @@ -274,6 +276,7 @@ extension RigidSet /* where Element: Copyable */ { } #if UnstableContainersPreview + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient @inline(__always) public mutating func insert< diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Append.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Append.swift index b80ed3bc..56027fe9 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Append.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Append.swift @@ -258,6 +258,7 @@ extension UniqueArray { } #if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) @inlinable internal mutating func _append< Source: Iterable_ & ~Copyable & ~Escapable @@ -291,6 +292,7 @@ extension UniqueArray { /// /// - Complexity: O(`newElements.count`), when amortized over many invocations /// over the same array. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient @inline(__always) public mutating func append< @@ -346,6 +348,7 @@ extension UniqueArray { /// /// - Complexity: O(`newElements.count`), when amortized over many invocations /// over the same array. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient @inline(__always) public mutating func append< diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift index 6d158025..03a596c4 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift @@ -19,9 +19,9 @@ import ContainersPreview #if compiler(>=6.2) #if compiler(>=6.4) && UnstableContainersPreview -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension UniqueArray: Iterable_ where Element: ~Copyable { - public typealias BorrowingIterator_ = RigidArray.BorrowingIterator_ + public typealias BorrowingIterator_ = Span.BorrowingIterator_ @inlinable public var underestimatedCount_: Int { count } @@ -35,7 +35,7 @@ extension UniqueArray: Iterable_ where Element: ~Copyable { #endif #if compiler(>=6.4) && UnstableContainersPreview -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension UniqueArray: Container where Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(borrow self) @@ -51,20 +51,20 @@ extension UniqueArray: Container where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension UniqueArray: BidirectionalContainer where Element: ~Copyable {} -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension UniqueArray: RandomAccessContainer where Element: ~Copyable {} -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension UniqueArray: MutableContainer where Element: ~Copyable {} #if compiler(>=6.4) -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension UniqueArray: RangeReplaceableContainer where Element: ~Copyable {} -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension UniqueArray: DynamicContainer where Element: ~Copyable {} #endif #endif diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Initializers.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Initializers.swift index 678933f1..ce4ce62a 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Initializers.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Initializers.swift @@ -94,6 +94,7 @@ extension UniqueArray /*where Element: Copyable*/ { /// just enough capacity to store the contents. /// - contents: A sequence whose contents to copy into the new array. /// The sequence must not contain more than `capacity` elements. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient @inline(__always) public init( @@ -131,6 +132,7 @@ extension UniqueArray /*where Element: Copyable*/ { /// - capacity: The storage capacity of the new array, or nil to allocate /// just enough capacity to store the contents. /// - contents: The container whose contents to copy into the new array. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient @inline(__always) public init>( diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Removals.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Removals.swift index 25b488e8..deaa5bc1 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Removals.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Removals.swift @@ -110,7 +110,6 @@ extension UniqueArray where Element: ~Copyable { @available(SwiftStdlib 5.0, *) extension UniqueArray where Element: ~Copyable { -#if !UnstableContainersPreview /// Removes and returns the last element of the array, if there is one. /// /// - Returns: The last element of the array if the array is not empty; @@ -123,7 +122,6 @@ extension UniqueArray where Element: ~Copyable { if isEmpty { return nil } return removeLast() } -#endif } #endif diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Replacements.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Replacements.swift index 816e5818..9c6603e9 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Replacements.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Replacements.swift @@ -551,6 +551,7 @@ extension UniqueArray { /// /// - Complexity: O(*n* + *m*), where *n* is count of this array and /// *m* is the count of `newElements`. + @available(SwiftStdlib 6.4, *) @inlinable @inline(__always) public mutating func replace< @@ -641,6 +642,7 @@ extension UniqueArray { /// /// - Complexity: O(*n* + *m*), where *n* is count of this array and /// *m* is the count of `newElements`. + @available(SwiftStdlib 6.4, *) @inlinable @inline(__always) public mutating func replace< diff --git a/Sources/BasicContainers/UniqueSet/UniqueSet+Initializers.swift b/Sources/BasicContainers/UniqueSet/UniqueSet+Initializers.swift index c6855e27..a4b65a36 100644 --- a/Sources/BasicContainers/UniqueSet/UniqueSet+Initializers.swift +++ b/Sources/BasicContainers/UniqueSet/UniqueSet+Initializers.swift @@ -75,6 +75,7 @@ extension UniqueSet where Element: ~Copyable { extension UniqueSet where Element: Copyable { #if UnstableContainersPreview + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient public init< S: Iterable_ & ~Copyable & ~Escapable @@ -94,6 +95,7 @@ extension UniqueSet where Element: Copyable { } #if UnstableContainersPreview + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient public init< S: Iterable_ & Sequence diff --git a/Sources/BasicContainers/UniqueSet/UniqueSet+Insertions.swift b/Sources/BasicContainers/UniqueSet/UniqueSet+Insertions.swift index 6686459b..ac095a70 100644 --- a/Sources/BasicContainers/UniqueSet/UniqueSet+Insertions.swift +++ b/Sources/BasicContainers/UniqueSet/UniqueSet+Insertions.swift @@ -131,6 +131,7 @@ extension UniqueSet /* where Element: Copyable */ { } #if UnstableContainersPreview + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient package mutating func _insert< S: Iterable_ & ~Copyable & ~Escapable @@ -149,6 +150,7 @@ extension UniqueSet /* where Element: Copyable */ { #endif #if UnstableContainersPreview + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient @inline(__always) public mutating func insert< @@ -171,6 +173,7 @@ extension UniqueSet /* where Element: Copyable */ { } #if UnstableContainersPreview + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient @inline(__always) public mutating func insert< diff --git a/Sources/ContainersPreview/CMakeLists.txt b/Sources/ContainersPreview/CMakeLists.txt index ece38517..7d85b8d3 100644 --- a/Sources/ContainersPreview/CMakeLists.txt +++ b/Sources/ContainersPreview/CMakeLists.txt @@ -25,10 +25,18 @@ else() endif() target_sources(${module_name} PRIVATE + "Conformances/Array+Iterable.swift" + "Conformances/ClosedRange+Iterable.swift" + "Conformances/InlineArray+Iterable.swift" "Conformances/InputSpan+Container.swift" + "Conformances/InputSpan+Iterable.swift" "Conformances/MutableSpan+Container.swift" + "Conformances/MutableSpan+Iterable.swift" "Conformances/OutputSpan+Container.swift" + "Conformances/OutputSpan+Iterable.swift" + "Conformances/Range+Iterable.swift" "Conformances/Span+Container.swift" + "Conformances/Span+Iterable.swift" "Protocols/Container/BidirectionalContainer.swift" "Protocols/Container/Container.swift" "Protocols/Container/Container+Filter.swift" @@ -51,7 +59,6 @@ target_sources(${module_name} PRIVATE "Protocols/BorrowingIteratorProtocol+SpanwiseZip.swift" "Protocols/Iterable.swift" "Protocols/Iterable+Algorithms.swift" - "Protocols/Iterable+Standard Conformances.swift" "Protocols/Iterable+Utilities.swift" "Protocols/CountedProducer.swift" "Protocols/Drain.swift" @@ -66,6 +73,5 @@ target_sources(${module_name} PRIVATE "Types/MutableRef.swift" "Types/OutputSpan+Helpers.swift" "Types/Shared.swift" - "Types/SpanIterator.swift" "Types/UniqueBox.swift" ) diff --git a/Sources/ContainersPreview/Conformances/Array+Iterable.swift b/Sources/ContainersPreview/Conformances/Array+Iterable.swift new file mode 100644 index 00000000..5d6f4b2b --- /dev/null +++ b/Sources/ContainersPreview/Conformances/Array+Iterable.swift @@ -0,0 +1,31 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.4) && UnstableContainersPreview + +@available(SwiftStdlib 6.4, *) +extension Array: Iterable_ { + public typealias Element_ = Element + public typealias BorrowingIterator_ = Span.BorrowingIterator_ + + @inlinable + public var underestimatedCount_: Int { count } + + @_lifetime(borrow self) + @inlinable + public func makeBorrowingIterator_() -> BorrowingIterator_ { + BorrowingIterator_(self.span) + } +} + +#endif diff --git a/Sources/ContainersPreview/Conformances/ClosedRange+Iterable.swift b/Sources/ContainersPreview/Conformances/ClosedRange+Iterable.swift new file mode 100644 index 00000000..c4e199b2 --- /dev/null +++ b/Sources/ContainersPreview/Conformances/ClosedRange+Iterable.swift @@ -0,0 +1,69 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.4) && UnstableContainersPreview + +@available(SwiftStdlib 6.2, *) +extension ClosedRange: Iterable_ +where Bound: Strideable, Bound.Stride: SignedInteger +{ + public typealias Element_ = Bound + + @frozen + public struct BorrowingIterator_: BorrowingIteratorProtocol_, ~Copyable { + @usableFromInline + internal var _current: InlineArray<1, Bound> + + @usableFromInline + internal var _last: Bound + + @usableFromInline + internal var _progress: Bool + + @inlinable + internal init(_ base: ClosedRange) { + self._current = .init(repeating: base.lowerBound) + self._last = base.upperBound + self._progress = false + } + @inlinable + @_lifetime(&self) + public mutating func nextSpan_(maxCount: Int) -> Span { + if _progress { + _current[0] = _current[0].advanced(by: 1) + } + guard _current[0] <= _last else { + _progress = false + return .init() + } + _progress = true + return _current.span + } + } + + @inlinable + public var underestimatedCount_: Int { + guard let distance = Int(exactly: lowerBound.distance(to: upperBound)) + else { return 0 } + let advanced = distance.addingReportingOverflow(1) + guard !advanced.overflow else { return 0 } + return advanced.partialValue + } + + @inlinable + public func makeBorrowingIterator_() -> BorrowingIterator_ { + BorrowingIterator_(self) + } +} + +#endif diff --git a/Sources/ContainersPreview/Conformances/InlineArray+Iterable.swift b/Sources/ContainersPreview/Conformances/InlineArray+Iterable.swift new file mode 100644 index 00000000..b503e97d --- /dev/null +++ b/Sources/ContainersPreview/Conformances/InlineArray+Iterable.swift @@ -0,0 +1,31 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.4) && UnstableContainersPreview + +@available(SwiftStdlib 6.4, *) +extension InlineArray: Iterable_ where Element: ~Copyable { + public typealias Element_ = Element + public typealias BorrowingIterator_ = Span.BorrowingIterator_ + + @inlinable + public var underestimatedCount_: Int { count } + + @_lifetime(borrow self) + @inlinable + public func makeBorrowingIterator_() -> BorrowingIterator_ { + BorrowingIterator_(self.span) + } +} + +#endif diff --git a/Sources/ContainersPreview/Conformances/InputSpan+Container.swift b/Sources/ContainersPreview/Conformances/InputSpan+Container.swift index 24bd2cc4..d2b97f7f 100644 --- a/Sources/ContainersPreview/Conformances/InputSpan+Container.swift +++ b/Sources/ContainersPreview/Conformances/InputSpan+Container.swift @@ -17,7 +17,7 @@ import InternalCollectionsUtilities #if compiler(>=6.2) && UnstableContainersPreview -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension InputSpan: RandomAccessContainer, MutableContainer where Element: ~Copyable { diff --git a/Sources/ContainersPreview/Conformances/InputSpan+Iterable.swift b/Sources/ContainersPreview/Conformances/InputSpan+Iterable.swift new file mode 100644 index 00000000..98d1d49c --- /dev/null +++ b/Sources/ContainersPreview/Conformances/InputSpan+Iterable.swift @@ -0,0 +1,30 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.4) && UnstableContainersPreview + +@available(SwiftStdlib 6.4, *) +extension InputSpan: Iterable_ where Element: ~Copyable { + public typealias BorrowingIterator_ = Span.BorrowingIterator_ + + @inlinable + public var underestimatedCount_: Int { count } + + @_lifetime(borrow self) + @inlinable + public func makeBorrowingIterator_() -> BorrowingIterator_ { + BorrowingIterator_(self.span) + } +} + +#endif diff --git a/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift b/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift index 52d2723c..c16a28c3 100644 --- a/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift +++ b/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift @@ -17,11 +17,14 @@ import InternalCollectionsUtilities #endif +@available(SwiftStdlib 6.4, *) extension MutableSpan: RandomAccessContainer where Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(borrow self) - public func makeBorrowingIterator(from start: Int) -> SpanIterator { - var it = SpanIterator(self.span) + public func makeBorrowingIterator( + from start: Int + ) -> BorrowingIterator_ { + var it = Span.BorrowingIterator_(self.span) var remainder = start while remainder > 0 { let d = it.skip_(by: remainder) @@ -32,7 +35,9 @@ extension MutableSpan: RandomAccessContainer where Element: ~Copyable { } @_alwaysEmitIntoClient - public func currentIndex(of iterator: borrowing SpanIterator) -> Int { + public func currentIndex( + of iterator: borrowing BorrowingIterator_ + ) -> Int { precondition( self.span.isTriviallyIdentical(to: iterator._span), "Invalid iterator") @@ -72,6 +77,7 @@ extension MutableSpan: RandomAccessContainer where Element: ~Copyable { } } +@available(SwiftStdlib 6.4, *) extension MutableSpan: MutableContainer where Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(&self) diff --git a/Sources/ContainersPreview/Conformances/MutableSpan+Iterable.swift b/Sources/ContainersPreview/Conformances/MutableSpan+Iterable.swift new file mode 100644 index 00000000..d736962f --- /dev/null +++ b/Sources/ContainersPreview/Conformances/MutableSpan+Iterable.swift @@ -0,0 +1,35 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.4) && UnstableContainersPreview + +@available(SwiftStdlib 6.4, *) +extension MutableSpan: Iterable_ where Element: ~Copyable { + public typealias BorrowingIterator_ = Span.BorrowingIterator_ + public typealias Element_ = Element + + @inlinable + public var underestimatedCount_: Int { count } + + @_lifetime(borrow self) + @inlinable + public func makeBorrowingIterator_() -> BorrowingIterator_ { + // FIXME: This should be declared to return BorrowingIterator, but it + // clashes with the stdlib's alternate definition: + // error: 'BorrowingIterator' is ambiguous for type lookup in this context + // Two different typealiases with the same name wreaks havoc with inference? + BorrowingIterator_(self.span) + } +} + +#endif diff --git a/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift b/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift index 2368855b..ec0b2171 100644 --- a/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift +++ b/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift @@ -16,7 +16,7 @@ import InternalCollectionsUtilities #endif #if compiler(>=6.2) && UnstableContainersPreview -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension OutputSpan: RandomAccessContainer, MutableContainer where Element: ~Copyable { diff --git a/Sources/ContainersPreview/Conformances/OutputSpan+Iterable.swift b/Sources/ContainersPreview/Conformances/OutputSpan+Iterable.swift new file mode 100644 index 00000000..60f6f170 --- /dev/null +++ b/Sources/ContainersPreview/Conformances/OutputSpan+Iterable.swift @@ -0,0 +1,31 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.4) && UnstableContainersPreview + +@available(SwiftStdlib 6.4, *) +extension OutputSpan: Iterable_ where Element: ~Copyable { + public typealias Element_ = Element + public typealias BorrowingIterator_ = Span.BorrowingIterator_ + + @inlinable + public var underestimatedCount_: Int { count } + + @_lifetime(borrow self) + @inlinable + public func makeBorrowingIterator_() -> BorrowingIterator_ { + BorrowingIterator_(self.span) + } +} + +#endif diff --git a/Sources/ContainersPreview/Conformances/Range+Iterable.swift b/Sources/ContainersPreview/Conformances/Range+Iterable.swift new file mode 100644 index 00000000..d44995dc --- /dev/null +++ b/Sources/ContainersPreview/Conformances/Range+Iterable.swift @@ -0,0 +1,68 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.4) && UnstableContainersPreview + +@available(SwiftStdlib 6.4, *) +extension Range: Iterable_ +where Bound: Strideable, Bound.Stride: SignedInteger +{ + public typealias Element_ = Bound + + @frozen + public struct BorrowingIterator_: BorrowingIteratorProtocol_, ~Copyable { + @usableFromInline + internal var _current: InlineArray<1, Bound> + + @usableFromInline + internal var _end: Bound + + @usableFromInline + internal var _progress: Bool + + @inlinable + internal init(_ base: Range) { + self._current = .init(repeating: base.lowerBound) + self._end = base.upperBound + self._progress = false + } + @inlinable + @_lifetime(&self) + public mutating func nextSpan_(maxCount: Int) -> Span { + if _progress { + _current[0] = _current[0].advanced(by: 1) + } + guard _current[0] < _end else { + _progress = false + return .init() + } + _progress = true + return _current.span + } + } + + @inlinable + public var underestimatedCount_: Int { + guard let count = Int(exactly: lowerBound.distance(to: upperBound)) else { + return 0 + } + return count + } + + @inlinable + public func makeBorrowingIterator_() -> BorrowingIterator_ { + BorrowingIterator_(self) + } +} + +#endif diff --git a/Sources/ContainersPreview/Conformances/Span+Container.swift b/Sources/ContainersPreview/Conformances/Span+Container.swift index 9276491d..ab24c195 100644 --- a/Sources/ContainersPreview/Conformances/Span+Container.swift +++ b/Sources/ContainersPreview/Conformances/Span+Container.swift @@ -13,13 +13,14 @@ #if compiler(>=6.4) && UnstableContainersPreview +@available(SwiftStdlib 6.4, *) extension Span: RandomAccessContainer where Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(borrow self) - public func makeBorrowingIterator(from start: Int) -> SpanIterator { + public func makeBorrowingIterator(from start: Int) -> BorrowingIterator_ { precondition(start >= 0 && start <= self.count, "Index out of bounds") // FIXME: SpanIterator needs to have a direct initializer that takes `start` - var it = SpanIterator(self) + var it = BorrowingIterator_(self) var remainder = start while remainder > 0 { let d = it.skip_(by: remainder) @@ -30,7 +31,7 @@ extension Span: RandomAccessContainer where Element: ~Copyable { } @_alwaysEmitIntoClient - public func currentIndex(of iterator: borrowing SpanIterator) -> Int { + public func currentIndex(of iterator: borrowing BorrowingIterator_) -> Int { // FIXME: SpanIterator needs to have public `base` and `position` properties precondition( self.isTriviallyIdentical(to: iterator._span), diff --git a/Sources/ContainersPreview/Conformances/Span+Iterable.swift b/Sources/ContainersPreview/Conformances/Span+Iterable.swift new file mode 100644 index 00000000..c23f7911 --- /dev/null +++ b/Sources/ContainersPreview/Conformances/Span+Iterable.swift @@ -0,0 +1,79 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.4) && UnstableContainersPreview + +@available(SwiftStdlib 6.4, *) +extension Span: Iterable_ where Element: ~Copyable { + public typealias Element_ = Element + + @inlinable + public var underestimatedCount_: Int { count } + + @inlinable + @_lifetime(borrow self) + public func makeBorrowingIterator_() -> BorrowingIterator_ { + BorrowingIterator_(self) + } +} + +@available(SwiftStdlib 5.0, *) +extension Span where Element: ~Copyable { + /// A borrowing iterator that provides access to the elements of a single + /// span through a `BorrowingIteratorProtocol` interface. + @available(SwiftStdlib 6.4, *) + public struct BorrowingIterator_: + BorrowingIteratorProtocol_, ~Copyable, ~Escapable + { + public typealias Element_ = Element + + @usableFromInline + internal var _span: Span + @usableFromInline + internal var _start: Int + @usableFromInline + internal var _count: Int + + @_lifetime(copy elements) + public init(_ elements: Span) { + _span = elements + _start = 0 + _count = elements.count + } + + @_alwaysEmitIntoClient + @_lifetime(&self) + @_lifetime(self: copy self) + @_transparent + public mutating func nextSpan_(maxCount: Int) -> Span { + let c = Swift.min(maxCount, _count) + defer { + _start &+= c + _count &-= c + } + return _span.extracting(droppingFirst: _start).extracting(first: c) + } + + @_alwaysEmitIntoClient + @_lifetime(self: copy self) + public mutating func skip_(by offset: Int) -> Int { + let c = Swift.min(offset, _count) + defer { + _start &+= c + _count &-= c + } + return c + } + } +} +#endif diff --git a/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+ElementsEqual.swift b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+ElementsEqual.swift index c947c90a..d2f57623 100644 --- a/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+ElementsEqual.swift +++ b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+ElementsEqual.swift @@ -17,7 +17,7 @@ import InternalCollectionsUtilities #if compiler(>=6.4) && UnstableContainersPreview -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension Iterable_ where Self: ~Copyable & ~Escapable, Element_: Equatable, @@ -37,7 +37,7 @@ where } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension Iterable_ where Self: ~Copyable & ~Escapable, @@ -79,7 +79,7 @@ where } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension BorrowingIteratorProtocol_ where Self: ~Copyable & ~Escapable, @@ -173,7 +173,7 @@ where } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension BorrowingIteratorProtocol_ where Self: ~Copyable & ~Escapable, diff --git a/Sources/ContainersPreview/Protocols/Container/BidirectionalContainer.swift b/Sources/ContainersPreview/Protocols/Container/BidirectionalContainer.swift index 6c1e3535..d141dea9 100644 --- a/Sources/ContainersPreview/Protocols/Container/BidirectionalContainer.swift +++ b/Sources/ContainersPreview/Protocols/Container/BidirectionalContainer.swift @@ -13,7 +13,7 @@ #if compiler(>=6.4) && UnstableContainersPreview -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) public protocol BidirectionalContainer: Container, ~Copyable, ~Escapable where Element: ~Copyable, Index: Comparable { @@ -66,7 +66,7 @@ where Element: ~Copyable, Index: Comparable } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension BidirectionalContainer where Self: ~Copyable & ~Escapable, Element: ~Copyable { @inlinable diff --git a/Sources/ContainersPreview/Protocols/Container/Container+SpanwiseZip.swift b/Sources/ContainersPreview/Protocols/Container/Container+SpanwiseZip.swift index 32e53ebd..e5e46726 100644 --- a/Sources/ContainersPreview/Protocols/Container/Container+SpanwiseZip.swift +++ b/Sources/ContainersPreview/Protocols/Container/Container+SpanwiseZip.swift @@ -17,7 +17,7 @@ import InternalCollectionsUtilities #if compiler(>=6.4) && UnstableContainersPreview -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { @_alwaysEmitIntoClient internal func _spanwiseZip( diff --git a/Sources/ContainersPreview/Protocols/Container/Container.swift b/Sources/ContainersPreview/Protocols/Container/Container.swift index ed7be60c..38a7b2bd 100644 --- a/Sources/ContainersPreview/Protocols/Container/Container.swift +++ b/Sources/ContainersPreview/Protocols/Container/Container.swift @@ -13,7 +13,7 @@ #if compiler(>=6.4) && UnstableContainersPreview -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) public protocol Container: Iterable_, ~Copyable, ~Escapable where Element: ~Copyable, Element == Element_, Failure_ == Never @@ -217,7 +217,7 @@ public protocol Container: func _customLastIndexOfEquatableElement(_ element: borrowing Element) -> Index?? } -@available(SwiftStdlib 5.0, *) +@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 /// the given index, and extends to the end of the contiguous storage chunk @@ -260,7 +260,7 @@ extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { @_alwaysEmitIntoClient public var isEmpty: Bool { @@ -422,7 +422,7 @@ extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { @_alwaysEmitIntoClient @_transparent diff --git a/Sources/ContainersPreview/Protocols/Container/DynamicContainer.swift b/Sources/ContainersPreview/Protocols/Container/DynamicContainer.swift index c2b5f6c1..08b2b425 100644 --- a/Sources/ContainersPreview/Protocols/Container/DynamicContainer.swift +++ b/Sources/ContainersPreview/Protocols/Container/DynamicContainer.swift @@ -13,7 +13,7 @@ #if compiler(>=6.4) && UnstableContainersPreview -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) public protocol DynamicContainer: RangeReplaceableContainer, ~Copyable where Element: ~Copyable { @@ -41,7 +41,7 @@ where Element: ~Copyable var freeCapacity: Int { get } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension DynamicContainer where Self: ~Copyable, Element: ~Copyable { @_alwaysEmitIntoClient public init() { @@ -104,7 +104,7 @@ extension DynamicContainer where Self: ~Copyable, Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension DynamicContainer where Self: ~Copyable, Element: Copyable { @_alwaysEmitIntoClient public init(repeating repeatedValue: Element, count: Int) { diff --git a/Sources/ContainersPreview/Protocols/Container/MutableContainer.swift b/Sources/ContainersPreview/Protocols/Container/MutableContainer.swift index c0000f95..2cc9b208 100644 --- a/Sources/ContainersPreview/Protocols/Container/MutableContainer.swift +++ b/Sources/ContainersPreview/Protocols/Container/MutableContainer.swift @@ -13,7 +13,7 @@ #if compiler(>=6.4) && UnstableContainersPreview -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) public protocol MutableContainer: PermutableContainer, ~Copyable, ~Escapable where @@ -97,7 +97,7 @@ where ) -> MutableSpan } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension MutableContainer where Self: ~Copyable & ~Escapable, Element: ~Copyable { diff --git a/Sources/ContainersPreview/Protocols/Container/PermutableContainer.swift b/Sources/ContainersPreview/Protocols/Container/PermutableContainer.swift index 8cfe7224..cf96d0e9 100644 --- a/Sources/ContainersPreview/Protocols/Container/PermutableContainer.swift +++ b/Sources/ContainersPreview/Protocols/Container/PermutableContainer.swift @@ -13,7 +13,7 @@ #if compiler(>=6.4) && UnstableContainersPreview -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) public protocol PermutableContainer: Container, ~Copyable, ~Escapable where Element: ~Copyable { diff --git a/Sources/ContainersPreview/Protocols/Container/RandomAccessContainer.swift b/Sources/ContainersPreview/Protocols/Container/RandomAccessContainer.swift index c77801ad..5443bb20 100644 --- a/Sources/ContainersPreview/Protocols/Container/RandomAccessContainer.swift +++ b/Sources/ContainersPreview/Protocols/Container/RandomAccessContainer.swift @@ -13,7 +13,7 @@ #if compiler(>=6.4) && UnstableContainersPreview -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) public protocol RandomAccessContainer : BidirectionalContainer, ~Copyable, ~Escapable where Element: ~Copyable { @@ -70,7 +70,7 @@ extension RandomAccessCollection { } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension RandomAccessContainer where Self: ~Copyable & ~Escapable, @@ -129,7 +129,7 @@ where } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension RandomAccessContainer where Self: ~Copyable & ~Escapable, @@ -198,7 +198,7 @@ where // Disambiguate parallel extensions on RandomAccessContainer and RandomAccessCollection -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension RandomAccessCollection where Self: RandomAccessContainer, diff --git a/Sources/ContainersPreview/Protocols/Container/RangeExpression2.swift b/Sources/ContainersPreview/Protocols/Container/RangeExpression2.swift index c847d61d..84c61e8d 100644 --- a/Sources/ContainersPreview/Protocols/Container/RangeExpression2.swift +++ b/Sources/ContainersPreview/Protocols/Container/RangeExpression2.swift @@ -15,7 +15,7 @@ // FIXME: Figure out if it would be possible to add the container-based // `relative(to:)` to the existing `RangeExpression`. -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) public protocol RangeExpression2: RangeExpression { override associatedtype Bound: Comparable @@ -26,7 +26,7 @@ public protocol RangeExpression2: RangeExpression { override func contains(_ element: Bound) -> Bool } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension Range: RangeExpression2 { @inlinable public func relative( @@ -36,7 +36,7 @@ extension Range: RangeExpression2 { } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension ClosedRange: RangeExpression2 { @inlinable public func relative( @@ -47,7 +47,7 @@ extension ClosedRange: RangeExpression2 { } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension PartialRangeFrom: RangeExpression2 { @inlinable public func relative( @@ -57,7 +57,7 @@ extension PartialRangeFrom: RangeExpression2 { } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension PartialRangeUpTo: RangeExpression2 { @inlinable public func relative( @@ -67,7 +67,7 @@ extension PartialRangeUpTo: RangeExpression2 { } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension PartialRangeThrough: RangeExpression2 { @inlinable public func relative( diff --git a/Sources/ContainersPreview/Protocols/Container/RangeReplaceableContainer.swift b/Sources/ContainersPreview/Protocols/Container/RangeReplaceableContainer.swift index 3b93a057..dd032b47 100644 --- a/Sources/ContainersPreview/Protocols/Container/RangeReplaceableContainer.swift +++ b/Sources/ContainersPreview/Protocols/Container/RangeReplaceableContainer.swift @@ -19,7 +19,7 @@ import InternalCollectionsUtilities //MARK: - Protocol Definition -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) public protocol RangeReplaceableContainer : Container, ~Copyable, ~Escapable where @@ -70,7 +70,7 @@ where //MARK: - Default Implementations -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension RangeReplaceableContainer where Self: ~Copyable & ~Escapable, Element: ~Copyable { @@ -170,7 +170,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable //MARK: - Standard Extensions -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension RangeReplaceableContainer where Self: ~Copyable & ~Escapable, Element: ~Copyable { @@ -291,7 +291,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension RangeReplaceableContainer where Self: ~Copyable & ~Escapable, Element: ~Copyable { @_alwaysEmitIntoClient @@ -353,7 +353,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension RangeReplaceableContainer where Self: BidirectionalContainer, @@ -373,7 +373,7 @@ where } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension RangeReplaceableContainer where Self: ~Copyable & ~Escapable, Element: ~Copyable { @@ -397,7 +397,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension RangeReplaceableContainer where Self: BidirectionalContainer & ~Copyable & ~Escapable, Element: ~Copyable { @@ -427,7 +427,7 @@ where Self: BidirectionalContainer & ~Copyable & ~Escapable, Element: ~Copyable } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension RangeReplaceableContainer where Self: BidirectionalContainer & ~Copyable & ~Escapable, Element: ~Copyable { @@ -439,7 +439,7 @@ where Self: BidirectionalContainer & ~Copyable & ~Escapable, Element: ~Copyable } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension RangeReplaceableContainer where Self: ~Copyable & ~Escapable, Element: ~Copyable { @@ -556,7 +556,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension RangeReplaceableContainer where Self: ~Copyable & ~Escapable, Element: ~Copyable { /// Appends at most `newItemCount` items generated by a producer to the end of @@ -663,7 +663,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { //MARK: - Standard Extensions Requiring Copyability -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension RangeReplaceableContainer where Self: ~Copyable & ~Escapable, diff --git a/Sources/ContainersPreview/Protocols/Iterable+Algorithms.swift b/Sources/ContainersPreview/Protocols/Iterable+Algorithms.swift index 92ecd192..01780d9c 100644 --- a/Sources/ContainersPreview/Protocols/Iterable+Algorithms.swift +++ b/Sources/ContainersPreview/Protocols/Iterable+Algorithms.swift @@ -13,7 +13,7 @@ #if compiler(>=6.4) && UnstableContainersPreview -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension Iterable_ where Self: ~Copyable & ~Escapable, Element_: ~Copyable { @@ -37,7 +37,7 @@ extension Iterable_ } // Ambiguity breakers -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension Sequence where Self: Iterable_ { public func reduce( _ initialResult: consuming Result, @@ -57,7 +57,7 @@ extension Sequence where Self: Iterable_ { } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension Iterable_ where Self: ~Copyable & ~Escapable, Element_: ~Copyable { @@ -92,7 +92,7 @@ extension Iterable_ } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension Iterable_ where Self: ~Copyable & ~Escapable, Element_: ~Copyable & Equatable { @inlinable diff --git a/Sources/ContainersPreview/Protocols/Iterable+Standard Conformances.swift b/Sources/ContainersPreview/Protocols/Iterable+Standard Conformances.swift deleted file mode 100644 index 6fd17844..00000000 --- a/Sources/ContainersPreview/Protocols/Iterable+Standard Conformances.swift +++ /dev/null @@ -1,223 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// 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 -// -// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception -// -//===----------------------------------------------------------------------===// - -#if compiler(>=6.4) && UnstableContainersPreview - -@available(SwiftStdlib 5.0, *) -extension Span: Iterable_ where Element: ~Copyable { - public typealias BorrowingIterator_ = SpanIterator - public typealias Element_ = Element - - @inlinable - public var underestimatedCount_: Int { count } - - @_lifetime(borrow self) - @inlinable - public func makeBorrowingIterator_() -> SpanIterator { - SpanIterator(self) - } -} - -@available(SwiftStdlib 5.0, *) -extension MutableSpan: Iterable_ where Element: ~Copyable { - public typealias BorrowingIterator_ = SpanIterator - public typealias Element_ = Element - - @inlinable - public var underestimatedCount_: Int { count } - - @_lifetime(borrow self) - @inlinable - public func makeBorrowingIterator_() -> SpanIterator { - // FIXME: This should be declared to return BorrowingIterator, but it - // clashes with the stdlib's alternate definition: - // error: 'BorrowingIterator' is ambiguous for type lookup in this context - // Two different typealiases with the same name wreaks havoc with inference? - SpanIterator(self.span) - } -} - -@available(SwiftStdlib 5.0, *) -extension OutputSpan: Iterable_ where Element: ~Copyable { - public typealias BorrowingIterator_ = SpanIterator - - @inlinable - public var underestimatedCount_: Int { count } - - @_lifetime(borrow self) - @inlinable - public func makeBorrowingIterator_() -> BorrowingIterator_ { - SpanIterator(self.span) - } -} - -@available(SwiftStdlib 5.0, *) -extension InputSpan: Iterable_ where Element: ~Copyable { - public typealias BorrowingIterator_ = SpanIterator - - @inlinable - public var underestimatedCount_: Int { count } - - @_lifetime(borrow self) - @inlinable - public func makeBorrowingIterator_() -> BorrowingIterator_ { - SpanIterator(self.span) - } -} - -@available(SwiftStdlib 6.2, *) -extension Array: Iterable_ { - public typealias BorrowingIterator_ = SpanIterator - - @inlinable - public var underestimatedCount_: Int { count } - - @_lifetime(borrow self) - @inlinable - public func makeBorrowingIterator_() -> BorrowingIterator_ { - SpanIterator(self.span) - } -} - -@available(SwiftStdlib 6.2, *) -extension InlineArray: Iterable_ where Element: ~Copyable { - public typealias BorrowingIterator_ = SpanIterator - - @inlinable - public var underestimatedCount_: Int { count } - - @_lifetime(borrow self) - @inlinable - public func makeBorrowingIterator_() -> SpanIterator { - // FIXME: This should be declared to return BorrowingIterator, but it - // clashes with the stdlib's alternate definition: - // error: 'BorrowingIterator' is ambiguous for type lookup in this context - // Two different typealiases with the same name wreaks havoc with inference? - SpanIterator(self.span) - } -} - -@available(SwiftStdlib 6.2, *) -extension Range: Iterable_ -where Bound: Strideable, Bound.Stride: SignedInteger -{ - public typealias Element = Bound - - @frozen - public struct BorrowingIterator_: BorrowingIteratorProtocol_, ~Copyable { - @usableFromInline - internal var _current: InlineArray<1, Bound> - - @usableFromInline - internal var _end: Bound - - @usableFromInline - internal var _progress: Bool - - @inlinable - internal init(_ base: Range) { - self._current = .init(repeating: base.lowerBound) - self._end = base.upperBound - self._progress = false - } - @inlinable - @_lifetime(&self) - public mutating func nextSpan_(maxCount: Int) -> Span { - if _progress { - _current[0] = _current[0].advanced(by: 1) - } - guard _current[0] < _end else { - _progress = false - return .init() - } - _progress = true - return _current.span - } - } - - @_alwaysEmitIntoClient - @_transparent - package var _borrowingUnderestimatedCount: Int { - guard let count = Int(exactly: lowerBound.distance(to: upperBound)) else { - return 0 - } - return count - } - - @inlinable - public var underestimatedCount_: Int { _borrowingUnderestimatedCount } - - @inlinable - public func makeBorrowingIterator_() -> BorrowingIterator_ { - BorrowingIterator_(self) - } -} - -@available(SwiftStdlib 6.2, *) -extension ClosedRange: Iterable_ -where Bound: Strideable, Bound.Stride: SignedInteger -{ - public typealias Element = Bound - - @frozen - public struct BorrowingIterator_: BorrowingIteratorProtocol_, ~Copyable { - @usableFromInline - internal var _current: InlineArray<1, Bound> - - @usableFromInline - internal var _last: Bound - - @usableFromInline - internal var _progress: Bool - - @inlinable - internal init(_ base: ClosedRange) { - self._current = .init(repeating: base.lowerBound) - self._last = base.upperBound - self._progress = false - } - @inlinable - @_lifetime(&self) - public mutating func nextSpan_(maxCount: Int) -> Span { - if _progress { - _current[0] = _current[0].advanced(by: 1) - } - guard _current[0] <= _last else { - _progress = false - return .init() - } - _progress = true - return _current.span - } - } - - @_alwaysEmitIntoClient - @_transparent - package var _borrowingUnderestimatedCount: Int { - guard let distance = Int(exactly: lowerBound.distance(to: upperBound)) - else { return 0 } - let advanced = distance.addingReportingOverflow(1) - guard !advanced.overflow else { return 0 } - return advanced.partialValue - } - - @inlinable - public var underestimatedCount_: Int { _borrowingUnderestimatedCount } - - @inlinable - public func makeBorrowingIterator_() -> BorrowingIterator_ { - BorrowingIterator_(self) - } -} - -#endif diff --git a/Sources/ContainersPreview/Protocols/Iterable+Utilities.swift b/Sources/ContainersPreview/Protocols/Iterable+Utilities.swift index f2cb3053..b1f4de7a 100644 --- a/Sources/ContainersPreview/Protocols/Iterable+Utilities.swift +++ b/Sources/ContainersPreview/Protocols/Iterable+Utilities.swift @@ -17,7 +17,7 @@ import InternalCollectionsUtilities #if compiler(>=6.4) && UnstableContainersPreview -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension Iterable_ where Self: ~Copyable & ~Escapable, Element_: Copyable { @inlinable package func _copyContents( diff --git a/Sources/ContainersPreview/Protocols/Iterable.swift b/Sources/ContainersPreview/Protocols/Iterable.swift index 380262d9..e6c97554 100644 --- a/Sources/ContainersPreview/Protocols/Iterable.swift +++ b/Sources/ContainersPreview/Protocols/Iterable.swift @@ -13,8 +13,14 @@ #if compiler(>=6.4) && UnstableContainersPreview -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) public protocol Iterable_: ~Copyable, ~Escapable { + // FIXME: None of these names should not have trailing underscores, but that + // would clash with the stdlib's versions: + // error: 'BorrowingIterator' is ambiguous for type lookup in this context + // + // This is likely best resolved by removing these definitions as soon as they + // appear in the stdlib. associatedtype Element_: ~Copyable associatedtype Failure_: Error = Never @@ -30,7 +36,7 @@ public protocol Iterable_: ~Copyable, ~Escapable { ) -> Bool? } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension Iterable_ where Self: ~Copyable & ~Escapable, Element_: ~Copyable @@ -44,7 +50,7 @@ where } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension Iterable_ where Self: Sequence { @inlinable public var underestimatedCount_: Int { 0 } diff --git a/Sources/ContainersPreview/Protocols/Producer+Collect.swift b/Sources/ContainersPreview/Protocols/Producer+Collect.swift index a1d169dd..da3caf38 100644 --- a/Sources/ContainersPreview/Protocols/Producer+Collect.swift +++ b/Sources/ContainersPreview/Protocols/Producer+Collect.swift @@ -15,6 +15,7 @@ @available(SwiftStdlib 5.0, *) extension Producer where Self: ~Copyable & ~Escapable, Element: ~Copyable { + @available(SwiftStdlib 6.4, *) @inlinable public consuming func collect< R: DynamicContainer & ~Copyable @@ -27,6 +28,7 @@ extension Producer where Self: ~Copyable & ~Escapable, Element: ~Copyable { /// Collect all items generated by this producer into the provided /// range-replaceable container instance, which must be able to accommodate /// every new element. + @available(SwiftStdlib 6.4, *) @inlinable public consuming func collect( into container: inout some RangeReplaceableContainer & ~Copyable & ~Escapable @@ -49,6 +51,7 @@ extension Producer where Self: ~Copyable & ~Escapable, Element: ~Copyable { /// Collect all items generated by this producer into the provided /// dynamic container instance, resizing it if necessary. + @available(SwiftStdlib 6.4, *) @inlinable public consuming func collect( into container: inout some DynamicContainer & ~Copyable diff --git a/Sources/ContainersPreview/Types/SpanIterator.swift b/Sources/ContainersPreview/Types/SpanIterator.swift deleted file mode 100644 index 6e59e785..00000000 --- a/Sources/ContainersPreview/Types/SpanIterator.swift +++ /dev/null @@ -1,61 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// 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 -// -// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception -// -//===----------------------------------------------------------------------===// - -#if compiler(>=6.4) && UnstableContainersPreview - -/// A borrowing iterator that provides access to the elements of a single -/// span through a `BorrowingIteratorProtocol` interface. -@available(SwiftStdlib 5.0, *) -public struct SpanIterator: BorrowingIteratorProtocol_, ~Copyable, ~Escapable - where Element_: ~Copyable -{ - @usableFromInline - internal var _span: Span - @usableFromInline - internal var _start: Int - @usableFromInline - internal var _count: Int - - @_lifetime(copy elements) - public init(_ elements: Span) { - _span = elements - _start = 0 - _count = elements.count - } - - @_alwaysEmitIntoClient - @_lifetime(&self) - @_lifetime(self: copy self) - @_transparent - public mutating func nextSpan_(maxCount: Int) -> Span { - let c = Swift.min(maxCount, _count) - defer { - _start &+= c - _count &-= c - } - return _span.extracting(droppingFirst: _start).extracting(first: c) - } - - @_alwaysEmitIntoClient - @_lifetime(self: copy self) - public mutating func skip_(by offset: Int) -> Int { - let c = Swift.min(offset, _count) - defer { - _start &+= c - _count &-= c - } - return c - } -} - -#endif diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Append.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Append.swift index 229e31a8..98193fac 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Append.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Append.swift @@ -311,6 +311,7 @@ extension RigidDeque /*where Element: Copyable*/ { } #if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient internal mutating func _append< S: Iterable_ & ~Copyable & ~Escapable @@ -334,6 +335,7 @@ extension RigidDeque /*where Element: Copyable*/ { /// - newElements: The new elements to copy into the deque. /// /// - Complexity: O(*m*), where *m* is the length of `newElements`. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient public mutating func append( copying newElements: borrowing S @@ -375,6 +377,7 @@ extension RigidDeque /*where Element: Copyable*/ { /// - items: The new elements to copy into the deque. /// /// - Complexity: O(*m*), where *m* is the length of `items`. @available(SwiftStdlib 5.0, *) + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient public mutating func append< S: Iterable_ & Sequence diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Equatable.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Equatable.swift index 6b82a90b..8935f6db 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Equatable.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Equatable.swift @@ -40,13 +40,14 @@ extension RigidDeque where Element: Equatable & ~Copyable { guard !left.isTriviallyIdentical(to: right) else { return true } #if compiler(>=6.4) && UnstableContainersPreview - return left._elementsEqual(right) -#else + if #available(anyAppleOS 27, *) { + return left._elementsEqual(right) + } +#endif for i in 0 ..< left.count { guard left[i] == right[i] else { return false } } return true -#endif } } diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Initializers.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Initializers.swift index fb1a09f8..f5f8bb00 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Initializers.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Initializers.swift @@ -129,6 +129,7 @@ extension RigidDeque /*where Element: Copyable*/ { /// - capacity: The storage capacity of the new deque. /// - contents: A sequence whose contents to copy into the new deque. /// The sequence must not contain more than `capacity` elements. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient @inline(__always) public init( @@ -183,6 +184,7 @@ extension RigidDeque /*where Element: Copyable*/ { /// - capacity: The storage capacity of the new deque. /// - contents: A sequence whose contents to copy into the new deque. /// The sequence must not contain more than `capacity` elements. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient @inline(__always) public init>( @@ -193,7 +195,9 @@ extension RigidDeque /*where Element: Copyable*/ { self.init(capacity: capacity) try self._append(copying: contents) } +#endif +#if compiler(>=6.4) && UnstableContainersPreview /// Creates a new deque with the specified capacity, holding a copy /// of the contents of a given collection. /// @@ -203,6 +207,7 @@ extension RigidDeque /*where Element: Copyable*/ { /// than or equal to the count of the collection. /// - contents: A collection whose contents to copy into the new deque. /// The sequence must not contain more than `capacity` elements. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient @inline(__always) public init>( diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift index f68a6235..d3c2f951 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift @@ -356,6 +356,7 @@ extension RigidDeque /* where Element: Copyable */ { } #if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) @inlinable internal mutating func _insertContainer< C: Container & ~Copyable & ~Escapable @@ -418,6 +419,7 @@ extension RigidDeque /* where Element: Copyable */ { /// a valid index of the deque. /// /// - Complexity: O(`self.count` + `items.count`). + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient @inline(__always) public mutating func insert< @@ -480,6 +482,7 @@ extension RigidDeque /* where Element: Copyable */ { /// a valid index of the deque. /// /// - Complexity: O(`self.count` + `items.count`) + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient @inline(__always) public mutating func insert< diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift index c31d5496..7ed7e432 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift @@ -288,6 +288,7 @@ extension RigidDeque /*where Element: Copyable*/ { } #if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) @inlinable internal mutating func _prepend< S: Iterable_ & ~Copyable & ~Escapable @@ -307,6 +308,7 @@ extension RigidDeque /*where Element: Copyable*/ { _handle.rotate(toStartAtOffset: oldCount) } + @available(SwiftStdlib 6.4, *) @inlinable internal mutating func _prepend< S: Iterable_ & ~Copyable & ~Escapable @@ -336,6 +338,7 @@ extension RigidDeque /*where Element: Copyable*/ { /// - items: The new elements to copy into the deque. /// /// - Complexity: O(*m*), where *m* is the length of `items`. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient public mutating func prepend( copying items: borrowing S @@ -354,6 +357,7 @@ extension RigidDeque /*where Element: Copyable*/ { /// - items: The new elements to copy into the deque. /// /// - Complexity: O(`items.count`) + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient public mutating func prepend & ~Copyable & ~Escapable>( copying items: borrowing C @@ -441,6 +445,7 @@ extension RigidDeque /*where Element: Copyable*/ { /// - items: The new elements to copy into the deque. /// /// - Complexity: O(*m*), where *m* is the length of `items`. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient public mutating func prepend>( copying items: borrowing S @@ -458,6 +463,7 @@ extension RigidDeque /*where Element: Copyable*/ { /// - items: The new elements to copy into the deque. /// /// - Complexity: O(*m*), where *m* is the length of `items`. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient public mutating func prepend>( copying items: borrowing S @@ -475,6 +481,7 @@ extension RigidDeque /*where Element: Copyable*/ { /// - items: The new elements to copy into the deque. /// /// - Complexity: O(*m*), where *m* is the length of `items`. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient public mutating func prepend & Sequence>( copying items: borrowing C @@ -491,6 +498,7 @@ extension RigidDeque /*where Element: Copyable*/ { /// - items: The new elements to copy into the deque. /// /// - Complexity: O(*m*), where *m* is the length of `items`. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient public mutating func prepend & Collection>( copying items: borrowing C diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Removals.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Removals.swift index ea5c1d1a..09ef16db 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Removals.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Removals.swift @@ -153,7 +153,6 @@ extension RigidDeque where Element: ~Copyable { return _handle.uncheckedRemoveFirst() } -#if !UnstableContainersPreview /// Removes and returns the last element of the deque, if there is one. /// /// - Returns: The last element of the original deque if it was not empty; @@ -162,10 +161,11 @@ extension RigidDeque where Element: ~Copyable { /// - Complexity: O(1) @_alwaysEmitIntoClient public mutating func popLast() -> Element? { + // FIXME: Remove this algorithm; it is already provided by + // RangeReplaceableContainer, albeit with stricter availability. guard !isEmpty else { return nil } return _handle.uncheckedRemoveLast() } -#endif } #endif diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift index ad64df6a..1e44dcb2 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift @@ -456,6 +456,7 @@ extension RigidDeque /* where Element: Copyable */ { } #if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) @inlinable internal mutating func _replace< C: Container & ~Copyable & ~Escapable @@ -529,6 +530,7 @@ extension RigidDeque /* where Element: Copyable */ { /// - items: The new elements to copy into the collection. /// /// - Complexity: O(`self.count` + `items.count`) + @available(SwiftStdlib 6.4, *) @inlinable @inline(__always) public mutating func replace< @@ -606,6 +608,7 @@ extension RigidDeque /* where Element: Copyable */ { /// /// - Complexity: O(*n* + *m*), where *n* is count of this deque and /// *m* is the count of `items`. + @available(SwiftStdlib 6.4, *) @inlinable @inline(__always) public mutating func replace< diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Append.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Append.swift index 58ced3b3..d4a36811 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Append.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Append.swift @@ -298,6 +298,7 @@ extension UniqueDeque /*where Element: Copyable*/ { } #if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient internal mutating func _append( copying items: borrowing S @@ -323,6 +324,7 @@ extension UniqueDeque /*where Element: Copyable*/ { /// /// - Complexity: O(*m*), where *m* is the length of `items`, when amortized /// over many similar invocations on the same deque + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient public mutating func append( copying items: borrowing S @@ -374,6 +376,7 @@ extension UniqueDeque /*where Element: Copyable*/ { /// /// - Complexity: O(*m*), where *m* is the length of `items`, when /// amortized over many similar invocations over the same deque. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient public mutating func append>( copying items: S diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Initializers.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Initializers.swift index ec6eb187..0d52fb11 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Initializers.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Initializers.swift @@ -142,6 +142,7 @@ extension UniqueDeque /*where Element: Copyable*/ { /// - capacity: The storage capacity of the new deque, or nil to let the /// deque grow itself as needed to accomodate all items in `contents`. /// - contents: A sequence whose contents to copy into the new deque. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient @inline(__always) public init( @@ -180,6 +181,7 @@ extension UniqueDeque /*where Element: Copyable*/ { /// deque grow itself as needed to accomodate all items in `contents`. /// - contents: A sequence whose contents to copy into the new deque. /// The sequence must not contain more than `capacity` elements. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient @inline(__always) public init>( @@ -198,6 +200,7 @@ extension UniqueDeque /*where Element: Copyable*/ { /// - capacity: The storage capacity of the new deque. /// - contents: A sequence whose contents to copy into the new deque. /// The sequence must not contain more than `capacity` elements. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient @inline(__always) public init>( diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Insertions.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Insertions.swift index c452c931..813ddf21 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Insertions.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Insertions.swift @@ -374,6 +374,7 @@ extension UniqueDeque /* where Element: Copyable */ { } #if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) @inlinable internal mutating func _insertContainer< C: Container & ~Copyable & ~Escapable @@ -439,6 +440,7 @@ extension UniqueDeque /* where Element: Copyable */ { /// /// - Complexity: O(`self.count` + `items.count`) when amortized over many /// similar invocations on the same deque. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient @inline(__always) public mutating func insert< @@ -505,6 +507,7 @@ extension UniqueDeque /* where Element: Copyable */ { /// /// - Complexity: O(`self.count` + `items.count`) when amortized over many /// similar invocations on the same deque. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient @inline(__always) public mutating func insert< diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift index 62aa8de1..45e5da0a 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift @@ -320,6 +320,7 @@ extension UniqueDeque /*where Element: Copyable*/ { } #if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) @inlinable internal mutating func _prepend( copying items: borrowing S @@ -338,6 +339,7 @@ extension UniqueDeque /*where Element: Copyable*/ { _storage._handle.rotate(toStartAtOffset: oldCount) } + @available(SwiftStdlib 6.4, *) @inlinable internal mutating func _prepend( copying items: borrowing S, @@ -366,6 +368,7 @@ extension UniqueDeque /*where Element: Copyable*/ { /// /// - Complexity: O(*m*), where *m* is the length of `items`, as amortized /// over many similar invocations on the same deque. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient public mutating func prepend( copying items: borrowing S @@ -385,6 +388,7 @@ extension UniqueDeque /*where Element: Copyable*/ { /// /// - Complexity: O(`items.count`) when amortized over many similar /// invocations on the same deque. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient public mutating func prepend & ~Copyable & ~Escapable>( copying items: borrowing C @@ -477,6 +481,7 @@ extension UniqueDeque /*where Element: Copyable*/ { /// /// - Complexity: O(*m*), where *m* is the length of `items`, as amortized /// over many similar invocations on the same deque. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient public mutating func prepend>( copying items: borrowing S @@ -495,6 +500,7 @@ extension UniqueDeque /*where Element: Copyable*/ { /// /// - Complexity: O(*m*), where *m* is the length of `items` when amortized /// over many similar invocations on the same deque. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient public mutating func prepend>( copying items: borrowing S @@ -513,6 +519,7 @@ extension UniqueDeque /*where Element: Copyable*/ { /// /// - Complexity: O(*m*), where *m* is the length of `items` when amortized /// over many similar invocations on the same deque. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient public mutating func prepend & Sequence>( copying items: borrowing C @@ -530,6 +537,7 @@ extension UniqueDeque /*where Element: Copyable*/ { /// /// - Complexity: O(*m*), where *m* is the length of `items` when amortized /// over many similar invocations on the same deque. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient public mutating func prepend & Collection>( copying items: C diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Removals.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Removals.swift index c86c82a5..302b0934 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Removals.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Removals.swift @@ -136,7 +136,6 @@ extension UniqueDeque where Element: ~Copyable { _storage.popFirst() } -#if !UnstableContainersPreview /// Removes and returns the last element of the deque, if there is one. /// /// - Returns: The last element of the original deque if it was not empty; @@ -146,9 +145,10 @@ extension UniqueDeque where Element: ~Copyable { @_alwaysEmitIntoClient @inline(__always) public mutating func popLast() -> Element? { + // FIXME: Remove this algorithm; it is already provided by + // RangeReplaceableContainer, albeit with stricter availability. _storage.popLast() } -#endif } #endif diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Replacements.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Replacements.swift index 75d6d47f..ca0579ad 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Replacements.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Replacements.swift @@ -465,6 +465,7 @@ extension UniqueDeque /* where Element: Copyable */ { } #if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) @inlinable internal mutating func _replace< C: Container & ~Copyable & ~Escapable @@ -539,6 +540,7 @@ extension UniqueDeque /* where Element: Copyable */ { /// - items: The new elements to copy into the collection. /// /// - Complexity: O(`self.count` + `items.count`) + @available(SwiftStdlib 6.4, *) @inlinable @inline(__always) public mutating func replace< @@ -618,6 +620,7 @@ extension UniqueDeque /* where Element: Copyable */ { /// /// - Complexity: O(*n* + *m*), where *n* is count of this deque and /// *m* is the count of `items`. + @available(SwiftStdlib 6.4, *) @inlinable @inline(__always) public mutating func replace< diff --git a/Tests/BasicContainersTests/RigidArrayTests.swift b/Tests/BasicContainersTests/RigidArrayTests.swift index 01a7cc96..617a9893 100644 --- a/Tests/BasicContainersTests/RigidArrayTests.swift +++ b/Tests/BasicContainersTests/RigidArrayTests.swift @@ -74,7 +74,9 @@ class RigidArrayTests: CollectionTestCase { expectEqual(tracker.instances, 2 * layout.count) expectRigidArrayContents(items, equalTo: expected) #if compiler(>=6.4) && UnstableContainersPreview - checkIterable(items, expectedContents: expected) + if #available(SwiftStdlib 6.4, *) { + checkIterable(items, expectedContents: expected) + } #endif } } @@ -1206,6 +1208,7 @@ class RigidArrayTests: CollectionTestCase { } #if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) func test_insert_copying_Container() { withSomeArrayLayouts("layout", ofCapacities: [0, 5, 10]) { layout in withEvery("i", in: 0 ... layout.count) { i in @@ -1438,6 +1441,7 @@ class RigidArrayTests: CollectionTestCase { } #if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) func test_replace_Container() { withSomeArrayLayouts("layout", ofCapacities: [0, 5, 10]) { layout in withEveryRange("range", in: 0 ..< layout.count) { range in diff --git a/Tests/BasicContainersTests/UniqueArrayTests.swift b/Tests/BasicContainersTests/UniqueArrayTests.swift index a1af5e0f..3571c02b 100644 --- a/Tests/BasicContainersTests/UniqueArrayTests.swift +++ b/Tests/BasicContainersTests/UniqueArrayTests.swift @@ -76,7 +76,9 @@ class UniqueArrayTests: CollectionTestCase { expectEqual(tracker.instances, 2 * layout.count) expectUniqueArrayContents(items, equalTo: expected) #if compiler(>=6.4) && UnstableContainersPreview - checkIterable(items, expectedContents: expected) + if #available(SwiftStdlib 6.4, *) { + checkIterable(items, expectedContents: expected) + } #endif } } diff --git a/Tests/ContainersTests/BorrowingSequenceTests.swift b/Tests/ContainersTests/BorrowingSequenceTests.swift index bafe236c..f89a48fa 100644 --- a/Tests/ContainersTests/BorrowingSequenceTests.swift +++ b/Tests/ContainersTests/BorrowingSequenceTests.swift @@ -22,7 +22,7 @@ import ContainersPreview #if compiler(>=6.4) && UnstableContainersPreview final class IterableTests: XCTestCase { - @available(SwiftStdlib 6.2, *) + @available(SwiftStdlib 6.4, *) func testBasic() { let array = [1, 2, 3, 4, 5, 6, 7, 8] @@ -63,7 +63,7 @@ final class IterableTests: XCTestCase { } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension Iterable_ where Self: ~Copyable & ~Escapable, Element_: Copyable { func collectViaBorrowing() throws(Failure_) -> [Element_] { var borrowIterator = makeBorrowingIterator_() diff --git a/Tests/DequeTests/RigidDequeTests.swift b/Tests/DequeTests/RigidDequeTests.swift index b558f4c7..0a3ce02d 100644 --- a/Tests/DequeTests/RigidDequeTests.swift +++ b/Tests/DequeTests/RigidDequeTests.swift @@ -82,16 +82,19 @@ internal func expectRigidDequeContents< line: UInt = #line ) { #if compiler(>=6.4) && UnstableContainersPreview - expectIterableContents( - left, - equivalentTo: right, - by: areEquivalent, - printer: printer, - message(), - trapping: trapping, - file: file, - line: line) -#else + if #available(SwiftStdlib 6.4, *) { + expectIterableContents( + left, + equivalentTo: right, + by: areEquivalent, + printer: printer, + message(), + trapping: trapping, + file: file, + line: line) + return + } +#endif var c = 0 var j = right.startIndex for i in 0 ..< left.count { @@ -106,7 +109,6 @@ internal func expectRigidDequeContents< right.formIndex(after: &j) c += 1 } -#endif } final class RigidDequeTests: CollectionTestCase { @@ -424,6 +426,7 @@ final class RigidDequeTests: CollectionTestCase { } #if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) func test_initCopyingBorrowingSequence() { withEvery("c", in: 0 ..< 10) { c in withEvery("capacity", in: [c, c + 1]) { capacity in @@ -534,7 +537,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_popLast() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withLifetimeTracking { tracker in @@ -1274,6 +1277,7 @@ final class RigidDequeTests: CollectionTestCase { } #if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) func test_insert_RigidArray() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withEvery("i", in: 0 ... layout.count) { i in diff --git a/Tests/DequeTests/UniqueDequeTests.swift b/Tests/DequeTests/UniqueDequeTests.swift index 08774ba3..3df8d6bb 100644 --- a/Tests/DequeTests/UniqueDequeTests.swift +++ b/Tests/DequeTests/UniqueDequeTests.swift @@ -82,16 +82,19 @@ internal func expectUniqueDequeContents< line: UInt = #line ) { #if compiler(>=6.4) && UnstableContainersPreview - expectIterableContents( - left, - equivalentTo: right, - by: areEquivalent, - printer: printer, - message(), - trapping: trapping, - file: file, - line: line) -#else + if #available(SwiftStdlib 6.4, *) { + expectIterableContents( + left, + equivalentTo: right, + by: areEquivalent, + printer: printer, + message(), + trapping: trapping, + file: file, + line: line) + return + } +#endif var c = 0 var j = right.startIndex for i in 0 ..< left.count { @@ -106,7 +109,6 @@ internal func expectUniqueDequeContents< right.formIndex(after: &j) c += 1 } -#endif } final class UniqueDequeTests: CollectionTestCase { diff --git a/Tests/_CollectionsTestSupport/AssertionContexts/Assertions+Containers.swift b/Tests/_CollectionsTestSupport/AssertionContexts/Assertions+Containers.swift index 929ac9e5..2a7522a5 100644 --- a/Tests/_CollectionsTestSupport/AssertionContexts/Assertions+Containers.swift +++ b/Tests/_CollectionsTestSupport/AssertionContexts/Assertions+Containers.swift @@ -124,7 +124,7 @@ public func expectIterableContents< #if compiler(>=6.4) && UnstableContainersPreview /// Check if `left` contains lifetime tracked instances whose payloads equal /// the elements in `right`. -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) public func expectIterablePayloads< Payload: Equatable, E1: Iterable_, E> & ~Copyable & ~Escapable, @@ -172,7 +172,7 @@ public func expectIterablePayloads< /// Check if `left` contains lifetime tracked instances whose payloads equal /// the elements in `right`. -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) public func expectIterablePayloads< Payload: Equatable, E1: Iterable_, E> & ~Copyable & ~Escapable, @@ -220,7 +220,7 @@ public func expectIterablePayloads< #endif #if compiler(>=6.4) && UnstableContainersPreview -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) public func expectIterablesWithEquivalentElements< S1: Iterable_ & ~Copyable & ~Escapable, S2: Iterable_ & ~Copyable & ~Escapable @@ -245,7 +245,7 @@ where } /// Check if `left` and `right` contain equal elements in the same order. -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) public func expectIterablesWithEqualElements< Element: Equatable, S1: Iterable_ & ~Copyable & ~Escapable, @@ -270,7 +270,7 @@ where } /// Check if `left` and `right` contain equal elements in the same order. -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) public func expectIterableContents< Element: Equatable, S1: Iterable_ & ~Copyable & ~Escapable, @@ -313,7 +313,7 @@ public func expectIterableContents< } /// Check if `left` and `right` contain equal elements in the same order. -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) public func expectIterableContents< S1: Iterable_ & ~Copyable & ~Escapable, C2: Collection, diff --git a/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift b/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift index e922a6c6..7f264011 100644 --- a/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift +++ b/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift @@ -19,7 +19,7 @@ import Collections import ContainersPreview #endif -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) @inlinable public func checkIterable< S: Iterable_ & ~Copyable & ~Escapable, @@ -37,7 +37,7 @@ public func checkIterable< file: file, line: line) } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) @inlinable public func checkIterable< S: Iterable_ & ~Copyable & ~Escapable, diff --git a/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift b/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift index 7e20eb98..df021524 100644 --- a/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift +++ b/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift @@ -84,10 +84,15 @@ public struct _StaccatoBorrowingIterator: BorrowingIteratorP internal var _offset: Int @_lifetime(copy contents) - internal init(contents: Span, params: _StaccatoParameters) { + internal init( + contents: Span, + params: _StaccatoParameters, + start: _StaccatoIndex = .init(_offset: 0) + ) { + precondition(start._offset >= 0 && start._offset <= params._count) self._contents = contents self._params = params - self._offset = 0 + self._offset = start._offset } @_lifetime(&self) // FIXME: Should be `@_lifetime(copy self)` @@ -97,6 +102,10 @@ public struct _StaccatoBorrowingIterator: BorrowingIteratorP _offset = endOffset return _contents.extracting(startOffset ..< endOffset) } + + public var currentIndex: _StaccatoIndex { + _StaccatoIndex(_offset: _offset) + } } @available(SwiftStdlib 5.0, *) @@ -132,8 +141,16 @@ extension StaccatoContainer: Container where Element: ~Copyable { public var isEmpty: Bool { _contents.isEmpty } public var count: Int { _contents.count } - - + + @_lifetime(borrow self) + public func makeBorrowingIterator(from start: Index) -> BorrowingIterator_ { + BorrowingIterator_(contents: _contents.span, params: _params, start: start) + } + + public func currentIndex(of iterator: borrowing BorrowingIterator_) -> Index { + iterator.currentIndex + } + package func _isValid(_ index: Index) -> Bool { index._offset >= 0 && index._offset <= count } diff --git a/Xcode/Collections.xcodeproj/project.pbxproj b/Xcode/Collections.xcodeproj/project.pbxproj index ffc840f3..46bcf490 100644 --- a/Xcode/Collections.xcodeproj/project.pbxproj +++ b/Xcode/Collections.xcodeproj/project.pbxproj @@ -7,6 +7,10 @@ objects = { /* Begin PBXBuildFile section */ + 7D0DC7BF2FFD929900BEE8B2 /* Array+Iterable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D0DC7BE2FFD929500BEE8B2 /* Array+Iterable.swift */; }; + 7D0DC7C12FFD92BB00BEE8B2 /* InlineArray+Iterable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D0DC7C02FFD92B500BEE8B2 /* InlineArray+Iterable.swift */; }; + 7D0DC7C32FFD987800BEE8B2 /* Range+Iterable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D0DC7C22FFD987400BEE8B2 /* Range+Iterable.swift */; }; + 7D0DC7C52FFD990E00BEE8B2 /* ClosedRange+Iterable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D0DC7C42FFD990E00BEE8B2 /* ClosedRange+Iterable.swift */; }; 7D12E33D2FF5CC2A003050AB /* OutputSpan+Helpers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D12E33C2FF5CC2A003050AB /* OutputSpan+Helpers.swift */; }; 7D12E33F2FF5DAE4003050AB /* _HTable+Deprecated.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D12E33E2FF5DADE003050AB /* _HTable+Deprecated.swift */; }; 7D12E3412FF5DD0B003050AB /* RigidSet+Deprecated.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D12E3402FF5DD07003050AB /* RigidSet+Deprecated.swift */; }; @@ -157,6 +161,10 @@ 7D77E6252FD0F880003FA63B /* UnsafePointer+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D77E6242FD0F87B003FA63B /* UnsafePointer+Extras.swift */; }; 7D77E6272FD0F94B003FA63B /* UnsafeMutablePointer+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D77E6262FD0F940003FA63B /* UnsafeMutablePointer+Extras.swift */; }; 7D945E6B2FF5E0D1001041A6 /* UniqueSet+Deprecations.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D945E6A2FF5E0CB001041A6 /* UniqueSet+Deprecations.swift */; }; + 7D945E6D2FF71D76001041A6 /* Span+Iterable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D945E6C2FF71D76001041A6 /* Span+Iterable.swift */; }; + 7D945E6F2FF71DFF001041A6 /* MutableSpan+Iterable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D945E6E2FF71DF8001041A6 /* MutableSpan+Iterable.swift */; }; + 7D945E712FF71E58001041A6 /* OutputSpan+Iterable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D945E702FF71E53001041A6 /* OutputSpan+Iterable.swift */; }; + 7D945E732FF71E8C001041A6 /* InputSpan+Iterable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D945E722FF71E86001041A6 /* InputSpan+Iterable.swift */; }; 7D9748D42E9748930098631A /* BigString+Chunk+UTF16.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9748D32E9748930098631A /* BigString+Chunk+UTF16.swift */; }; 7D9748D52E9748930098631A /* BigString+Chunk+UnicodeScalar.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9748D12E9748930098631A /* BigString+Chunk+UnicodeScalar.swift */; }; 7D9748D62E9748930098631A /* BigString+Chunk+Character.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9748CF2E9748930098631A /* BigString+Chunk+Character.swift */; }; @@ -189,7 +197,6 @@ 7DA23F5A2F32C68300E4C03A /* RigidArray+Hashable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DA23F592F32C67D00E4C03A /* RigidArray+Hashable.swift */; }; 7DA23F5C2F32C69100E4C03A /* RigidArray+Descriptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DA23F5B2F32C68B00E4C03A /* RigidArray+Descriptions.swift */; }; 7DA296012FB79DC5005042B0 /* CollectionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DA295FF2FB79DC5005042B0 /* CollectionsTests.swift */; }; - 7DACFA122F75FBF100291F2E /* SpanIterator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DACFA112F75FBF100291F2E /* SpanIterator.swift */; }; 7DAD899E2E8B09C300DD5786 /* UInt+first and last set bit.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DAD899C2E8B09C300DD5786 /* UInt+first and last set bit.swift */; }; 7DAD899F2E8B09C300DD5786 /* UInt+reversed.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DAD899D2E8B09C300DD5786 /* UInt+reversed.swift */; }; 7DAD89A02E8B09C300DD5786 /* FixedWidthInteger+roundUpToPowerOfTwo.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DAD899A2E8B09C300DD5786 /* FixedWidthInteger+roundUpToPowerOfTwo.swift */; }; @@ -209,7 +216,6 @@ 7DB257A32F58B1D3007B539F /* UniqueDictionary+Debugging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DB257A22F58B1CC007B539F /* UniqueDictionary+Debugging.swift */; }; 7DC037B72FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Copy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037B12FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Copy.swift */; }; 7DC037B82FE3492D00CF0CB8 /* Iterable+Utilities.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037AF2FE3492D00CF0CB8 /* Iterable+Utilities.swift */; }; - 7DC037B92FE3492D00CF0CB8 /* Iterable+Standard Conformances.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037AE2FE3492D00CF0CB8 /* Iterable+Standard Conformances.swift */; }; 7DC037BA2FE3492D00CF0CB8 /* BorrowingIteratorProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037B02FE3492D00CF0CB8 /* BorrowingIteratorProtocol.swift */; }; 7DC037BB2FE3492D00CF0CB8 /* Iterable+Algorithms.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037AD2FE3492D00CF0CB8 /* Iterable+Algorithms.swift */; }; 7DC037BC2FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Filter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037B32FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Filter.swift */; }; @@ -619,6 +625,10 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ + 7D0DC7BE2FFD929500BEE8B2 /* Array+Iterable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Array+Iterable.swift"; sourceTree = ""; }; + 7D0DC7C02FFD92B500BEE8B2 /* InlineArray+Iterable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "InlineArray+Iterable.swift"; sourceTree = ""; }; + 7D0DC7C22FFD987400BEE8B2 /* Range+Iterable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Range+Iterable.swift"; sourceTree = ""; }; + 7D0DC7C42FFD990E00BEE8B2 /* ClosedRange+Iterable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ClosedRange+Iterable.swift"; sourceTree = ""; }; 7D12E33C2FF5CC2A003050AB /* OutputSpan+Helpers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "OutputSpan+Helpers.swift"; sourceTree = ""; }; 7D12E33E2FF5DADE003050AB /* _HTable+Deprecated.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "_HTable+Deprecated.swift"; sourceTree = ""; }; 7D12E3402FF5DD07003050AB /* RigidSet+Deprecated.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidSet+Deprecated.swift"; sourceTree = ""; }; @@ -783,6 +793,10 @@ 7D77E6242FD0F87B003FA63B /* UnsafePointer+Extras.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UnsafePointer+Extras.swift"; sourceTree = ""; }; 7D77E6262FD0F940003FA63B /* UnsafeMutablePointer+Extras.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UnsafeMutablePointer+Extras.swift"; sourceTree = ""; }; 7D945E6A2FF5E0CB001041A6 /* UniqueSet+Deprecations.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueSet+Deprecations.swift"; sourceTree = ""; }; + 7D945E6C2FF71D76001041A6 /* Span+Iterable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Span+Iterable.swift"; sourceTree = ""; }; + 7D945E6E2FF71DF8001041A6 /* MutableSpan+Iterable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "MutableSpan+Iterable.swift"; sourceTree = ""; }; + 7D945E702FF71E53001041A6 /* OutputSpan+Iterable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "OutputSpan+Iterable.swift"; sourceTree = ""; }; + 7D945E722FF71E86001041A6 /* InputSpan+Iterable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "InputSpan+Iterable.swift"; sourceTree = ""; }; 7D9748CF2E9748930098631A /* BigString+Chunk+Character.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BigString+Chunk+Character.swift"; sourceTree = ""; }; 7D9748D02E9748930098631A /* BigString+Chunk+Index.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BigString+Chunk+Index.swift"; sourceTree = ""; }; 7D9748D12E9748930098631A /* BigString+Chunk+UnicodeScalar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BigString+Chunk+UnicodeScalar.swift"; sourceTree = ""; }; @@ -816,7 +830,6 @@ 7DA23F592F32C67D00E4C03A /* RigidArray+Hashable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidArray+Hashable.swift"; sourceTree = ""; }; 7DA23F5B2F32C68B00E4C03A /* RigidArray+Descriptions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidArray+Descriptions.swift"; sourceTree = ""; }; 7DA295FF2FB79DC5005042B0 /* CollectionsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CollectionsTests.swift; sourceTree = ""; }; - 7DACFA112F75FBF100291F2E /* SpanIterator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpanIterator.swift; sourceTree = ""; }; 7DAD899A2E8B09C300DD5786 /* FixedWidthInteger+roundUpToPowerOfTwo.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FixedWidthInteger+roundUpToPowerOfTwo.swift"; sourceTree = ""; }; 7DAD899B2E8B09C300DD5786 /* Integer rank.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Integer rank.swift"; sourceTree = ""; }; 7DAD899C2E8B09C300DD5786 /* UInt+first and last set bit.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UInt+first and last set bit.swift"; sourceTree = ""; }; @@ -836,7 +849,6 @@ 7DB257A22F58B1CC007B539F /* UniqueDictionary+Debugging.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueDictionary+Debugging.swift"; sourceTree = ""; }; 7DC037AC2FE3492D00CF0CB8 /* Iterable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Iterable.swift; sourceTree = ""; }; 7DC037AD2FE3492D00CF0CB8 /* Iterable+Algorithms.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Iterable+Algorithms.swift"; sourceTree = ""; }; - 7DC037AE2FE3492D00CF0CB8 /* Iterable+Standard Conformances.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Iterable+Standard Conformances.swift"; sourceTree = ""; }; 7DC037AF2FE3492D00CF0CB8 /* Iterable+Utilities.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Iterable+Utilities.swift"; sourceTree = ""; }; 7DC037B02FE3492D00CF0CB8 /* BorrowingIteratorProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BorrowingIteratorProtocol.swift; sourceTree = ""; }; 7DC037B12FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Copy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BorrowingIteratorProtocol+Copy.swift"; sourceTree = ""; }; @@ -1331,7 +1343,6 @@ children = ( 7DC037AC2FE3492D00CF0CB8 /* Iterable.swift */, 7DC037AD2FE3492D00CF0CB8 /* Iterable+Algorithms.swift */, - 7DC037AE2FE3492D00CF0CB8 /* Iterable+Standard Conformances.swift */, 7DC037AF2FE3492D00CF0CB8 /* Iterable+Utilities.swift */, 7DC037B02FE3492D00CF0CB8 /* BorrowingIteratorProtocol.swift */, 7DC037B12FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Copy.swift */, @@ -1363,7 +1374,6 @@ 7D12E33C2FF5CC2A003050AB /* OutputSpan+Helpers.swift */, 7D2A77352F27F1E4005780C7 /* InputSpan.swift */, 7D2A77362F27F1E4005780C7 /* Shared.swift */, - 7DACFA112F75FBF100291F2E /* SpanIterator.swift */, ); path = Types; sourceTree = ""; @@ -1516,9 +1526,17 @@ 7D59D0652FE49C87005B5097 /* Conformances */ = { isa = PBXGroup; children = ( + 7D0DC7BE2FFD929500BEE8B2 /* Array+Iterable.swift */, + 7D0DC7C42FFD990E00BEE8B2 /* ClosedRange+Iterable.swift */, + 7D0DC7C02FFD92B500BEE8B2 /* InlineArray+Iterable.swift */, + 7D945E722FF71E86001041A6 /* InputSpan+Iterable.swift */, 7D59D0612FE49C87005B5097 /* InputSpan+Container.swift */, + 7D945E6E2FF71DF8001041A6 /* MutableSpan+Iterable.swift */, 7D59D0622FE49C87005B5097 /* MutableSpan+Container.swift */, + 7D945E702FF71E53001041A6 /* OutputSpan+Iterable.swift */, 7D59D0632FE49C87005B5097 /* OutputSpan+Container.swift */, + 7D0DC7C22FFD987400BEE8B2 /* Range+Iterable.swift */, + 7D945E6C2FF71D76001041A6 /* Span+Iterable.swift */, 7D59D0642FE49C87005B5097 /* Span+Container.swift */, ); path = Conformances; @@ -2677,7 +2695,6 @@ 7DE9203C29CA70F3004483EB /* OrderedSet+Partial SetAlgebra formSymmetricDifference.swift in Sources */, 7DC037B72FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Copy.swift in Sources */, 7DC037B82FE3492D00CF0CB8 /* Iterable+Utilities.swift in Sources */, - 7DC037B92FE3492D00CF0CB8 /* Iterable+Standard Conformances.swift in Sources */, 7DC037BA2FE3492D00CF0CB8 /* BorrowingIteratorProtocol.swift in Sources */, 7DC037BB2FE3492D00CF0CB8 /* Iterable+Algorithms.swift in Sources */, 7DC037BC2FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Filter.swift in Sources */, @@ -2697,6 +2714,7 @@ 7D2A777F2F27F2BF005780C7 /* RigidDeque+Container.swift in Sources */, 7D2A77802F27F2BF005780C7 /* Deque.swift in Sources */, 7D2A77812F27F2BF005780C7 /* UniqueDeque+Append.swift in Sources */, + 7D945E712FF71E58001041A6 /* OutputSpan+Iterable.swift in Sources */, 7D2A77822F27F2BF005780C7 /* UniqueDeque+Initializers.swift in Sources */, 7D2A77832F27F2BF005780C7 /* Deque+Equatable.swift in Sources */, 7D2A77842F27F2BF005780C7 /* UniqueDeque+Container.swift in Sources */, @@ -2814,7 +2832,6 @@ 7DE9209A29CA70F4004483EB /* Rope+Append.swift in Sources */, 7DE9203F29CA70F3004483EB /* OrderedSet+Partial SetAlgebra isDisjoint.swift in Sources */, 7DC85F8D2F3FDC91004A4E3D /* String+Padding.swift in Sources */, - 7DACFA122F75FBF100291F2E /* SpanIterator.swift in Sources */, 7DE9208629CA70F4004483EB /* BigString+LosslessStringConvertible.swift in Sources */, 7DE9204329CA70F3004483EB /* _HashTable+Bucket.swift in Sources */, 7DE9216A29CA70F4004483EB /* TreeDictionary.swift in Sources */, @@ -2837,6 +2854,7 @@ 7D479CE72F47D88600A8CB59 /* _HTable+Consumption.swift in Sources */, 7DE9202B29CA70F3004483EB /* OrderedSet+Equatable.swift in Sources */, 7D479CC52F46D20B00A8CB59 /* UniqueSet+Consumption.swift in Sources */, + 7D0DC7BF2FFD929900BEE8B2 /* Array+Iterable.swift in Sources */, 7DE920EA29CA70F4004483EB /* BitArray.swift in Sources */, 7DE920CB29CA70F4004483EB /* BitSet+Random.swift in Sources */, 7DE9201629CA70F3004483EB /* OrderedDictionary+Elements.swift in Sources */, @@ -2965,6 +2983,7 @@ 7DE920A329CA70F4004483EB /* Rope+Index.swift in Sources */, 7DA23F462F329A2300E4C03A /* RigidArray+Experimental.swift in Sources */, 7DA23F472F329A2300E4C03A /* UniqueArray.swift in Sources */, + 7D945E732FF71E8C001041A6 /* InputSpan+Iterable.swift in Sources */, 7DFA40842FD3A98D00CD20C1 /* OrderedSet+Move.swift in Sources */, 7DA23F482F329A2300E4C03A /* RigidArray+Replacements.swift in Sources */, 7DA23F492F329A2300E4C03A /* RigidArray+Container.swift in Sources */, @@ -3048,6 +3067,7 @@ 7DE9202729CA70F3004483EB /* OrderedSet+Insertions.swift in Sources */, 7D479CD42F46DD9600A8CB59 /* UniqueSet+Initializers.swift in Sources */, 7DE9208729CA70F4004483EB /* BigString+Sequence.swift in Sources */, + 7D0DC7C32FFD987800BEE8B2 /* Range+Iterable.swift in Sources */, 7DE9202229CA70F3004483EB /* OrderedSet+Diffing.swift in Sources */, 7DE920CA29CA70F4004483EB /* BitSet+CustomStringConvertible.swift in Sources */, 7DEB31622F4F98D700F9AF28 /* RigidDictionary+Indices.swift in Sources */, @@ -3078,6 +3098,7 @@ 7DE9201829CA70F3004483EB /* OrderedDictionary+Invariants.swift in Sources */, 7DE920CD29CA70F4004483EB /* BitSet+CustomDebugStringConvertible.swift in Sources */, 7DE9212529CA70F4004483EB /* TreeSet+SetAlgebra isStrictSubset.swift in Sources */, + 7D945E6F2FF71DFF001041A6 /* MutableSpan+Iterable.swift in Sources */, 7DE9209229CA70F4004483EB /* Rope+_Storage.swift in Sources */, 7DE9203929CA70F3004483EB /* OrderedSet+Partial RangeReplaceableCollection.swift in Sources */, 7DE9206329CA70F4004483EB /* BigString+Contents.swift in Sources */, @@ -3135,6 +3156,7 @@ 7DE920E029CA70F4004483EB /* Range+Utilities.swift in Sources */, 7DE920D929CA70F4004483EB /* BitSet+SetAlgebra intersection.swift in Sources */, 7DE920DD29CA70F4004483EB /* BitSet+SetAlgebra isStrictSubset.swift in Sources */, + 7D0DC7C52FFD990E00BEE8B2 /* ClosedRange+Iterable.swift in Sources */, 7DE920F229CA70F4004483EB /* BitArray._UnsafeHandle.swift in Sources */, 7D479CEB2F47F3C100A8CB59 /* UniqueDictionary+Resizing.swift in Sources */, 7DE9204229CA70F3004483EB /* _HashTable+UnsafeHandle.swift in Sources */, @@ -3144,11 +3166,13 @@ 7D77E6122FCF810E003FA63B /* CountedProducer.swift in Sources */, 7DE920E829CA70F4004483EB /* BitArray+BitwiseOperations.swift in Sources */, 7DE9207829CA70F4004483EB /* BigString+Append.swift in Sources */, + 7D0DC7C12FFD92BB00BEE8B2 /* InlineArray+Iterable.swift in Sources */, 7DE9217F29CA70F4004483EB /* _HeapNode.swift in Sources */, 7D479CB92F46A6DB00A8CB59 /* RigidSet+Debugging.swift in Sources */, 7DE9202929CA70F3004483EB /* OrderedSet+Codable.swift in Sources */, 7DE9204829CA70F3004483EB /* _HashTable+CustomStringConvertible.swift in Sources */, 7D479CE52F47D74500A8CB59 /* RigidDictionary+Resizing.swift in Sources */, + 7D945E6D2FF71D76001041A6 /* Span+Iterable.swift in Sources */, 7DE9213029CA70F4004483EB /* TreeSet+SetAlgebra isSuperset.swift in Sources */, 7DE9217529CA70F4004483EB /* TreeDictionary+MapValues.swift in Sources */, 7DE9206C29CA70F4004483EB /* BigString+Chunk.swift in Sources */, From c6eabe862a3384d63f16d0cf69e3cd4a43837e72 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 7 Jul 2026 14:34:41 -0700 Subject: [PATCH 26/50] Resolve access issues & missing imports --- Sources/BasicContainers/RigidSet/RigidSet+Insertions.swift | 1 + Sources/ContainersPreview/Conformances/Span+Iterable.swift | 6 +++--- Tests/ContainersTests/MutableRefTests.swift | 1 + Tests/ContainersTests/RefTests.swift | 1 + 4 files changed, 6 insertions(+), 3 deletions(-) diff --git a/Sources/BasicContainers/RigidSet/RigidSet+Insertions.swift b/Sources/BasicContainers/RigidSet/RigidSet+Insertions.swift index 1415bfd9..7bee7ad0 100644 --- a/Sources/BasicContainers/RigidSet/RigidSet+Insertions.swift +++ b/Sources/BasicContainers/RigidSet/RigidSet+Insertions.swift @@ -12,6 +12,7 @@ //===----------------------------------------------------------------------===// #if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities import ContainersPreview #endif diff --git a/Sources/ContainersPreview/Conformances/Span+Iterable.swift b/Sources/ContainersPreview/Conformances/Span+Iterable.swift index c23f7911..256c41ae 100644 --- a/Sources/ContainersPreview/Conformances/Span+Iterable.swift +++ b/Sources/ContainersPreview/Conformances/Span+Iterable.swift @@ -38,11 +38,11 @@ extension Span where Element: ~Copyable { public typealias Element_ = Element @usableFromInline - internal var _span: Span + package var _span: Span @usableFromInline - internal var _start: Int + package var _start: Int @usableFromInline - internal var _count: Int + package var _count: Int @_lifetime(copy elements) public init(_ elements: Span) { diff --git a/Tests/ContainersTests/MutableRefTests.swift b/Tests/ContainersTests/MutableRefTests.swift index d6792ffd..281aeff2 100644 --- a/Tests/ContainersTests/MutableRefTests.swift +++ b/Tests/ContainersTests/MutableRefTests.swift @@ -15,6 +15,7 @@ import XCTest #if COLLECTIONS_SINGLE_MODULE import Collections #else +import InternalCollectionsUtilities import _CollectionsTestSupport import ContainersPreview #endif diff --git a/Tests/ContainersTests/RefTests.swift b/Tests/ContainersTests/RefTests.swift index 2e096946..5f4222da 100644 --- a/Tests/ContainersTests/RefTests.swift +++ b/Tests/ContainersTests/RefTests.swift @@ -16,6 +16,7 @@ import XCTest #if COLLECTIONS_SINGLE_MODULE import Collections #else +import InternalCollectionsUtilities import _CollectionsTestSupport import ContainersPreview #endif From 920bc2a81f7227ce69d2c295f99e5dd92fb1be84 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 7 Jul 2026 15:21:26 -0700 Subject: [PATCH 27/50] [DequeModule] RigidDeque: Fix duplicate Equatable conformance --- Sources/DequeModule/RigidDeque/RigidDeque+Equatable.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Equatable.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Equatable.swift index 8935f6db..98624465 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Equatable.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Equatable.swift @@ -19,7 +19,7 @@ import ContainersPreview #endif @available(SwiftStdlib 5.0, *) -extension RigidDeque: Equatable where Element: Equatable & ~Copyable { +extension RigidDeque where Element: Equatable & ~Copyable { public func isTriviallyIdentical(to other: borrowing Self) -> Bool { self._handle.isIdentical(to: other._handle) } From fbb8aa1e36e6d2f3dfaea7f461dfa2196680303c Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 7 Jul 2026 15:21:42 -0700 Subject: [PATCH 28/50] [DequeModule] UniqueDeque: Add isTriviallyIdentical(to:) --- Sources/DequeModule/RigidDeque/RigidDeque+Equatable.swift | 2 +- .../DequeModule/UniqueDeque/UniqueDeque+Equatable.swift | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Equatable.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Equatable.swift index 98624465..7400c982 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Equatable.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Equatable.swift @@ -19,7 +19,7 @@ import ContainersPreview #endif @available(SwiftStdlib 5.0, *) -extension RigidDeque where Element: Equatable & ~Copyable { +extension RigidDeque where Element: ~Copyable { public func isTriviallyIdentical(to other: borrowing Self) -> Bool { self._handle.isIdentical(to: other._handle) } diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Equatable.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Equatable.swift index aac7237a..e08facb1 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Equatable.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Equatable.swift @@ -17,6 +17,13 @@ import InternalCollectionsUtilities #endif +@available(SwiftStdlib 5.0, *) +extension UniqueDeque where Element: ~Copyable { + public func isTriviallyIdentical(to other: borrowing Self) -> Bool { + self._storage.isTriviallyIdentical(to: other._storage) + } +} + @available(SwiftStdlib 6.4, *) extension UniqueDeque: Equatable where Element: Equatable & ~Copyable { } From b1cba023930593e1541c832f87cc51790f388f41 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 7 Jul 2026 15:29:54 -0700 Subject: [PATCH 29/50] [DequeModule] Disable Equatable/Hashable conformance on pre-6.4 toolchains --- .../RigidDeque/RigidDeque+Equatable.swift | 26 ++++++++++++++++--- .../RigidDeque/RigidDeque+Hashable.swift | 2 +- .../UniqueDeque/UniqueDeque+Equatable.swift | 13 ++++++++++ .../UniqueDeque/UniqueDeque+Hashable.swift | 2 +- 4 files changed, 37 insertions(+), 6 deletions(-) diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Equatable.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Equatable.swift index 7400c982..0e94bceb 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Equatable.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Equatable.swift @@ -25,9 +25,9 @@ extension RigidDeque where Element: ~Copyable { } } +#if compiler(>=6.4) @available(SwiftStdlib 6.4, *) -extension RigidDeque: Equatable where Element: Equatable & ~Copyable { -} +extension RigidDeque: Equatable where Element: Equatable & ~Copyable {} @available(SwiftStdlib 5.0, *) extension RigidDeque where Element: Equatable & ~Copyable { @@ -38,8 +38,8 @@ extension RigidDeque where Element: Equatable & ~Copyable { ) -> Bool { guard left.count == right.count else { return false } guard !left.isTriviallyIdentical(to: right) else { return true } - -#if compiler(>=6.4) && UnstableContainersPreview + +#if UnstableContainersPreview if #available(anyAppleOS 27, *) { return left._elementsEqual(right) } @@ -50,5 +50,23 @@ extension RigidDeque where Element: Equatable & ~Copyable { return true } } +#else +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: Equatable { + @inlinable + public static func ==( + left: borrowing Self, + right: borrowing Self + ) -> Bool { + guard left.count == right.count else { return false } + guard !left.isTriviallyIdentical(to: right) else { return true } + + for i in 0 ..< left.count { + guard left[i] == right[i] else { return false } + } + return true + } +} +#endif #endif diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Hashable.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Hashable.swift index 3659a1b6..5a0dbc46 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Hashable.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Hashable.swift @@ -17,7 +17,7 @@ import InternalCollectionsUtilities #endif -#if compiler(>=6.4) && UnstableContainersPreview +#if compiler(>=6.4) @available(SwiftStdlib 6.4, *) extension RigidDeque: Hashable where Element: Hashable & ~Copyable { } diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Equatable.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Equatable.swift index e08facb1..a133988a 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Equatable.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Equatable.swift @@ -24,6 +24,7 @@ extension UniqueDeque where Element: ~Copyable { } } +#if compiler(>=6.4) @available(SwiftStdlib 6.4, *) extension UniqueDeque: Equatable where Element: Equatable & ~Copyable { } @@ -38,5 +39,17 @@ extension UniqueDeque where Element: Equatable & ~Copyable { left._storage == right._storage } } +#else +@available(SwiftStdlib 5.0, *) +extension UniqueDeque where Element: Equatable { + @inlinable + public static func ==( + left: borrowing Self, + right: borrowing Self + ) -> Bool { + left._storage == right._storage + } +} +#endif #endif diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Hashable.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Hashable.swift index 350a0004..7df61de7 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Hashable.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Hashable.swift @@ -13,7 +13,7 @@ #if compiler(>=6.2) -#if compiler(>=6.4) && UnstableContainersPreview +#if compiler(>=6.4) @available(SwiftStdlib 6.4, *) extension UniqueDeque: Hashable where Element: Hashable & ~Copyable { } From 62332dc40a4b0c9fb9ead54b45f3243bae176e7b Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 7 Jul 2026 15:31:24 -0700 Subject: [PATCH 30/50] Avoid borrow/mutate accessors before Swift 6.4 --- .../RigidArray/RigidArray+Container.swift | 25 +++++++++++++++++-- .../UniqueArray/UniqueArray+Container.swift | 21 ++++++++++++++++ .../ContainersPreview/Types/InputSpan.swift | 21 ++++++++++++++++ .../DequeModule/RigidDeque/RigidDeque.swift | 20 +++++++++++++++ .../DequeModule/UniqueDeque/UniqueDeque.swift | 20 +++++++++++++++ 5 files changed, 105 insertions(+), 2 deletions(-) diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Container.swift b/Sources/BasicContainers/RigidArray/RigidArray+Container.swift index 6aa3b7e4..6ff71645 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Container.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Container.swift @@ -157,7 +157,7 @@ extension RigidArray where Element: ~Copyable { let p = _storage.baseAddress.unsafelyUnwrapped.advanced(by: index) return UnsafePointer(p) } - + @inlinable @inline(__always) internal mutating func _mutablePtr( to index: Int @@ -165,7 +165,8 @@ extension RigidArray where Element: ~Copyable { _checkItemIndex(index) return _storage.baseAddress.unsafelyUnwrapped.advanced(by: index) } - + +#if compiler(>=6.4) /// Accesses the element at the specified position. /// /// - Parameter position: The position of the element to access. @@ -186,6 +187,26 @@ extension RigidArray where Element: ~Copyable { &_mutablePtr(to: position).pointee } } +#else + /// Accesses the element at the specified position. + /// + /// - Parameter position: The position of the element to access. + /// The position must be a valid index of the array that is not equal + /// to the `endIndex` property. + /// + /// - Complexity: O(1) + @inlinable + public subscript(position: Int) -> Element { + @inline(__always) + unsafeAddress { + _ptr(to: position) + } + @inline(__always) + unsafeMutableAddress { + _mutablePtr(to: position) + } + } +#endif } @available(SwiftStdlib 5.0, *) diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift index 03a596c4..3f6a5127 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift @@ -117,6 +117,7 @@ extension UniqueArray where Element: ~Copyable { @inline(__always) public var indices: Range { _storage.indices } +#if compiler(>=6.4) /// Accesses the element at the specified position. /// /// - Parameter position: The position of the element to access. @@ -136,6 +137,26 @@ extension UniqueArray where Element: ~Copyable { &_storage[position] } } +#else + /// Accesses the element at the specified position. + /// + /// - Parameter position: The position of the element to access. + /// The position must be a valid index of the array that is not equal + /// to the `endIndex` property. + /// + /// - Complexity: O(1) + @inlinable + public subscript(position: Int) -> Element { + @inline(__always) + unsafeAddress { + _storage._ptr(to: position) + } + @inline(__always) + unsafeMutableAddress { + _storage._mutablePtr(to: position) + } + } +#endif } @available(SwiftStdlib 5.0, *) diff --git a/Sources/ContainersPreview/Types/InputSpan.swift b/Sources/ContainersPreview/Types/InputSpan.swift index 1bc52c51..61bcd472 100644 --- a/Sources/ContainersPreview/Types/InputSpan.swift +++ b/Sources/ContainersPreview/Types/InputSpan.swift @@ -237,6 +237,7 @@ extension InputSpan where Element: ~Copyable { unsafe Range(uncheckedBounds: (0, _count)) } +#if compiler(>=6.4) /// Accesses the element at the specified position. /// /// - Parameter index: A valid index into this span. @@ -257,6 +258,26 @@ extension InputSpan where Element: ~Copyable { return unsafe &_unsafeAddressOfElement(uncheckedOffset: index).pointee } } +#else + /// Accesses the element at the specified position. + /// + /// - Parameter index: A valid index into this span. + /// + /// - Complexity: O(1) + @_alwaysEmitIntoClient + public subscript(_ index: Index) -> Element { + unsafeAddress { + precondition(indices.contains(index), "Index out of bounds") + return unsafe UnsafePointer(_unsafeAddressOfElement(uncheckedOffset: index)) + } + + @_lifetime(self: copy self) + unsafeMutableAddress { + precondition(indices.contains(index), "Index out of bounds") + return unsafe _unsafeAddressOfElement(uncheckedOffset: index) + } + } +#endif /// Accesses the element at the specified position. /// diff --git a/Sources/DequeModule/RigidDeque/RigidDeque.swift b/Sources/DequeModule/RigidDeque/RigidDeque.swift index a7e90e53..95a48a60 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque.swift @@ -260,6 +260,7 @@ extension RigidDeque where Element: ~Copyable { "Index range out of bounds") } +#if compiler(>=6.4) @_alwaysEmitIntoClient public subscript(position: Int) -> Element { @inline(__always) @@ -279,6 +280,25 @@ extension RigidDeque where Element: ~Copyable { return &_handle.mutablePtr(at: slot).pointee } } +#else + @_alwaysEmitIntoClient + public subscript(position: Int) -> Element { + @inline(__always) + @_transparent + unsafeAddress { + _checkItemIndex(position) + let slot = _handle.slot(forOffset: position) + return _handle.ptr(at: slot) + } + @inline(__always) + @_transparent + unsafeMutableAddress { + _checkItemIndex(position) + let slot = _handle.slot(forOffset: position) + return _handle.mutablePtr(at: slot) + } + } +#endif } @available(SwiftStdlib 5.0, *) diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque.swift index 5d26bc64..bbf13983 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque.swift @@ -194,6 +194,7 @@ extension UniqueDeque where Element: ~Copyable { @inline(__always) public var indices: Range { unsafe Range(uncheckedBounds: (0, count)) } +#if compiler(>=6.4) @_alwaysEmitIntoClient public subscript(position: Int) -> Element { @inline(__always) @@ -208,6 +209,25 @@ extension UniqueDeque where Element: ~Copyable { &_storage[position] } } +#else + @_alwaysEmitIntoClient + public subscript(position: Int) -> Element { + @inline(__always) + @_transparent + unsafeAddress { + precondition(position >= 0 && position < count, "Index out of bounds") + let slot = _storage._handle.slot(forOffset: position) + return _storage._handle.ptr(at: slot) + } + @inline(__always) + @_transparent + unsafeMutableAddress { + precondition(position >= 0 && position < count, "Index out of bounds") + let slot = _storage._handle.slot(forOffset: position) + return _storage._handle.mutablePtr(at: slot) + } + } +#endif } @available(SwiftStdlib 5.0, *) From 70dc238938a0a8be6f48ada20307ead8d8e722e1 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 7 Jul 2026 16:14:48 -0700 Subject: [PATCH 31/50] [BasicContainers] RigidDictionary, UniqueDictionary: Add keys property This replaces `withKeys`, which is now deprecated. --- .../RigidDictionary+Keys.swift | 20 ++++----- .../UniqueDictionary+Keys.swift | 20 ++++----- .../RigidDictionaryTests.swift | 42 ++++++++++++++++- .../UniqueDictionaryTests.swift | 45 +++++++++++++++++-- .../Utilities/With.swift | 38 ++++++++++++++++ Xcode/Collections.xcodeproj/project.pbxproj | 4 ++ 6 files changed, 141 insertions(+), 28 deletions(-) create mode 100644 Tests/_CollectionsTestSupport/Utilities/With.swift diff --git a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Keys.swift b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Keys.swift index 49d5e1ce..539ef596 100644 --- a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Keys.swift +++ b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Keys.swift @@ -15,19 +15,15 @@ @available(SwiftStdlib 5.0, *) extension RigidDictionary where Key: ~Copyable, Value: ~Copyable { + @_alwaysEmitIntoClient + public var keys: RigidSet { + borrow { + _keys + } + } -#if false // This requires the BorrowAndMutateAccessors feature that isn't available yet. -// @inlinable -// public var keys: RigidSet { -// borrow { -// _keys -// } -// } -#endif - - /// This is a stand-in for an eventual computed property with a `borrow` - /// accessor. It is destined for deprecation once that feature becomes - /// available. + // FIXME: Remove + @available(*, deprecated, renamed: "keys") @_alwaysEmitIntoClient public func withKeys( _ body: (borrowing RigidSet) throws(E) -> R diff --git a/Sources/BasicContainers/UniqueDictionary/UniqueDictionary+Keys.swift b/Sources/BasicContainers/UniqueDictionary/UniqueDictionary+Keys.swift index b09a0c45..324f7b33 100644 --- a/Sources/BasicContainers/UniqueDictionary/UniqueDictionary+Keys.swift +++ b/Sources/BasicContainers/UniqueDictionary/UniqueDictionary+Keys.swift @@ -15,19 +15,15 @@ @available(SwiftStdlib 5.0, *) extension UniqueDictionary where Key: ~Copyable, Value: ~Copyable { + @_alwaysEmitIntoClient + public var keys: RigidSet { + borrow { + _storage.keys + } + } -#if false // This requires the BorrowAndMutateAccessors feature that isn't available yet. -// @inlinable -// public var keys: RigidSet { -// borrow { -// _storage.keys -// } -// } -#endif - - /// This is a stand-in for an eventual computed property with a `borrow` - /// accessor. It is destined for deprecation once that feature becomes - /// available. + // FIXME: Remove + @available(*, deprecated, renamed: "keys") @_alwaysEmitIntoClient public func withKeys( _ body: (borrowing RigidSet) throws(E) -> R diff --git a/Tests/BasicContainersTests/RigidDictionaryTests.swift b/Tests/BasicContainersTests/RigidDictionaryTests.swift index 704e4155..13fc9f4b 100644 --- a/Tests/BasicContainersTests/RigidDictionaryTests.swift +++ b/Tests/BasicContainersTests/RigidDictionaryTests.swift @@ -242,6 +242,46 @@ class RigidDictionaryTests: CollectionTestCase { } } + func test_keys() { + typealias Key = LifetimeTracked + typealias Value = LifetimeTracked + withEvery("capacity", in: [0, 1, 2, 10, 100, 1000]) { capacity in + withLifetimeTracking { tracker in + var d = RigidDictionary(capacity: capacity) + withEvery("i", in: 0 ..< capacity) { i in + let key = tracker.instance(for: i) + let value = tracker.instance(for: "\(i)") + d.insertValue(value, forKey: key) + + expectEqual(d.keys.count, i + 1) + expectEqual(d.keys.capacity, capacity) + +#if UnstableContainersPreview + var actual: Set = [] + _with(d.keys) { keys in // FIXME: Sigh, borrow accessors are limited in 6.4 + var it = keys.makeBorrowingIterator_() + while true { + let next = it.nextSpan_() + guard !next.isEmpty else { break } + for i in next.indices { + expectTrue( + actual.insert(next[i].payload).inserted, + "Duplicate value \(next[i].payload)") + } + } + } + expectEqualElements(actual.sorted(), 0 ... i) +#else + for j in 0 ... i { + expectTrue(d.keys.contains(tracker.instance(for: j))) + } +#endif + } + } + } + } + + @available(*, deprecated) func test_withKeys() { typealias Key = LifetimeTracked typealias Value = LifetimeTracked @@ -256,7 +296,7 @@ class RigidDictionaryTests: CollectionTestCase { d.withKeys { keys in expectEqual(keys.count, i + 1) expectEqual(keys.capacity, capacity) -#if compiler(>=6.4) && UnstableContainersPreview +#if UnstableContainersPreview var it = keys.makeBorrowingIterator_() var actual: Set = [] while true { diff --git a/Tests/BasicContainersTests/UniqueDictionaryTests.swift b/Tests/BasicContainersTests/UniqueDictionaryTests.swift index 42366881..5f8e188c 100644 --- a/Tests/BasicContainersTests/UniqueDictionaryTests.swift +++ b/Tests/BasicContainersTests/UniqueDictionaryTests.swift @@ -129,8 +129,47 @@ class UniqueDictionaryTests: CollectionTestCase { } expectEqual(actual.sorted(), expected) } - - + + func test_keys() { + typealias Key = LifetimeTracked + typealias Value = LifetimeTracked + withEvery("capacity", in: [0, 1, 2, 10, 100, 1000]) { capacity in + withLifetimeTracking { tracker in + var d = RigidDictionary(capacity: capacity) + withEvery("i", in: 0 ..< capacity) { i in + let key = tracker.instance(for: i) + let value = tracker.instance(for: "\(i)") + d.insertValue(value, forKey: key) + + expectEqual(d.keys.count, i + 1) + expectEqual(d.keys.capacity, capacity) + +#if UnstableContainersPreview + var actual: Set = [] + _with(d.keys) { keys in // FIXME: Sigh, borrow accessors are limited in 6.4 + var it = keys.makeBorrowingIterator_() + while true { + let next = it.nextSpan_() + guard !next.isEmpty else { break } + for i in next.indices { + expectTrue( + actual.insert(next[i].payload).inserted, + "Duplicate value \(next[i].payload)") + } + } + } + expectEqualElements(actual.sorted(), 0 ... i) +#else + for j in 0 ... i { + expectTrue(d.keys.contains(tracker.instance(for: j))) + } +#endif + } + } + } + } + + @available(*, deprecated) func test_withKeys() { typealias Key = LifetimeTracked typealias Value = LifetimeTracked @@ -145,7 +184,7 @@ class UniqueDictionaryTests: CollectionTestCase { d.withKeys { keys in expectEqual(keys.count, i + 1) expectEqual(keys.capacity, capacity) -#if compiler(>=6.4) && UnstableContainersPreview +#if UnstableContainersPreview var it = keys.makeBorrowingIterator_() var actual: Set = [] while true { diff --git a/Tests/_CollectionsTestSupport/Utilities/With.swift b/Tests/_CollectionsTestSupport/Utilities/With.swift new file mode 100644 index 00000000..544f8109 --- /dev/null +++ b/Tests/_CollectionsTestSupport/Utilities/With.swift @@ -0,0 +1,38 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021 - 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 +// +// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.4) +// FIXME: Properties with borrow accessors cannot initialize locals. +// +// let keys = d.keys // error: `d.keys` is borrowed and cannot be consumed +// +// We'll probably need language support for `borrow` (rather than +// `let`) bindings. Meanwhile, work around this by defining a silly +// `_with(foo) { foo in ... }` that sort of emulates borrow bindings +// in the most unhelpful way... +// +// _with(d.keys) { keys in +// // OK +// } +@inlinable +package func _with< + T: ~Copyable & ~Escapable, + E: Error, + R: ~Copyable +>( + _ value: borrowing T, + do body: (borrowing T) throws(E) -> R +) throws(E) -> R { + try body(value) +} +#endif diff --git a/Xcode/Collections.xcodeproj/project.pbxproj b/Xcode/Collections.xcodeproj/project.pbxproj index 46bcf490..d4a8b58a 100644 --- a/Xcode/Collections.xcodeproj/project.pbxproj +++ b/Xcode/Collections.xcodeproj/project.pbxproj @@ -11,6 +11,7 @@ 7D0DC7C12FFD92BB00BEE8B2 /* InlineArray+Iterable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D0DC7C02FFD92B500BEE8B2 /* InlineArray+Iterable.swift */; }; 7D0DC7C32FFD987800BEE8B2 /* Range+Iterable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D0DC7C22FFD987400BEE8B2 /* Range+Iterable.swift */; }; 7D0DC7C52FFD990E00BEE8B2 /* ClosedRange+Iterable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D0DC7C42FFD990E00BEE8B2 /* ClosedRange+Iterable.swift */; }; + 7D0DC7C72FFDC40900BEE8B2 /* With.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D0DC7C62FFDC40600BEE8B2 /* With.swift */; }; 7D12E33D2FF5CC2A003050AB /* OutputSpan+Helpers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D12E33C2FF5CC2A003050AB /* OutputSpan+Helpers.swift */; }; 7D12E33F2FF5DAE4003050AB /* _HTable+Deprecated.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D12E33E2FF5DADE003050AB /* _HTable+Deprecated.swift */; }; 7D12E3412FF5DD0B003050AB /* RigidSet+Deprecated.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D12E3402FF5DD07003050AB /* RigidSet+Deprecated.swift */; }; @@ -629,6 +630,7 @@ 7D0DC7C02FFD92B500BEE8B2 /* InlineArray+Iterable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "InlineArray+Iterable.swift"; sourceTree = ""; }; 7D0DC7C22FFD987400BEE8B2 /* Range+Iterable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Range+Iterable.swift"; sourceTree = ""; }; 7D0DC7C42FFD990E00BEE8B2 /* ClosedRange+Iterable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ClosedRange+Iterable.swift"; sourceTree = ""; }; + 7D0DC7C62FFDC40600BEE8B2 /* With.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = With.swift; sourceTree = ""; }; 7D12E33C2FF5CC2A003050AB /* OutputSpan+Helpers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "OutputSpan+Helpers.swift"; sourceTree = ""; }; 7D12E33E2FF5DADE003050AB /* _HTable+Deprecated.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "_HTable+Deprecated.swift"; sourceTree = ""; }; 7D12E3402FF5DD07003050AB /* RigidSet+Deprecated.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidSet+Deprecated.swift"; sourceTree = ""; }; @@ -2453,6 +2455,7 @@ 7DEBDB2529CCE43600ADC226 /* Utilities */ = { isa = PBXGroup; children = ( + 7D0DC7C62FFDC40600BEE8B2 /* With.swift */, 7DEBDB2C29CCE43600ADC226 /* AllOnesRandomNumberGenerator.swift */, 7D48BCDB2E51554900D7F6F7 /* ClassBox.swift */, 7D48BCDD2E51558700D7F6F7 /* TestPrintable.swift */, @@ -3276,6 +3279,7 @@ 7DEBDB7E29CCE44A00ADC226 /* CheckComparable.swift in Sources */, 7DEBDB7C29CCE44A00ADC226 /* MinimalDecoder.swift in Sources */, 7DE9220829CA8576004483EB /* BitSetTests.swift in Sources */, + 7D0DC7C72FFDC40900BEE8B2 /* With.swift in Sources */, 7DEBDB7329CCE44A00ADC226 /* _MinimalCollectionCore.swift in Sources */, 7DE921C829CA81DC004483EB /* _UniqueCollection.swift in Sources */, 7D48BCF42E5159A300D7F6F7 /* StaccatoContainer.swift in Sources */, From dfd2e340097b229569f17f853fd430522e52eec4 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 14 Jul 2026 17:45:27 -0700 Subject: [PATCH 32/50] =?UTF-8?q?Overhaul=20Producer=E2=80=99s=20skip(by:)?= =?UTF-8?q?=20to=20better=20align=20with=20Iterable?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Don’t allow `skip(by:)` to skip fewer than the requested number of items, unless it hits the end of the sequence or an error. Remove its Boolean return value. - Introduce a variant of `skip(by:)` that doesn’t take an inout argument, losing the ability to report which item triggered a throw. This is just a standard algorithm; the protocol continues to require proper reporting of partial success. - Use the stdlib’s `withTemporaryAllocation` method where possible to create temporary buffers. --- .../ContainersPreview/Protocols/Drain.swift | 48 +++---- .../Protocols/Producer.swift | 130 ++++++++++++------ 2 files changed, 109 insertions(+), 69 deletions(-) diff --git a/Sources/ContainersPreview/Protocols/Drain.swift b/Sources/ContainersPreview/Protocols/Drain.swift index 948e0b0a..427151ab 100644 --- a/Sources/ContainersPreview/Protocols/Drain.swift +++ b/Sources/ContainersPreview/Protocols/Drain.swift @@ -171,46 +171,46 @@ extension Drain where Self: ~Copyable & ~Escapable, Element: ~Copyable { return true } - /// Skip at most the given number items in the underlying generative sequence, - /// decreasing it by the number of items successfully skipped. + /// Skip the given number items in the underlying generative sequence, + /// decreasing it by the number of items successfully skipped before hitting + /// the end of the sequence or an error. /// /// This is equivalent to generating the same number of items then immediately /// discarding them, except it may avoid the overhead of actually - /// materializing them. + /// materializing the elements. /// /// As soon as the producer has run out of items, all subsequent calls to - /// this method stop decrementing `remainder` and return false. + /// this method stop decrementing `n` and return false. /// - /// The default implementation of this method calls `generate(into:)` with - /// a small temporary buffer, immediately discarding all generated items. - /// Conforming types are encouraged to replace this default approach - /// with a more efficient implementation whenever it is possible to do so. + /// The default implementation of this method repeatedly calls + /// `generate(into:)` with a small temporary buffer, immediately discarding + /// all generated items. Conforming types are encouraged to replace this + /// default approach with a more efficient implementation whenever it is + /// possible to do so. /// /// ### Error handling /// /// This method throws an error to indicate a failure while trying to skip - /// the upcoming next item in the sequence. Failure may happen midway through - /// skipping a batch of items, in which case the `remainder` will still be + /// an upcoming item in the sequence. Failure may happen midway through + /// skipping a batch of items, in which case `n` will still be /// decremented by the number of elements that were successfully skipped - /// before encountering the problem. + /// before encountering the problem. This can be used to precisely track + /// the current position of the failed producer, allowing better diagnostics, + /// and allowing iteration to continue if the failure is resolvable. /// - /// - Parameter remainder: The maximum number of items remaining to skip. - /// This method decrements this value by the number of items it + /// - Parameter n: The number of items to skip. This must be greater than + /// zero. This method decrements this value by the number of items it /// successfully skipped before returning. - /// - Returns: A boolean value indicating whether the operation was able to - /// satisfy the request at least partially without hitting the end of the - /// underlying consumable sequence. @inlinable @_lifetime(self: copy self) - public mutating func skip( - upTo n: inout Int - ) -> Bool { // FIXME: Compiler crash when this declares throws(Failure) + public mutating func skip(by n: inout Int) { + // FIXME: Compiler crash when this declares throws(Failure) precondition(n >= 0, "Cannot skip a negative number of elements") - guard n > 0 else { return true } - let span = drainNext(maxCount: n) - let success = span.count > 0 - n &-= span.count - return success + while n > 0 { + let span = drainNext(maxCount: n) + guard !span.isEmpty else { return } + n &-= span.count + } } } diff --git a/Sources/ContainersPreview/Protocols/Producer.swift b/Sources/ContainersPreview/Protocols/Producer.swift index cbbfc7b6..384b1697 100644 --- a/Sources/ContainersPreview/Protocols/Producer.swift +++ b/Sources/ContainersPreview/Protocols/Producer.swift @@ -100,37 +100,38 @@ public protocol Producer: ~Copyable, ~Escapable { into target: inout OutputSpan ) throws(Failure) -> Bool - /// Skip at most the given number items in the underlying generative sequence, - /// decreasing it by the number of items successfully skipped. + /// Skip the given number items in the underlying generative sequence, + /// decreasing it by the number of items successfully skipped before hitting + /// the end of the sequence or an error. /// /// This is equivalent to generating the same number of items then immediately /// discarding them, except it may avoid the overhead of actually - /// materializing them. + /// materializing the elements. /// /// As soon as the producer has run out of items, all subsequent calls to /// this method stop decrementing `n` and return false. /// - /// The default implementation of this method calls `generate(into:)` with - /// a small temporary buffer, immediately discarding all generated items. - /// Conforming types are encouraged to replace this default approach - /// with a more efficient implementation whenever it is possible to do so. + /// The default implementation of this method repeatedly calls + /// `generate(into:)` with a small temporary buffer, immediately discarding + /// all generated items. Conforming types are encouraged to replace this + /// default approach with a more efficient implementation whenever it is + /// possible to do so. /// /// ### Error handling /// /// This method throws an error to indicate a failure while trying to skip - /// the upcoming next item in the sequence. Failure may happen midway through + /// an upcoming item in the sequence. Failure may happen midway through /// skipping a batch of items, in which case `n` will still be /// decremented by the number of elements that were successfully skipped - /// before encountering the problem. + /// before encountering the problem. This can be used to precisely track + /// the current position of the failed producer, allowing better diagnostics, + /// and allowing iteration to continue if the failure is resolvable. /// - /// - Parameter n: The maximum number of items remaining to skip. This - /// must be greater than zero. This method decrements this value by the - /// number of items it successfully skipped before returning. - /// - Returns: A boolean value indicating whether the operation was able to - /// skip at least one item without hitting the end of the underlying - /// sequence. + /// - Parameter n: The number of items to skip. This must be greater than + /// zero. This method decrements this value by the number of items it + /// successfully skipped before returning. @_lifetime(self: copy self) - mutating func skip(by n: inout Int) throws(Failure) -> Bool + mutating func skip(by n: inout Int) throws(Failure) /// Generate and return the next element in the underlying generative /// sequence. @@ -178,48 +179,89 @@ extension Producer where Self: ~Copyable & ~Escapable, Element: ~Copyable { @inline(__always) public var underestimatedCount: Int { 0 } - /// Skip at most the given number items in the underlying generative sequence, - /// decreasing it by the number of items successfully skipped. + /// Skip the given number items in the underlying generative sequence, + /// decreasing it by the number of items successfully skipped before hitting + /// the end of the sequence or an error. /// /// This is equivalent to generating the same number of items then immediately /// discarding them, except it may avoid the overhead of actually - /// materializing them. + /// materializing the elements. /// /// As soon as the producer has run out of items, all subsequent calls to /// this method stop decrementing `n` and return false. /// - /// The default implementation of this method calls `generate(into:)` with - /// a small temporary buffer, immediately discarding all generated items. - /// Conforming types are encouraged to replace this default approach - /// with a more efficient implementation whenever it is possible to do so. + /// The default implementation of this method repeatedly calls + /// `generate(into:)` with a small temporary buffer, immediately discarding + /// all generated items. Conforming types are encouraged to replace this + /// default approach with a more efficient implementation whenever it is + /// possible to do so. /// /// ### Error handling /// /// This method throws an error to indicate a failure while trying to skip - /// the upcoming next item in the sequence. Failure may happen midway through + /// an upcoming item in the sequence. Failure may happen midway through /// skipping a batch of items, in which case `n` will still be /// decremented by the number of elements that were successfully skipped - /// before encountering the problem. + /// before encountering the problem. This can be used to precisely track + /// the current position of the failed producer, allowing better diagnostics, + /// and allowing iteration to continue if the failure is resolvable. /// - /// - Parameter n: The maximum number of items remaining to skip. This - /// must be greater than zero. This method decrements this value by the - /// number of items it successfully skipped before returning. - /// - Returns: A boolean value indicating whether the operation was able to - /// skip at least one item without hitting the end of the underlying - /// sequence. + /// - Parameter n: The number of items to skip. This must be greater than + /// zero. This method decrements this value by the number of items it + /// successfully skipped before returning. @inlinable @_lifetime(self: copy self) - public mutating func skip(by n: inout Int) throws(Failure) -> Bool { + public mutating func skip(by n: inout Int) throws(Failure) { precondition(n > 0, "Cannot skip fewer than one item") - let maxBufferSize = 8 - return try withTemporaryOutputSpan( - of: Element.self, capacity: Swift.min(maxBufferSize, n) - ) { span throws(Failure) in - defer { n &-= span.count } - return try self.generate(into: &span) + let maxBufferSize = _producerBufferSize + return try withTemporaryAllocation( + of: Element.self, + capacity: Swift.min(maxBufferSize, n) + ) { buffer throws(Failure) in + repeat { + defer { n &-= buffer.count } + guard try self.generate(into: &buffer) else { return } + buffer.removeAll() + } while n > 0 } } + /// Skip the given number items in the underlying generative sequence, + /// returning the number of items successfully skipped before hitting the end + /// of the sequence. + /// + /// This is equivalent to generating the same number of items then immediately + /// discarding them, except it may avoid the overhead of actually + /// materializing the elements. + /// + /// If the producer runs out of items, all subsequent calls to + /// this method return zero without skipping any elements. + /// + /// ### Error handling + /// + /// This method throws an error to indicate a failure while trying to skip + /// an upcoming item in the sequence. Failure may happen midway through + /// skipping a batch of items, in which case this operation has no way to + /// report which item triggered the error. This is not an issue in the common + /// case when the iterator simply gets discarded anyway; however, when losing + /// position is not acceptable, it is recommended to avoid calling this + /// algorithm, and instead call the variant of `skip(by:)` that takes an inout + /// integer value. For example, this applies to use cases that need to report + /// the precise location of errors, and cases that are able to recover some + /// error conditions and want to be able to continue iterating without losing + /// data. + /// + /// - Returns: The number of items successfully skipped. This can be less than + /// `n` if the operation hits the end of the underlying sequence before + /// managing to skip the requested number of elements. + @inlinable + @_lifetime(self: copy self) + public mutating func skip(by n: Int) throws(Failure) -> Int { + var remainder = n + try self.skip(by: &remainder) + return n - remainder + } + /// Generate and return the next element in the underlying generative /// sequence. /// @@ -254,12 +296,11 @@ extension Producer where Self: ~Copyable & ~Escapable, Element: ~Copyable { @inlinable @_lifetime(self: copy self) public mutating func next() throws(Failure) -> Element? { - try _withUnsafeTemporaryAllocation( + try withTemporaryAllocation( of: Element.self, capacity: 1 ) { buffer throws(Failure) in - var span = OutputSpan(buffer: buffer, initializedCount: 0) - guard try self.generate(into: &span) else { return nil } - return span.removeLast() + guard try self.generate(into: &buffer) else { return nil } + return buffer.removeLast() } } } @@ -274,9 +315,8 @@ extension Producer where Self: ~Copyable & ~Escapable, Element: ~Copyable { _ message: String = "Invalid Producer" ) throws(Failure) { var c = 1 - if try !skip(by: &c) { - preconditionFailure(message) - } + try skip(by: &c) + precondition(c == 0, message) } } From 6210abf469eaf706f8ec5d14d4adf42ebae2e240 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 14 Jul 2026 17:46:43 -0700 Subject: [PATCH 33/50] Update Producer/Drain algorithms - Implement skip(by:) whenever possible --- .../BorrowingIteratorProtocol+Map.swift | 22 +++++++++ .../Protocols/Drain+Map.swift | 10 ++++- .../Protocols/Producer+Filter.swift | 2 + .../Protocols/Producer+Map.swift | 6 +++ .../Protocols/Producer+Reduce.swift | 45 +++++++++---------- .../Types/OutputSpan+Helpers.swift | 10 ++--- 6 files changed, 64 insertions(+), 31 deletions(-) diff --git a/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+Map.swift b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+Map.swift index 73affc6c..35d6fd4f 100644 --- a/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+Map.swift +++ b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+Map.swift @@ -115,6 +115,28 @@ where } return success } + + @inlinable + @_lifetime(self: copy self) + public mutating func skip(by n: inout Int) throws(Failure) { + precondition(n > 0, "Can't skip a negative number of elements") + if Failure.self == Never.self { + n -= try! _it.skip_(by: n) + return + } +#if false + // FIXME: Iterator's ill-conceived skip(by:) fails to report the position that triggers errors + try _it.skip_(by: &n) +#else + // We have no choice other than skipping items one by one, or allowing + // the base to materialize every element. The latter performs better in + // the common case of containers, so let's do that. + while n > 0 { + let span = try _it.nextSpan_(maxCount: n) + n -= span.count + } +#endif + } } #endif diff --git a/Sources/ContainersPreview/Protocols/Drain+Map.swift b/Sources/ContainersPreview/Protocols/Drain+Map.swift index 4feb9a10..9d041903 100644 --- a/Sources/ContainersPreview/Protocols/Drain+Map.swift +++ b/Sources/ContainersPreview/Protocols/Drain+Map.swift @@ -48,7 +48,7 @@ public struct DrainMapProducer< } @available(SwiftStdlib 5.0, *) -extension DrainMapProducer +extension DrainMapProducer: Producer where Base: ~Copyable & ~Escapable, Element: ~Copyable @@ -70,7 +70,7 @@ where @_lifetime(self: copy self) public mutating func generate( into target: inout OutputSpan - ) throws(Error) -> Bool { + ) throws(Failure) -> Bool { var success = false while !target.isFull { var source = _base.drainNext(maxCount: target.freeCapacity) @@ -82,6 +82,12 @@ where } return success } + + @inlinable + @_lifetime(self: copy self) + public mutating func skip(by n: inout Int) throws(Failure) { + _base.skip(by: &n) + } } #endif diff --git a/Sources/ContainersPreview/Protocols/Producer+Filter.swift b/Sources/ContainersPreview/Protocols/Producer+Filter.swift index da668868..e801694b 100644 --- a/Sources/ContainersPreview/Protocols/Producer+Filter.swift +++ b/Sources/ContainersPreview/Protocols/Producer+Filter.swift @@ -101,6 +101,8 @@ where } while target.count == startCount return target.count > startCount } + + // Note: We can't implement skip(by:) a better way than the default algorithm. } #endif diff --git a/Sources/ContainersPreview/Protocols/Producer+Map.swift b/Sources/ContainersPreview/Protocols/Producer+Map.swift index 3e2acba9..7d120eff 100644 --- a/Sources/ContainersPreview/Protocols/Producer+Map.swift +++ b/Sources/ContainersPreview/Protocols/Producer+Map.swift @@ -101,6 +101,12 @@ extension ConsumingMapProducer: Producer where Base: ~Copyable & ~Escapable { return result } } + + @inlinable + @_lifetime(self: copy self) + public mutating func skip(by n: inout Int) throws(Failure) { + try _base.skip(by: &n) + } } #endif diff --git a/Sources/ContainersPreview/Protocols/Producer+Reduce.swift b/Sources/ContainersPreview/Protocols/Producer+Reduce.swift index ee9684b2..89782a66 100644 --- a/Sources/ContainersPreview/Protocols/Producer+Reduce.swift +++ b/Sources/ContainersPreview/Protocols/Producer+Reduce.swift @@ -27,22 +27,20 @@ extension Producer where Self: ~Copyable & ~Escapable, Element: ~Copyable { ) throws(Failure) -> Result ) throws(Failure) -> Result { var initialResult: Optional = initialResult - return try _withUnsafeTemporaryAllocation( + return try withTemporaryAllocation( of: Element.self, capacity: _producerBufferSize ) { buffer throws(Failure) in var done = false - var result = initialResult.take()! - while !done { - var span = OutputSpan(buffer: buffer, initializedCount: 0) - done = try !self.generate(into: &span) - let c = span.finalize(for: buffer) - for i in 0 ..< c { - result = try nextPartialResult( - result, - buffer.moveElement(from: i)) + var result = initialResult.take() + repeat { + done = try !self.generate(into: &buffer) + try buffer._consumeAll { span throws(Failure) in + while let next = span.popFirst() { + result = try nextPartialResult(result.take()!, next) + } } - } - return result + } while !done + return result! } } @@ -53,23 +51,22 @@ extension Producer where Self: ~Copyable & ~Escapable, Element: ~Copyable { inout Result, consuming Element ) throws(Failure) -> Void ) throws(Failure) -> Result { - var result = initialResult - try _withUnsafeTemporaryAllocation( + var initialResult: Optional = initialResult + return try withTemporaryAllocation( of: Element.self, capacity: _producerBufferSize ) { buffer throws(Failure) in + var result = initialResult.take()! var done = false - while !done { - var span = OutputSpan(buffer: buffer, initializedCount: 0) - done = try !self.generate(into: &span) - let c = span.finalize(for: buffer) - for i in 0 ..< c { - try updateAccumulatingResult( - &result, - buffer.moveElement(from: i)) + repeat { + done = try !self.generate(into: &buffer) + try buffer._consumeAll { span throws(Failure) in + while let next = span.popFirst() { + try updateAccumulatingResult(&result, next) + } } - } + } while !done + return result } - return result } } diff --git a/Sources/ContainersPreview/Types/OutputSpan+Helpers.swift b/Sources/ContainersPreview/Types/OutputSpan+Helpers.swift index 0e2bfdb8..2389eb1a 100644 --- a/Sources/ContainersPreview/Types/OutputSpan+Helpers.swift +++ b/Sources/ContainersPreview/Types/OutputSpan+Helpers.swift @@ -35,14 +35,14 @@ extension OutputSpan where Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(self: copy self) - package mutating func _consumeAll( - consumingWith consumer: (inout InputSpan) -> Void - ) { - self.withUnsafeMutableBufferPointer { buffer, count in + package mutating func _consumeAll( + consumingWith consumer: (inout InputSpan) throws(Failure) -> Void + ) throws(Failure) { + try self.withUnsafeMutableBufferPointer { buffer, count throws(Failure) in var span = InputSpan( buffer: buffer._extracting(first: count), initializedCount: count) - consumer(&span) + try consumer(&span) _ = consume span count = 0 } From dcaffab0afb2419e826b220a7475a6230a322e7c Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 14 Jul 2026 17:53:40 -0700 Subject: [PATCH 34/50] Update Container MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Require Index to be Hashable - Add strong complexity expectations. Require `isEmpty`, `count` and `endIndex` to have O(1) complexity. Recommend most index navigation methods to be linear in the distance traveled. - Remove `index(alignedDown:)` and `index(alignedUp:)`; Collection views are far less relevant in this model, so index rounding is mostly unnecessary. (The need can still pop up when indices are shared between several views of layout-compatible Element types — such as a container of UInt64 than can also be interpreted as a container of UInt8; if that becomes a thing, we may need to bring these requirements back.) - Add `nextSpan(after:limitedBy:)` as an alternative to `nextSpan(after:maximumCount:)`. This makes it possible to provide fast default implementations for `distance(from:to:)` and `formIndex(_:offsetBy:limitedBy:)`. --- .../Container/BidirectionalContainer.swift | 7 +- .../Protocols/Container/Container.swift | 132 +++++++++++------- .../MinimalTypes/StaccatoContainer.swift | 10 +- 3 files changed, 93 insertions(+), 56 deletions(-) diff --git a/Sources/ContainersPreview/Protocols/Container/BidirectionalContainer.swift b/Sources/ContainersPreview/Protocols/Container/BidirectionalContainer.swift index d141dea9..ccc71ca7 100644 --- a/Sources/ContainersPreview/Protocols/Container/BidirectionalContainer.swift +++ b/Sources/ContainersPreview/Protocols/Container/BidirectionalContainer.swift @@ -82,8 +82,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { @inlinable public func distance(from start: Index, to end: Index) -> Int { - var i = self.index(alignedDown: start) - let end = self.index(alignedDown: end) + var i = start var d = 0 if start <= end { // FIXME: Use bulk iteration here, with binary search within the final chunk. @@ -103,7 +102,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { @inlinable public func index(_ index: Index, offsetBy n: Int) -> Index { - var index = self.index(alignedDown: index) + var index = index var n = n if n >= 0 { while n > 0 { @@ -130,9 +129,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { public func formIndex( _ index: inout Index, offsetBy n: inout Int, limitedBy limit: Index ) { - index = self.index(alignedDown: index) var n = n - let limit = self.index(alignedDown: limit) if n >= 0 { if index > limit { index = self.index(index, offsetBy: n) diff --git a/Sources/ContainersPreview/Protocols/Container/Container.swift b/Sources/ContainersPreview/Protocols/Container/Container.swift index 38a7b2bd..8617b329 100644 --- a/Sources/ContainersPreview/Protocols/Container/Container.swift +++ b/Sources/ContainersPreview/Protocols/Container/Container.swift @@ -19,7 +19,16 @@ public protocol Container: where Element: ~Copyable, Element == Element_, Failure_ == Never { associatedtype Element: ~Copyable - associatedtype Index: Equatable + + /// Indices are expected to implement `==` and `hash(into:)` with + /// constant complexity. + associatedtype Index: Equatable, Hashable + + // FIXME: We need Container to define a default value for BorrowingIterator, + // but we can only do that once ContainerIterator can support a + // nonescapable Base. + //associatedtype BorrowingIterator = ContainerIterator + // FIXME: Ideally Index should also be required to be Hashable. // FIXME: If we discard the separate BorrowingSequence abstraction, then we // should consider dropping Comparable and just having Equatable indices, so @@ -29,14 +38,26 @@ public protocol Container: // somewhere -- `RandomAccessContainer` or `BidirectionalContainer` would be // the obvious candidates. + /// - Complexity: Recommended to be O(1); conforming types must clearly + /// document deviations from this expectation. @_lifetime(borrow self) func makeBorrowingIterator(from start: Index) -> BorrowingIterator_ + + /// - Complexity: Recommended to be O(1); conforming types must clearly + /// document deviations from this expectation. func currentIndex(of iterator: borrowing BorrowingIterator_) -> Index + /// Complexity: O(1) var isEmpty: Bool { get } + + /// Complexity: O(1) var count: Int { get } + /// - Complexity: Recommended to be O(1); conforming types must clearly + /// document deviations from this expectation. var startIndex: Index { get } + + /// Complexity: Must be O(1) on all container types. var endIndex: Index { get } /// Returns the position immediately after the given index. @@ -44,12 +65,16 @@ public protocol Container: /// - Parameter index: A valid index of the container. `i` must be less /// than `endIndex`. /// - Returns: The index immediately following `i`. + /// - Complexity: Recommended to be O(1); conforming types must clearly + /// document deviations from this expectation. func index(after index: Index) -> Index /// Replaces the given index with its successor. /// /// - Parameter index: A valid index of the container. `i` must be less /// than `endIndex`. + /// - Complexity: Recommended to be O(1); conforming types must clearly + /// document deviations from this expectation. func formIndex(after index: inout Index) /// Returns an index that is the specified distance from the given index. @@ -63,6 +88,8 @@ public protocol Container: /// this is the same value as the result of `n` calls to `index(after:)`. /// If `n` is negative, this is the same value as the result of `abs(n)` /// calls to `index(before:)`. + /// - Complexity: Recommended to be O(`n`); conforming types must clearly + /// document deviations from this expectation. func index(_ index: Index, offsetBy n: Int) -> Index /// Offsets the given index by the specified distance, but no further than @@ -87,6 +114,8 @@ public protocol Container: /// If `n > 0`, a limit that is less than `index` has no effect. /// Likewise, if `n < 0`, a limit that is greater than `index` has no /// effect. + /// - Complexity: Recommended to be O(n); conforming types must clearly + /// document deviations from this expectation. func formIndex( _ index: inout Index, offsetBy n: inout Int, limitedBy limit: Index ) @@ -97,6 +126,9 @@ public protocol Container: /// - Parameter end: Another valid index of the collection. If end is equal /// to start, the result is zero. /// - Returns: The distance between `start` and `end`. + /// - Complexity: Recommended to be O(*d*), where *d* is the resulting + /// distance. Conforming types must clearly document deviations from this + /// expectation. func distance(from start: Index, to end: Index) -> Int /// Accesses the element at the specified position. @@ -108,7 +140,7 @@ public protocol Container: /// - Parameter position: The position of the element to access. /// `position` must be a valid index of the container that is not equal /// to the `endIndex` property. - /// - Complexity: O(1) + /// - Complexity: O(1). This is a hard requirement. subscript(index: Index) -> Element { borrow } /// Return a span over the container's storage that begins with the element at @@ -178,40 +210,18 @@ public protocol Container: /// If the input index is the end index, then this returns an empty span. /// Otherwise the result is non-empty, with its first element matching the /// element at the input index. + /// - Complexity: Recommended to be O(1). Conforming types must clearly + /// document deviations from this expectation. @_lifetime(borrow self) func nextSpan(after index: inout Index, maxCount: Int) -> Span - /// Return the nearest valid index in this container less than or equal to - /// the given index value, which must be valid in at least one view of self. - /// - /// This operation is important for container types that provide multiple - /// alternative projections (or "views") over the same underlying - /// representation, with each view conforming to `Container`, and sharing - /// the same `Index`. (Like `String` does with its UTF-8, UTF-16, - /// Unicode ccalar and character views in the `Collection` world.) - /// This rounding operation enables clients to convert/normalize valid index - /// values in one container view into valid indices in another, allowing them - /// to (easily) decide whether two (potentially misaligned) index values - /// address the same element. - /// - /// The default implementation of this operation simply returns `index`. - func index(alignedDown index: Index) -> Index - - /// Return the nearest valid index in this container greater than or equal to - /// the given index value, which must be valid in at least one view of self. - /// - /// This operation is important for container types that provide multiple - /// alternative projections (or "views") over the same underlying - /// representation, with each view conforming to `Container`, and sharing - /// the same `Index`. (Like `String` does with its UTF-8, UTF-16, - /// Unicode ccalar and character views in the `Collection` world.) - /// This rounding operation enables clients to convert/normalize valid index - /// values in one container view into valid indices in another, allowing them - /// to (easily) decide whether two (potentially misaligned) index values - /// address the same element. - /// - /// The default implementation of this operation simply returns `index`. - func index(alignedUp index: Index) -> Index + // 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 + ) -> Span func _customIndexOfEquatableElement(_ element: borrowing Element) -> Index?? func _customLastIndexOfEquatableElement(_ element: borrowing Element) -> Index?? @@ -264,7 +274,7 @@ extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { @_alwaysEmitIntoClient public var isEmpty: Bool { - startIndex == endIndex + count == 0 } @_alwaysEmitIntoClient @@ -283,7 +293,7 @@ extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { n >= 0, "Only BidirectionalContainers can be advanced by a negative amount") - var index = self.index(alignedDown: index) + var index = index var n = n #if true // with nextSpan(after:maxCount:) @@ -327,9 +337,6 @@ extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { n >= 0, "Only BidirectionalContainers can be advanced by a negative amount") - index = self.index(alignedDown: index) - let limit = self.index(alignedDown: limit) - // 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 { @@ -356,8 +363,6 @@ extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { // slower/larger. // FIXME: Linked lists may require an even slower implementation // to avoid looping (turtle/hare cycle detection). - let start = self.index(alignedDown: start) - let end = self.index(alignedDown: end) let limit = self.endIndex var a = start var b = end @@ -387,14 +392,17 @@ extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { // 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: Linked lists may require an even slower implementation - // to avoid looping (turtle/hare cycle detection). - let i = self.index(alignedDown: start) - let target = self.index(alignedDown: end) + // FIXME: Certain linked lists may require an even slower implementation + // to avoid looping indefinitely (turtle/hare cycle detection). + 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 } @@ -403,10 +411,14 @@ extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { } @_alwaysEmitIntoClient - public func index(alignedDown index: Index) -> Index { index } - - @_alwaysEmitIntoClient - public func index(alignedUp index: Index) -> Index { index } + @_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) + } @_alwaysEmitIntoClient public func _customIndexOfEquatableElement(_: borrowing Element) -> Index?? { @@ -421,6 +433,28 @@ extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { } } +@available(SwiftStdlib 6.4, *) +extension Container +where + Self: ~Copyable & ~Escapable, + Element: ~Copyable, + Index: Comparable +{ + @_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 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 + } + return d + } +} @available(SwiftStdlib 6.4, *) extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { @@ -429,5 +463,7 @@ extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { public var underestimatedCount_: Int { count } } +// FIXME: Add ambiguity resolvers against Collection's algorithms. + #endif diff --git a/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift b/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift index df021524..223e6194 100644 --- a/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift +++ b/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift @@ -109,7 +109,7 @@ public struct _StaccatoBorrowingIterator: BorrowingIteratorP } @available(SwiftStdlib 5.0, *) -public struct _StaccatoIndex: Comparable { +public struct _StaccatoIndex: Comparable, Hashable{ var _offset: Int init(_offset: Int) { self._offset = _offset @@ -122,6 +122,10 @@ public struct _StaccatoIndex: Comparable { public static func <(left: Self, right: Self) -> Bool { left._offset < right._offset } + + public func hash(into hasher: inout Hasher) { + hasher.combine(_offset) + } } @available(SwiftStdlib 5.0, *) @@ -139,8 +143,8 @@ extension StaccatoContainer: Iterable_ where Element: ~Copyable { extension StaccatoContainer: Container where Element: ~Copyable { public typealias Index = _StaccatoIndex - public var isEmpty: Bool { _contents.isEmpty } - public var count: Int { _contents.count } + public var isEmpty: Bool { count == 0 } + public var count: Int { _params._count } @_lifetime(borrow self) public func makeBorrowingIterator(from start: Index) -> BorrowingIterator_ { From ea581e47e191873dce193d09fc740bd66d634f2d Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 15 Jul 2026 15:10:23 -0700 Subject: [PATCH 35/50] Add UnfoldProducer --- Sources/ContainersPreview/CMakeLists.txt | 1 + .../Protocols/Producer+Unfold.swift | 86 +++++++++++++++++++ Xcode/Collections.xcodeproj/project.pbxproj | 4 + 3 files changed, 91 insertions(+) create mode 100644 Sources/ContainersPreview/Protocols/Producer+Unfold.swift diff --git a/Sources/ContainersPreview/CMakeLists.txt b/Sources/ContainersPreview/CMakeLists.txt index 7d85b8d3..35317ad1 100644 --- a/Sources/ContainersPreview/CMakeLists.txt +++ b/Sources/ContainersPreview/CMakeLists.txt @@ -69,6 +69,7 @@ target_sources(${module_name} PRIVATE "Protocols/Producer+Filter.swift" "Protocols/Producer+Map.swift" "Protocols/Producer+Reduce.swift" + "Protocols/Producer+Unfold.swift" "Types/InputSpan.swift" "Types/MutableRef.swift" "Types/OutputSpan+Helpers.swift" diff --git a/Sources/ContainersPreview/Protocols/Producer+Unfold.swift b/Sources/ContainersPreview/Protocols/Producer+Unfold.swift new file mode 100644 index 00000000..d4654537 --- /dev/null +++ b/Sources/ContainersPreview/Protocols/Producer+Unfold.swift @@ -0,0 +1,86 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// 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 +// +// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +#endif + +#if compiler(>=6.4) && UnstableContainersPreview + +@_lifetime(copy state) +public func producer< + State: ~Copyable & ~Escapable, + Failure: Error, + Element: ~Copyable +>( + state: consuming State, + next: @escaping (inout State) throws(Failure) -> Element? +) -> UnfoldProducer { + .init(state: state, next: next) +} + +@frozen +public struct UnfoldProducer< + State: ~Copyable & ~Escapable, + Failure: Error, + Element: ~Copyable +>: ~Copyable, ~Escapable { + @usableFromInline + internal let _next: (inout State) throws(Failure) -> Element? + + @usableFromInline + internal var _state: State + + @inlinable + @_lifetime(copy state) + public init( + state: consuming State, + next: @escaping (inout State) throws(Failure) -> Element? + ) { + self._next = next + self._state = state + } +} + +extension UnfoldProducer: Producer +where + State: ~Copyable & ~Escapable, + Element: ~Copyable +{ + @inlinable + public var underestimatedCount: Int { 0 } + + @inlinable + @discardableResult + @_lifetime(target: copy target) + @_lifetime(self: copy self) + public mutating func generate( + into target: inout OutputSpan + ) throws(Failure) -> Bool { + var c = 0 + while !target.isFull { + guard let next = try _next(&self._state) else { break } + target.append(next) + c += 1 + } + return c > 0 + } + + @inlinable + @_lifetime(self: copy self) + public mutating func next() throws(Failure) -> Element? { + try _next(&_state) + } +} + +#endif diff --git a/Xcode/Collections.xcodeproj/project.pbxproj b/Xcode/Collections.xcodeproj/project.pbxproj index d4a8b58a..6712ff1a 100644 --- a/Xcode/Collections.xcodeproj/project.pbxproj +++ b/Xcode/Collections.xcodeproj/project.pbxproj @@ -65,6 +65,7 @@ 7D2A779C2F27F2BF005780C7 /* Deque+ExpressibleByArrayLiteral.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A775C2F27F2BF005780C7 /* Deque+ExpressibleByArrayLiteral.swift */; }; 7D2A77A02F27F367005780C7 /* RefTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A779D2F27F367005780C7 /* RefTests.swift */; }; 7D2F598E2FAC229B00D43FE7 /* MutableRefTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2F598D2FAC229B00D43FE7 /* MutableRefTests.swift */; }; + 7D3F1F7B3007177100AD924D /* Producer+Unfold.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D3F1F7A3007176C00AD924D /* Producer+Unfold.swift */; }; 7D479CB02F450E4600A8CB59 /* RigidSet+BorrowingSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D479CAF2F450E3F00A8CB59 /* RigidSet+BorrowingSequence.swift */; }; 7D479CB32F45296A00A8CB59 /* UniqueSet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D479CB12F45296000A8CB59 /* UniqueSet.swift */; }; 7D479CB52F452D6900A8CB59 /* UniqueSetTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D479CB42F452D6700A8CB59 /* UniqueSetTests.swift */; }; @@ -691,6 +692,7 @@ 7D2A77762F27F2BF005780C7 /* UniqueDeque+Replacements.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueDeque+Replacements.swift"; sourceTree = ""; }; 7D2A779D2F27F367005780C7 /* RefTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RefTests.swift; sourceTree = ""; }; 7D2F598D2FAC229B00D43FE7 /* MutableRefTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MutableRefTests.swift; sourceTree = ""; }; + 7D3F1F7A3007176C00AD924D /* Producer+Unfold.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Producer+Unfold.swift"; sourceTree = ""; }; 7D479CAF2F450E3F00A8CB59 /* RigidSet+BorrowingSequence.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidSet+BorrowingSequence.swift"; sourceTree = ""; }; 7D479CB12F45296000A8CB59 /* UniqueSet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UniqueSet.swift; sourceTree = ""; }; 7D479CB42F452D6700A8CB59 /* UniqueSetTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UniqueSetTests.swift; sourceTree = ""; }; @@ -1364,6 +1366,7 @@ 7D57EDE62F64913C0029D5E3 /* Producer+Filter.swift */, 7D57EDD12F647DB10029D5E3 /* Producer+Map.swift */, 7D57EDD22F647DB10029D5E3 /* Producer+Reduce.swift */, + 7D3F1F7A3007176C00AD924D /* Producer+Unfold.swift */, ); path = Protocols; sourceTree = ""; @@ -2825,6 +2828,7 @@ 7D479CF32F47FB4100A8CB59 /* _HTable+Removal.swift in Sources */, 7DE9203529CA70F3004483EB /* OrderedSet+CustomReflectable.swift in Sources */, 7DEB31582F4E762200F9AF28 /* RigidDictionary+Equatable.swift in Sources */, + 7D3F1F7B3007177100AD924D /* Producer+Unfold.swift in Sources */, 7DE920C929CA70F4004483EB /* BitSet+BidirectionalCollection.swift in Sources */, 7DE920ED29CA70F4004483EB /* BitArray+Extras.swift in Sources */, 7DE9206829CA70F4004483EB /* BigString+Chunk+Append and Insert.swift in Sources */, From 99ac14d1fabbf656c756a2aa49f42c2162b1b0c4 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 17 Jul 2026 11:50:38 -0700 Subject: [PATCH 36/50] =?UTF-8?q?previousSpan(before:maxCount:)=20?= =?UTF-8?q?=E2=9F=B9=20spanBoundary(before:maxDistance:)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This allows MutableContainers to support mutating iteration backwards without requiring a separate MutableBidirectionalContainer protocol. --- .../RigidArray/RigidArray+Container.swift | 8 +++++++ .../UniqueArray/UniqueArray+Container.swift | 5 +++++ .../Conformances/InputSpan+Container.swift | 12 +++++------ .../Conformances/MutableSpan+Container.swift | 11 ++++------ .../Conformances/OutputSpan+Container.swift | 11 +++++----- .../Conformances/Span+Container.swift | 9 ++++---- .../Container/BidirectionalContainer.swift | 21 +++++++++++++++---- .../RigidDeque/RigidDeque+Container.swift | 8 +++++++ .../UniqueDeque/UniqueDeque+Container.swift | 6 ++++++ 9 files changed, 62 insertions(+), 29 deletions(-) diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Container.swift b/Sources/BasicContainers/RigidArray/RigidArray+Container.swift index 6ff71645..ec7900f3 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Container.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Container.swift @@ -458,6 +458,14 @@ extension RigidArray where Element: ~Copyable { return _mutableSpan(in: Range(uncheckedBounds: (start, index))) } + @_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) + } + @inlinable @_lifetime(borrow self) public func previousSpan( diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift index 3f6a5127..564f2e68 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift @@ -400,6 +400,11 @@ extension UniqueArray where Element: ~Copyable { _storage.nextMutableSpan(after: &index, maxCount: maxCount) } + @_alwaysEmitIntoClient + public func spanBoundary(before index: Index, maxDistance: Int) -> Index? { + _storage.spanBoundary(before: index, maxDistance: maxDistance) + } + @inlinable @_lifetime(borrow self) public func previousSpan( diff --git a/Sources/ContainersPreview/Conformances/InputSpan+Container.swift b/Sources/ContainersPreview/Conformances/InputSpan+Container.swift index d2b97f7f..0a9285bf 100644 --- a/Sources/ContainersPreview/Conformances/InputSpan+Container.swift +++ b/Sources/ContainersPreview/Conformances/InputSpan+Container.swift @@ -67,14 +67,12 @@ where Element: ~Copyable return _uncheckedMutableSpan(in: Range(uncheckedBounds: (start, start &+ c))) } - @inlinable - @_lifetime(borrow self) - public func previousSpan(before index: inout Int, maxCount: Int) -> Span { + @_alwaysEmitIntoClient + public func spanBoundary(before index: Index, maxDistance: Int) -> Index? { precondition(index >= 0 && index <= count, "Index out of bounds") - precondition(maxCount > 0, "maxCount must be positive") - let c = Swift.min(index, maxCount) - let end = capacity &- count &+ index - return _uncheckedSpan(in: Range(uncheckedBounds: (end &- c, end))) + precondition(maxDistance > 0, "maxDistance must be positive") + guard index > 0 else { return nil } + return Swift.max(0, index &- maxDistance) } } #endif diff --git a/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift b/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift index c16a28c3..d0d52af5 100644 --- a/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift +++ b/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift @@ -66,14 +66,11 @@ extension MutableSpan: RandomAccessContainer where Element: ~Copyable { } @_alwaysEmitIntoClient - @_lifetime(borrow self) - public func previousSpan( - before index: inout Int, maxCount: Int - ) -> Span { + public func spanBoundary(before index: Index, maxDistance: Int) -> Index? { precondition(index >= 0 && index <= count, "Index out of bounds") - precondition(maxCount > 0, "maxCount must be positive") - let limit = index &- Swift.min(maxCount, index) - return self.span.extracting(unchecked: Range(uncheckedBounds: (limit, index))) + precondition(maxDistance > 0, "maxDistance must be positive") + guard index > 0 else { return nil } + return Swift.max(0, index &- maxDistance) } } diff --git a/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift b/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift index ec0b2171..4d57fe50 100644 --- a/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift +++ b/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift @@ -64,13 +64,12 @@ where Element: ~Copyable return self.mutableSpan._consumingExtracting(Range(uncheckedBounds: (index, limit))) } - @inlinable - @_lifetime(borrow self) - public func previousSpan(before index: inout Int, maxCount: Int) -> Span { + @_alwaysEmitIntoClient + public func spanBoundary(before index: Index, maxDistance: Int) -> Index? { precondition(index >= 0 && index <= count, "Index out of bounds") - precondition(maxCount > 0, "maxCount must be positive") - let limit = Swift.max(0, index - maxCount) - return self.span.extracting(unchecked: Range(uncheckedBounds: (limit, index))) + precondition(maxDistance > 0, "maxDistance must be positive") + guard index > 0 else { return nil } + return Swift.max(0, index &- maxDistance) } } #endif diff --git a/Sources/ContainersPreview/Conformances/Span+Container.swift b/Sources/ContainersPreview/Conformances/Span+Container.swift index ab24c195..cdc7649f 100644 --- a/Sources/ContainersPreview/Conformances/Span+Container.swift +++ b/Sources/ContainersPreview/Conformances/Span+Container.swift @@ -59,12 +59,11 @@ extension Span: RandomAccessContainer where Element: ~Copyable { } @_alwaysEmitIntoClient - @_lifetime(borrow self) - public func previousSpan(before index: inout Int, maxCount: Int) -> Span { + public func spanBoundary(before index: Index, maxDistance: Int) -> Index? { precondition(index >= 0 && index <= count, "Index out of bounds") - precondition(maxCount > 0, "maxCount must be positive") - let limit = index &- Swift.min(maxCount, index) - return self.extracting(unchecked: Range(uncheckedBounds: (limit, index))) + precondition(maxDistance > 0, "maxDistance must be positive") + guard index > 0 else { return nil } + return Swift.max(0, index &- maxDistance) } } diff --git a/Sources/ContainersPreview/Protocols/Container/BidirectionalContainer.swift b/Sources/ContainersPreview/Protocols/Container/BidirectionalContainer.swift index ccc71ca7..f1de8e67 100644 --- a/Sources/ContainersPreview/Protocols/Container/BidirectionalContainer.swift +++ b/Sources/ContainersPreview/Protocols/Container/BidirectionalContainer.swift @@ -44,13 +44,12 @@ where Element: ~Copyable, Index: Comparable // // FIXME: Consider avoiding using `@_nonoverride`, reducing witness sizes. - func index(before i: Index) -> Index func formIndex(before i: inout Index) - @_lifetime(borrow self) - func previousSpan(before index: inout Index, maxCount: Int) -> Span + func spanBoundary(before index: Index, maxDistance: Int) -> Index? + override func index(after index: Index) -> Index @@ -63,12 +62,26 @@ where Element: ~Copyable, Index: Comparable ) @_nonoverride func distance(from start: Index, to end: Index) -> Int - } @available(SwiftStdlib 6.4, *) extension BidirectionalContainer where Self: ~Copyable & ~Escapable, Element: ~Copyable { + @_alwaysEmitIntoClient + @_lifetime(borrow self) + public func previousSpan( + before index: inout Index, maxCount: Int + ) -> Span { + guard let i = spanBoundary(before: index, maxDistance: maxCount) else { + return .init() + } + var j = i + let span = nextSpan(after: &j, maxCount: maxCount) + precondition(j == index, "Invalid BidirectionalContainer") + index = i + return span + } + @inlinable public func formIndex(before i: inout Index) { i = self.index(before: i) diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift index 6377acb5..81ca02fc 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift @@ -179,6 +179,14 @@ extension RigidDeque where Element: ~Copyable { mutating: &self) } + @_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) + } + @_alwaysEmitIntoClient @_lifetime(borrow self) public func previousSpan(before index: inout Int, maxCount: Int) -> Span { diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift index d5527471..14fe9ebb 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift @@ -104,6 +104,7 @@ extension UniqueDeque where Element: ~Copyable { _storage.nextSpan(after: &index, maxCount: maxCount) } + @_alwaysEmitIntoClient @_lifetime(&self) public mutating func nextMutableSpan( after index: inout Int, maxCount: Int @@ -111,6 +112,11 @@ extension UniqueDeque where Element: ~Copyable { _storage.nextMutableSpan(after: &index, maxCount: maxCount) } + @_alwaysEmitIntoClient + public func spanBoundary(before index: Index, maxDistance: Int) -> Index? { + _storage.spanBoundary(before: index, maxDistance: maxDistance) + } + @_alwaysEmitIntoClient @_lifetime(borrow self) public func previousSpan(before index: inout Int, maxCount: Int) -> Span { From 27fe58c42c42db1529f2267e3c5402d6265c437a Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 17 Jul 2026 11:51:20 -0700 Subject: [PATCH 37/50] =?UTF-8?q?Beef=20up=20ContainerIterator=E2=80=99s?= =?UTF-8?q?=20provided=20algorithms?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Protocols/Container/Container.swift | 19 +++++++++++-------- .../Container/ContainerIterator.swift | 13 ++++++++++++- 2 files changed, 23 insertions(+), 9 deletions(-) diff --git a/Sources/ContainersPreview/Protocols/Container/Container.swift b/Sources/ContainersPreview/Protocols/Container/Container.swift index 8617b329..d2fb3928 100644 --- a/Sources/ContainersPreview/Protocols/Container/Container.swift +++ b/Sources/ContainersPreview/Protocols/Container/Container.swift @@ -13,6 +13,10 @@ #if compiler(>=6.4) && UnstableContainersPreview +/// An `Iterable` that holds its elements in memory, so that we can form +/// references to them that aren't dependent on iteration state. +/// The contents of a container can be traversed multiple times, +/// nondestructively, and efficiently accessed. @available(SwiftStdlib 6.4, *) public protocol Container: Iterable_, ~Copyable, ~Escapable @@ -59,7 +63,7 @@ public protocol Container: /// Complexity: Must be O(1) on all container types. var endIndex: Index { get } - + /// Returns the position immediately after the given index. /// /// - Parameter index: A valid index of the container. `i` must be less @@ -68,7 +72,7 @@ public protocol Container: /// - Complexity: Recommended to be O(1); conforming types must clearly /// document deviations from this expectation. func index(after index: Index) -> Index - + /// Replaces the given index with its successor. /// /// - Parameter index: A valid index of the container. `i` must be less @@ -91,7 +95,7 @@ public protocol Container: /// - Complexity: Recommended to be O(`n`); conforming types must clearly /// document deviations from this expectation. func index(_ index: Index, offsetBy n: Int) -> Index - + /// Offsets the given index by the specified distance, but no further than /// the given limiting index. /// @@ -119,7 +123,7 @@ public protocol Container: func formIndex( _ index: inout Index, offsetBy n: inout Int, limitedBy limit: Index ) - + /// Returns the distance between two indices. /// /// - Parameter start: A valid index of the collection. @@ -147,8 +151,8 @@ public protocol Container: /// the given index, and extends to the end of the contiguous storage chunk /// that contains it, but no more than `maxCount` items. /// - /// On return, the index is updated to address the next item following the - /// end of the returned span. + /// On return, the index is updated to address the item following the + /// last element of the returned span. /// /// This method can be used to efficiently process the items of a container in /// bulk, by directly iterating over its piecewise contiguous pieces of @@ -168,7 +172,7 @@ public protocol Container: /// /// If the caller is able to process any number available items, it can signal /// that by passing `Int.max` as the `maxCount`, or simply by calling the - /// `nexSpan(after:)` method, which does precisely that. This is frequently + /// `nextSpan(after:)` method, which does precisely that. This is frequently /// the case when the caller simply wants to iterate over the entire /// container in a single loop. /// @@ -466,4 +470,3 @@ extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { // FIXME: Add ambiguity resolvers against Collection's algorithms. #endif - diff --git a/Sources/ContainersPreview/Protocols/Container/ContainerIterator.swift b/Sources/ContainersPreview/Protocols/Container/ContainerIterator.swift index 1e296def..3e3f5795 100644 --- a/Sources/ContainersPreview/Protocols/Container/ContainerIterator.swift +++ b/Sources/ContainersPreview/Protocols/Container/ContainerIterator.swift @@ -25,6 +25,17 @@ where public func makeBorrowingIterator_() -> BorrowingIterator_ { ContainerIterator(_borrowing: self, from: self.startIndex) } + + @_alwaysEmitIntoClient + @_lifetime(borrow self) + public func makeBorrowingIterator(from start: Index) -> BorrowingIterator_ { + ContainerIterator(_borrowing: self, from: start) + } + + @_alwaysEmitIntoClient + public func currentIndex(of iterator: borrowing BorrowingIterator_) -> Index { + iterator._position + } } @available(SwiftStdlib 6.4, *) @@ -43,7 +54,7 @@ where Base.Element: ~Copyable @_alwaysEmitIntoClient @_lifetime(borrow base) - package init(_borrowing base: borrowing @_addressable Base, from position: Base.Index) { + package init(_borrowing base: borrowing Base, from position: Base.Index) { self._base = Ref(base) self._position = position } From a7f6b90c991ef334c7f142035d124c8a1522937b Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 17 Jul 2026 16:57:26 -0700 Subject: [PATCH 38/50] 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 From 391693a8bab96800b73292234c5c5693a5aea666 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 17 Jul 2026 16:58:01 -0700 Subject: [PATCH 39/50] =?UTF-8?q?Review=20and=20update=20BidirectionalCont?= =?UTF-8?q?ainer=E2=80=99s=20default=20implementations?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Container/BidirectionalContainer.swift | 176 ++++++++---------- 1 file changed, 82 insertions(+), 94 deletions(-) diff --git a/Sources/ContainersPreview/Protocols/Container/BidirectionalContainer.swift b/Sources/ContainersPreview/Protocols/Container/BidirectionalContainer.swift index f1de8e67..e59e52de 100644 --- a/Sources/ContainersPreview/Protocols/Container/BidirectionalContainer.swift +++ b/Sources/ContainersPreview/Protocols/Container/BidirectionalContainer.swift @@ -50,7 +50,6 @@ where Element: ~Copyable, Index: Comparable func spanBoundary(before index: Index, maxDistance: Int) -> Index? - override func index(after index: Index) -> Index override func formIndex(after index: inout Index) @@ -67,6 +66,17 @@ where Element: ~Copyable, Index: Comparable @available(SwiftStdlib 6.4, *) extension BidirectionalContainer where Self: ~Copyable & ~Escapable, Element: ~Copyable { + @_alwaysEmitIntoClient + public func spanBoundary(before index: Index) -> Index? { + self.spanBoundary(before: index, maxDistance: Int.max) + } + + @_alwaysEmitIntoClient + @_lifetime(borrow self) + public func previousSpan(before index: inout Index) -> Span { + previousSpan(before: &index, maxCount: Int.max) + } + @_alwaysEmitIntoClient @_lifetime(borrow self) public func previousSpan( @@ -82,125 +92,103 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { return span } - @inlinable + @_alwaysEmitIntoClient + @_lifetime(borrow self) + public func previousSpan( + before index: inout Index, + limitedBy limit: Index + ) -> Span { + var j = index + let span = self.previousSpan(before: &j) + if limit <= index, limit > j { + let d = self.distance(from: limit, to: index) + index = limit + return span.extracting(last: d) + } + index = j + return span + } +} + +@available(SwiftStdlib 6.4, *) +extension BidirectionalContainer +where Self: ~Copyable & ~Escapable, Element: ~Copyable { + @_alwaysEmitIntoClient public func formIndex(before i: inout Index) { i = self.index(before: i) } - @inlinable - @_lifetime(borrow self) - public func previousSpan(before index: inout Index) -> Span { - previousSpan(before: &index, maxCount: Int.max) - } - - @inlinable - public func distance(from start: Index, to end: Index) -> Int { - var i = start - var d = 0 - if start <= end { - // FIXME: Use bulk iteration here, with binary search within the final chunk. - while i != end { - self.formIndex(after: &i) - d += 1 - } - } else { - // FIXME: Use bulk iteration here, with binary search within the final chunk. - while i != end { - self.formIndex(before: &i) - d -= 1 - } - } - return d - } - - @inlinable + @_alwaysEmitIntoClient public func index(_ index: Index, offsetBy n: Int) -> Index { var index = index var n = n if n >= 0 { while n > 0 { - let span = self.nextSpan(after: &index, maxCount: n) - precondition( - !span.isEmpty, - "Cannot advance index beyond the end of the container") - n &-= span.count + self.formIndex(after: &index) + n &-= 1 } } else { - n = -n - while n > 0 { - let span = self.previousSpan(before: &index, maxCount: n) - precondition( - !span.isEmpty, - "Cannot advance index beyond the end of the container") - n &-= span.count + while n < 0 { + self.formIndex(before: &index) + n &+= 1 } } return index } - @inlinable + @_alwaysEmitIntoClient public func formIndex( _ index: inout Index, offsetBy n: inout Int, limitedBy limit: Index ) { var n = n if n >= 0 { - if index > limit { + while n > 0 { + var j = index + let c = self.nextSpan(after: &j, limitedBy: limit).count + if c == 0 { + // We hit the limit (or the end) + break + } + if c > n { + index = self.index(index, offsetBy: n) + n = 0 + break + } + index = j + n &-= c + } + return + } + // Note: Don't negate `n` -- it may be `Int.min`. + while n < 0 { + let c = self.previousSpan(before: &index, limitedBy: limit).count + if c == 0 { + // We hit the limit (or the start) + return + } + n &+= c + if n > 0 { index = self.index(index, offsetBy: n) n = 0 return } - // Skip forward until we find our target or overshoot the limit. - while n > 0 { - var j = index - let span = self.nextSpan(after: &j, maxCount: n) - precondition( - !span.isEmpty, - "Cannot advance index beyond the end of the container") - if j > limit { - break - } - index = j - n &-= span.count - } - // Step through to find the precise target when we hit the limit. - // FIXME: Figure out a way to use binary search here (with `index(_:offsetBy:)`) - while n != 0 { - if index == limit { - return - } - formIndex(after: &index) - n &-= 1 - } - return - } - // n < 0 - if index < limit { - index = self.index(index, offsetBy: n) - n = 0 - return - } - // Skip backward until we find our target or overshoot the limit. - while n < 0 { - var j = index - let span = self.previousSpan(before: &j, maxCount: -n) - precondition( - !span.isEmpty, - "Cannot move index before the start of the container") - if j < limit { - break - } - index = j - n &+= span.count - } - // Step through to find the precise target when we hit the limit. - // FIXME: Figure out a way to use binary search here (with `index(_:offsetBy:)`) - while n != 0 { - if index == limit { - return - } - formIndex(before: &index) - n &+= 1 } } + + @_alwaysEmitIntoClient + public func index( + _ index: Index, offsetBy n: Int, limitedBy limit: Index + ) -> Index? { + var index = index + var n = n + self.formIndex(&index, offsetBy: &n, limitedBy: limit) + if n != 0 { return nil } + return index + } + + // Note: `distance(from:to:)` comes from `Container where Index: Comparable`. } + +// FIXME: Add ambiguity resolvers against BidirectionCollection algorithms. + #endif From e70b4df22894ea780db84a5c73c6846b49682be4 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Sat, 18 Jul 2026 14:14:13 -0700 Subject: [PATCH 40/50] Introduce Container.nextSpan(after:maxCount:limitedBy:) and make it the core Container primitive --- .../RigidArray/RigidArray+Container.swift | 28 +- .../RigidArray/RigidArray+Deprecated.swift | 5 +- .../UniqueArray/UniqueArray+Container.swift | 8 +- .../UniqueArray/UniqueArray+Deprecated.swift | 5 +- .../Conformances/InputSpan+Container.swift | 17 +- .../Conformances/MutableSpan+Container.swift | 8 +- .../Conformances/OutputSpan+Container.swift | 10 +- .../Conformances/Span+Container.swift | 34 +- .../Protocols/Container/Container.swift | 351 +++++++++--------- .../RigidDeque/RigidDeque+Container.swift | 23 +- .../UniqueDeque/UniqueDeque+Container.swift | 10 +- .../Span+Extras.swift | 31 ++ .../MinimalTypes/StaccatoContainer.swift | 12 +- 13 files changed, 290 insertions(+), 252 deletions(-) diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Container.swift b/Sources/BasicContainers/RigidArray/RigidArray+Container.swift index 0d647255..5e4cf41d 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Container.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Container.swift @@ -354,10 +354,6 @@ extension RigidArray where Element: ~Copyable { /// On return, `n` is set to zero if the operation succeeded without /// hitting the limit; otherwise, `n` reflects the number of steps that /// couldn't be taken. - /// - Parameter limit: A valid index of the array to use as a limit. - /// If `n > 0`, a limit that is less than `index` has no effect. - /// Likewise, if `n < 0`, a limit that is greater than `index` has no - /// effect. /// - Complexity: O(1) @_alwaysEmitIntoClient public func formIndex( @@ -366,6 +362,14 @@ extension RigidArray where Element: ~Copyable { index._advance(by: &n, limitedBy: limit) } + @inlinable + @_lifetime(borrow self) + public func nextSpan( + after index: inout Int + ) -> Span { + self.span._nextSpan(after: &index) + } + /// Return a span over the array's storage that begins with the element at /// the given index, and extends to the end of the contiguous storage chunk /// that contains it, but no more than `maxCount` items. @@ -429,6 +433,10 @@ extension RigidArray where Element: ~Copyable { /// to process immediately. `maxCount` must be greater than zero. /// If you are able to process an arbitrary number of items, set /// `maxCount` to `Int.max`, or call the `nextSpan(after:)` method. + /// - Parameter limit: A valid index of the array to use as a limit. + /// If `n > 0`, a limit that is less than `index` has no effect. + /// Likewise, if `n < 0`, a limit that is greater than `index` has no + /// effect. /// - Returns: A span over contiguous storage that starts at the given index. /// If the input index is the end index, then this returns an empty span. /// Otherwise the result is non-empty, with its first element matching the @@ -437,17 +445,9 @@ extension RigidArray where Element: ~Copyable { @inlinable @_lifetime(borrow self) public func nextSpan( - after index: inout Int, maxCount: Int + after index: inout Int, maxCount: Int, limitedBy limit: Index ) -> Span { - 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) + self.span._nextSpan(after: &index, maxCount: maxCount, limitedBy: limit) } @inlinable diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Deprecated.swift b/Sources/BasicContainers/RigidArray/RigidArray+Deprecated.swift index 68d90aa8..0aadedd8 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Deprecated.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Deprecated.swift @@ -21,7 +21,10 @@ extension RigidArray where Element: ~Copyable { public func nextSpan( after index: inout Int, maximumCount: Int ) -> Span { - self.nextSpan(after: &index, maxCount: maximumCount) + self.nextSpan( + after: &index, + maxCount: maximumCount, + limitedBy: self.endIndex) } @available(*, deprecated, renamed: "nextMutableSpan(after:maxCount:)") diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift index c674c81c..eb041b82 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift @@ -387,17 +387,17 @@ extension UniqueArray where Element: ~Copyable { @inlinable @_lifetime(borrow self) public func nextSpan( - after index: inout Int, maxCount: Int + after index: inout Int ) -> Span { - _storage.nextSpan(after: &index, maxCount: maxCount) + _storage.nextSpan(after: &index) } @_alwaysEmitIntoClient @_lifetime(borrow self) public func nextSpan( - after index: inout Int, limitedBy limit: Int? + after index: inout Int, maxCount: Int, limitedBy limit: Int ) -> Span { - _storage.nextSpan(after: &index, limitedBy: limit) + _storage.nextSpan(after: &index, maxCount: maxCount, limitedBy: limit) } @inlinable diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Deprecated.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Deprecated.swift index b1839027..21a47b37 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Deprecated.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Deprecated.swift @@ -21,7 +21,10 @@ extension UniqueArray where Element: ~Copyable { public func nextSpan( after index: inout Int, maximumCount: Int ) -> Span { - self.nextSpan(after: &index, maxCount: maximumCount) + self.nextSpan( + after: &index, + maxCount: maximumCount, + limitedBy: self.endIndex) } @available(*, deprecated, renamed: "nextMutableSpan(after:maxCount:)") diff --git a/Sources/ContainersPreview/Conformances/InputSpan+Container.swift b/Sources/ContainersPreview/Conformances/InputSpan+Container.swift index b9fed89a..c6e88a04 100644 --- a/Sources/ContainersPreview/Conformances/InputSpan+Container.swift +++ b/Sources/ContainersPreview/Conformances/InputSpan+Container.swift @@ -47,25 +47,16 @@ where Element: ~Copyable @_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 c = Swift.min(count &- index, maxCount) - let start = capacity &- count &+ index - return _uncheckedSpan(in: Range(uncheckedBounds: (start, start &+ c))) + public func nextSpan(after index: inout Index) -> Span { + self.span._nextSpan(after: &index) } @_alwaysEmitIntoClient @_lifetime(borrow self) public func nextSpan( - after index: inout Index, limitedBy limit: Index? + after index: inout Index, maxCount: Int, 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) + self.span._nextSpan(after: &index, maxCount: maxCount, limitedBy: limit) } @_alwaysEmitIntoClient diff --git a/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift b/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift index 8ec1ae2b..25760b26 100644 --- a/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift +++ b/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift @@ -57,17 +57,17 @@ extension MutableSpan: RandomAccessContainer where Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(borrow self) public func nextSpan( - after index: inout Int, maxCount: Int + after index: inout Int ) -> Span { - self.span._nextSpan(after: &index, maxCount: maxCount) + self.span._nextSpan(after: &index) } @_alwaysEmitIntoClient @_lifetime(borrow self) public func nextSpan( - after index: inout Index, limitedBy limit: Index? + after index: inout Index, maxCount: Int, limitedBy limit: Index ) -> Span { - self.span._nextSpan(after: &index, limitedBy: limit) + self.span._nextSpan(after: &index, maxCount: maxCount, limitedBy: limit) } @_alwaysEmitIntoClient diff --git a/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift b/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift index 0909be7a..e95408f3 100644 --- a/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift +++ b/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift @@ -46,14 +46,16 @@ where Element: ~Copyable @_alwaysEmitIntoClient @_lifetime(borrow self) - public func nextSpan(after index: inout Index, maxCount: Int) -> Span { - self.span._nextSpan(after: &index, maxCount: maxCount) + public func nextSpan(after index: inout Index) -> Span { + self.span._nextSpan(after: &index) } @_alwaysEmitIntoClient @_lifetime(borrow self) - public func nextSpan(after index: inout Index, limitedBy limit: Int?) -> Span { - self.span._nextSpan(after: &index, limitedBy: limit) + public func nextSpan( + after index: inout Index, maxCount: Int, limitedBy limit: Int + ) -> Span { + self.span._nextSpan(after: &index, maxCount: maxCount, limitedBy: limit) } @_alwaysEmitIntoClient diff --git a/Sources/ContainersPreview/Conformances/Span+Container.swift b/Sources/ContainersPreview/Conformances/Span+Container.swift index 4a6f2fd5..c20d33cc 100644 --- a/Sources/ContainersPreview/Conformances/Span+Container.swift +++ b/Sources/ContainersPreview/Conformances/Span+Container.swift @@ -52,47 +52,43 @@ extension Span where Element: ~Copyable { count } - // FIXME: This has the proper lifetime declaration but can't fulfill the Container requirement. @_alwaysEmitIntoClient @_lifetime(copy self) - public func _nextSpan(after index: inout Int, maxCount: Int) -> Self { + public func _nextSpan(after index: inout 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))) + let result = self.extracting(last: count - index) + index = count + return result } @_alwaysEmitIntoClient @_lifetime(borrow self) - public func nextSpan(after index: inout Int, maxCount: Int) -> Self { - _nextSpan(after: &index, maxCount: maxCount) + public func nextSpan(after index: inout Int) -> Self { + _nextSpan(after: &index) } // 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? + after index: inout Int, maxCount: Int, limitedBy limit: Int ) -> 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 + precondition(maxCount > 0, "maxCount must be positive") + precondition(limit >= 0 && limit <= count, "Index out of bounds") + var end = index &+ Swift.min(maxCount, count &- index) + if limit >= index, limit < end { + end = limit } - let range = Range(uncheckedBounds: (index, end)) - index = end - return self.extracting(unchecked: range) + return self.extracting(unchecked: Range(uncheckedBounds: (index, end))) } @_alwaysEmitIntoClient @_lifetime(borrow self) public func nextSpan( - after index: inout Index, limitedBy limit: Index? + after index: inout Int, maxCount: Int, limitedBy limit: Int ) -> Self { - _nextSpan(after: &index, limitedBy: limit) + _nextSpan(after: &index, maxCount: maxCount, limitedBy: limit) } @_alwaysEmitIntoClient diff --git a/Sources/ContainersPreview/Protocols/Container/Container.swift b/Sources/ContainersPreview/Protocols/Container/Container.swift index c4107a8d..36213044 100644 --- a/Sources/ContainersPreview/Protocols/Container/Container.swift +++ b/Sources/ContainersPreview/Protocols/Container/Container.swift @@ -64,6 +64,130 @@ public protocol Container: /// Complexity: Must be O(1) on all container types. var endIndex: Index { get } + /// Return a span over the container's storage that begins with the element at + /// the given index, and extends to the end of the contiguous storage chunk + /// that contains it. On return, the index is updated to address the next item + /// following the end of the returned span. + /// + /// This method can be used to efficiently process the items of a container in + /// bulk, by directly iterating over its piecewise contiguous pieces of + /// storage: + /// + /// var index = items.startIndex + /// while true { + /// let span = items.nextSpan(after: &index) + /// if span.isEmpty { break } + /// // Process items in `span` + /// } + /// + /// - Note: The spans returned by this method are not guaranteed to be + /// disjunct. Some containers may use the same storage chunk (or parts of a + /// storage chunk) multiple times, to repeat their contents. + /// + /// - Note: Repeated invocations of `nextSpan` on the same container and index + /// are not guaranteed to return identical results. (This is particularly + /// the case with containers that can store contents in their "inline" + /// representation. Such containers may not always have a unique address + /// in memory; the locations of the spans exposed by this method may vary + /// between different borrows of the same container.) + /// + /// - Parameter index: A valid index in the container, including the end + /// index. On return, this index is advanced by the count of the resulting + /// span, to simplify iteration. + /// - Returns: A span over contiguous storage that starts at the given index. + /// If the input index is the end index, then this returns an empty span. + /// Otherwise the result is non-empty, with its first element matching the + /// element at the input index. + @_lifetime(borrow self) + func nextSpan(after index: inout Index) -> Span + + /// Return a span over the container's storage that begins with the element at + /// the given index, and extends to the end of the contiguous storage chunk + /// that contains it, but no more than `maxCount` items, and no further than + /// the given limiting index (if any). + /// + /// On return, the index is updated to address the item following the + /// last element of the returned span. + /// + /// This method can be used to efficiently process the items of a container in + /// bulk, by directly iterating over its piecewise contiguous pieces of + /// storage: + /// + /// var index = items.startIndex + /// while true { + /// let span = items.nextSpan( + /// after: &index, + /// maxCount: 4, + /// limitedBy: items.endIndex) + /// if span.isEmpty { break } + /// // Process items in `span` + /// } + /// + /// The `maxCount` argument gives the caller control over the number of + /// items it receives from the iterator. This lets the caller avoid getting + /// more elements than it would be able to immediately process, which would + /// significantly complicate container use. + /// + /// If the caller is able to process any number available items, it can signal + /// that by passing `Int.max` as the `maxCount`, or simply by calling the + /// `nextSpan(after:)` method, which does precisely that. This is frequently + /// the case when the caller simply wants to iterate over the entire + /// container in a single loop. + /// + /// `maxCount` sets an upper bound. To read a specific number of items, + /// the caller usually needs to invoke `nextSpan` in a loop: + /// + /// var items: some Container + /// var index = items.startIndex + /// var remainder = numberOfItemsToRead + /// while remainder > 0 { + /// let next = items.nextSpan(after: &index, maxCount: remainder) + /// guard !next.isEmpty else { + /// // Container does not have enough items + /// break + /// } + /// remainder -= next.count + /// // Process items in `next` + /// } + /// + /// - Note: The spans returned by this method are not guaranteed to be + /// disjunct. Some containers may use the same storage chunk (or parts of a + /// storage chunk) multiple times, to repeat their contents. + /// + /// - Note: Repeated invocations of `nextSpan` on the same container and index + /// are not guaranteed to return identical results. (This is particularly + /// the case with containers that can store contents in their "inline" + /// representation. Such containers may not always have a unique address + /// in memory; the locations of the spans exposed by this method may vary + /// between different borrows of the same container.) + /// + /// - Parameter index: A valid index in the container, including the end + /// index. On return, this index is advanced by the count of the resulting + /// span, to simplify iteration. + /// - Parameter maxCount: The maximum number of items the caller is ready + /// to process. `maxCount` must be greater than zero. + /// If the client is able to process an arbitrary number of items, then + /// this can be signalled by setting `maxCount` to `Int.max`; calling + /// the `nextSpan(after:)` method is a more direct way to express the same. + /// - Parameter limit: A valid index of the container to use as a limit. + /// A limit that precedes `index` has no effect. Otherwise the method + /// stops before exceeding `limit`. If you don't have a specific limiting + /// index to use, you can set this to `endIndex` to allow the method to + /// traverse the entire container. + /// - Returns: A span over contiguous storage that starts at the given index. + /// If the input index is equal to the end index or `limit`, then this + /// returns an empty span. + /// Otherwise the result is non-empty, with its first element matching the + /// element at the input index. + /// - Complexity: Recommended to be O(1). Conforming types must clearly + /// document deviations from this expectation. + @_lifetime(borrow self) + func nextSpan( + after index: inout Index, + maxCount: Int, + limitedBy limit: Index + ) -> Span + /// Returns the position immediately after the given index. /// /// - Parameter index: A valid index of the container. `i` must be less @@ -147,84 +271,6 @@ public protocol Container: /// - Complexity: O(1). This is a hard requirement. subscript(index: Index) -> Element { borrow } - /// Return a span over the container's storage that begins with the element at - /// the given index, and extends to the end of the contiguous storage chunk - /// that contains it, but no more than `maxCount` items. - /// - /// On return, the index is updated to address the item following the - /// last element of the returned span. - /// - /// This method can be used to efficiently process the items of a container in - /// bulk, by directly iterating over its piecewise contiguous pieces of - /// storage: - /// - /// var index = items.startIndex - /// while true { - /// let span = items.nextSpan(after: &index, maxCount: 4) - /// if span.isEmpty { break } - /// // Process items in `span` - /// } - /// - /// The `maxCount` argument gives the caller control over the number of - /// items it receives from the iterator. This lets the caller avoid getting - /// more elements than it would be able to immediately process, which would - /// significantly complicate container use. - /// - /// If the caller is able to process any number available items, it can signal - /// that by passing `Int.max` as the `maxCount`, or simply by calling the - /// `nextSpan(after:)` method, which does precisely that. This is frequently - /// the case when the caller simply wants to iterate over the entire - /// container in a single loop. - /// - /// `maxCount` sets an upper bound. To read a specific number of items, - /// the caller usually needs to invoke `nextSpan` in a loop: - /// - /// var items: some Container - /// var index = items.startIndex - /// var remainder = numberOfItemsToRead - /// while remainder > 0 { - /// let next = items.nextSpan(after: &index, maxCount: remainder) - /// guard !next.isEmpty else { - /// // Container does not have enough items - /// break - /// } - /// remainder -= next.count - /// // Process items in `next` - /// } - /// - /// - Note: The spans returned by this method are not guaranteed to be - /// disjunct. Some containers may use the same storage chunk (or parts of a - /// storage chunk) multiple times, to repeat their contents. - /// - /// - Note: Repeated invocations of `nextSpan` on the same container and index - /// are not guaranteed to return identical results. (This is particularly - /// the case with containers that can store contents in their "inline" - /// representation. Such containers may not always have a unique address - /// in memory; the locations of the spans exposed by this method may vary - /// between different borrows of the same container.) - /// - /// - Parameter index: A valid index in the container, including the end - /// index. On return, this index is advanced by the count of the resulting - /// span, to simplify iteration. - /// - Parameter maxCount: The maximum number of items the caller is able - /// to process immediately. `maxCount` must be greater than zero. - /// If you are able to process an arbitrary number of items, set - /// `maxCount` to `Int.max`, or call the `nextSpan(after:)` method. - /// - Returns: A span over contiguous storage that starts at the given index. - /// If the input index is the end index, then this returns an empty span. - /// Otherwise the result is non-empty, with its first element matching the - /// element at the input index. - /// - Complexity: Recommended to be O(1). Conforming types must clearly - /// document deviations from this expectation. - @_lifetime(borrow self) - func nextSpan(after index: inout Index, maxCount: Int) -> Span - - @_lifetime(borrow self) - func nextSpan( - after index: inout Index, - limitedBy limit: Index? - ) -> Span - func _customIndexOfEquatableElement(_ element: borrowing Element) -> Index?? func _customLastIndexOfEquatableElement(_ element: borrowing Element) -> Index?? } @@ -238,44 +284,33 @@ extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { @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 - /// the given index, and extends to the end of the contiguous storage chunk - /// that contains it. On return, the index is updated to address the next item - /// following the end of the returned span. - /// - /// This method can be used to efficiently process the items of a container in - /// bulk, by directly iterating over its piecewise contiguous pieces of - /// storage: - /// - /// var index = items.startIndex - /// while true { - /// let span = items.nextSpan(after: &index) - /// if span.isEmpty { break } - /// // Process items in `span` - /// } - /// - /// - Note: The spans returned by this method are not guaranteed to be - /// disjunct. Some containers may use the same storage chunk (or parts of a - /// storage chunk) multiple times, to repeat their contents. - /// - /// - Note: Repeated invocations of `nextSpan` on the same container and index - /// are not guaranteed to return identical results. (This is particularly - /// the case with containers that can store contents in their "inline" - /// representation. Such containers may not always have a unique address - /// in memory; the locations of the spans exposed by this method may vary - /// between different borrows of the same container.) - /// - /// - Parameter index: A valid index in the container, including the end - /// index. On return, this index is advanced by the count of the resulting - /// span, to simplify iteration. - /// - Returns: A span over contiguous storage that starts at the given index. - /// If the input index is the end index, then this returns an empty span. - /// Otherwise the result is non-empty, with its first element matching the - /// element at the input index. @_alwaysEmitIntoClient + @_transparent @_lifetime(borrow self) - public func nextSpan(after index: inout Index) -> Span { - nextSpan(after: &index, limitedBy: nil) + public func nextSpan( + after index: inout Index + ) -> Span { + self.nextSpan(after: &index, maxCount: Int.max, limitedBy: self.endIndex) + } + + @_alwaysEmitIntoClient + @_transparent + @_lifetime(borrow self) + public func nextSpan( + after index: inout Index, + maxCount: Int + ) -> Span { + self.nextSpan(after: &index, maxCount: maxCount, limitedBy: self.endIndex) + } + + @_alwaysEmitIntoClient + @_transparent + @_lifetime(borrow self) + public func nextSpan( + after index: inout Index, + limitedBy limit: Index + ) -> Span { + self.nextSpan(after: &index, maxCount: Int.max, limitedBy: limit) } } @@ -286,13 +321,22 @@ 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 +#if false // count is required to be O(1), so it cannot have this default implementation @_alwaysEmitIntoClient public var count: Int { distance(from: startIndex, to: endIndex) } #endif + @_alwaysEmitIntoClient + public func index(after index: Index) -> Index { + let end = self.endIndex + var index = index + let c = self.nextSpan(after: &index, maxCount: 1, limitedBy: end).count + precondition(c == 1, "Can't advance beyond endIndex") + return index + } + @_alwaysEmitIntoClient public func formIndex(after index: inout Index) { index = self.index(after: index) @@ -300,30 +344,14 @@ extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { @_alwaysEmitIntoClient public func index(_ index: Index, offsetBy n: Int) -> Index { - precondition( - 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 + let end = self.endIndex while n > 0 { - let span = self.nextSpan(after: &index, maxCount: n) - precondition( - !span.isEmpty, - "Cannot advance index beyond the end of the container") - n &-= span.count + let c = self.nextSpan(after: &index, maxCount: n, limitedBy: end).count + precondition(c > 0, "Cannot advance index beyond the end of the container") + n &-= c } -#else - var index = index - var n = n - while n > 0 { - self.formIndex(after: &index) - n &-= 1 - } -#endif return index } @@ -335,15 +363,10 @@ extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { n >= 0, "Only BidirectionalContainers can be advanced by a negative amount") 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 + let c = self.nextSpan(after: &index, maxCount: n, limitedBy: limit).count + precondition(c <= n, "Invalid container") + guard c > 0 else { break } + n &-= c } } @@ -358,6 +381,21 @@ extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { return index } + @_alwaysEmitIntoClient + public func _customIndexOfEquatableElement(_: borrowing Element) -> Index?? { + nil + } + + @_alwaysEmitIntoClient + public func _customLastIndexOfEquatableElement( + _ element: borrowing Element + ) -> Index?? { + nil + } +} + +@available(SwiftStdlib 6.4, *) +extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { @_alwaysEmitIntoClient public func distance(from start: Index, to end: Index) -> Int { // This variant allows bulk iteration, but as we can't decide if @@ -373,31 +411,6 @@ extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { if j == start { return d2 } } } - - @_alwaysEmitIntoClient - @_lifetime(borrow self) - 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 - public func _customIndexOfEquatableElement(_: borrowing Element) -> Index?? { - nil - } - - @_alwaysEmitIntoClient - public func _customLastIndexOfEquatableElement( - _ element: borrowing Element - ) -> Index?? { - nil - } } @available(SwiftStdlib 6.4, *) diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift index 3a7dd349..6b513d6d 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift @@ -154,12 +154,9 @@ extension RigidDeque where Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(borrow self) - public func nextSpan(after index: inout Int, maxCount: Int) -> Span { + public func nextSpan(after index: inout Int) -> Span { _checkValidIndex(index) - precondition(maxCount > 0, "maxCount must be positive") - let segment = self._handle - .nextSegment(after: index) - ._extracting(first: maxCount) + let segment = self._handle.nextSegment(after: index) index &+= segment.count return _overrideLifetime(Span(_unsafeElements: segment), borrowing: self) } @@ -167,18 +164,18 @@ extension RigidDeque where Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(borrow self) public func nextSpan( - after index: inout Int, limitedBy limit: Int? + after index: inout Int, maxCount: Int, limitedBy limit: Int ) -> Span { _checkValidIndex(index) - let segment = self._handle.nextSegment(after: index) + _checkValidIndex(limit) + let segment = self._handle + .nextSegment(after: index) + ._extracting(first: maxCount) 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) - } + if limit >= index, span.count > limit &- index { + span = span.extracting(first: limit &- index) } - index += span.count + index &+= span.count return span } diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift index 1a420242..373a9ace 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift @@ -100,14 +100,16 @@ extension UniqueDeque where Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(borrow self) - public func nextSpan(after index: inout Int, maxCount: Int) -> Span { - _storage.nextSpan(after: &index, maxCount: maxCount) + public func nextSpan(after index: inout Int) -> Span { + _storage.nextSpan(after: &index) } @_alwaysEmitIntoClient @_lifetime(borrow self) - public func nextSpan(after index: inout Int, limitedBy limit: Int?) -> Span { - _storage.nextSpan(after: &index, limitedBy: limit) + public func nextSpan( + after index: inout Int, maxCount: Int, limitedBy limit: Int + ) -> Span { + _storage.nextSpan(after: &index, maxCount: maxCount, limitedBy: limit) } @_alwaysEmitIntoClient diff --git a/Sources/InternalCollectionsUtilities/Span+Extras.swift b/Sources/InternalCollectionsUtilities/Span+Extras.swift index de5d7ddc..35139dc2 100644 --- a/Sources/InternalCollectionsUtilities/Span+Extras.swift +++ b/Sources/InternalCollectionsUtilities/Span+Extras.swift @@ -110,4 +110,35 @@ extension Span where Element: Hashable /* & ~Copyable */ { } #endif +#if compiler(>=6.4) +@available(SwiftStdlib 5.0, *) +extension Span where Element: ~Copyable { + @_alwaysEmitIntoClient + @_lifetime(copy self) + package func clamped(to limits: borrowing Self) -> Self { + if self.isEmpty || limits.isEmpty { return .init() } + let buffer = self.withUnsafeBufferPointer { buffer in + limits.withUnsafeBufferPointer { limits in + let start = buffer.baseAddress! + let end = start + buffer.count + let limitStart = limits.baseAddress! + let limitEnd = limitStart + limits.count + + let clampedStart = ( + limitStart > start ? limitStart + : limitEnd < start ? limitEnd + : start) + let clampedEnd = ( + limitEnd < end ? limitEnd + : limitStart > end ? limitStart + : end) + let count = clampedEnd.distance(to: clampedStart) + return UnsafeBufferPointer(start: clampedStart, count: count) + } + } + return _overrideLifetime(Span(_unsafeElements: buffer), copying: self) + } +} +#endif + #endif diff --git a/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift b/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift index 94c1c702..19e6cbfb 100644 --- a/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift +++ b/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift @@ -204,28 +204,28 @@ extension StaccatoContainer: Container where Element: ~Copyable { @_lifetime(borrow self) public func nextSpan( - after index: inout Index, maxCount: Int + after index: inout Index ) -> Span { precondition(_isValid(index)) let startOffset = index._offset - let endOffset = _params.endOffset(fromOffset: index._offset, maxCount: maxCount) + let endOffset = _params.endOffset(fromOffset: index._offset, maxCount: Int.max) index._offset = endOffset return _contents.span.extracting(startOffset ..< endOffset) } @_lifetime(borrow self) public func nextSpan( - after index: inout Index, limitedBy limit: Index? + after index: inout Index, maxCount: Int, limitedBy limit: Index ) -> Span { precondition(_isValid(index)) - - var limit = limit ?? endIndex + precondition(_isValid(limit)) + var limit = limit if limit < index { limit = endIndex } let startOffset = index._offset let endOffset = _params.endOffset( fromOffset: index._offset, - maxCount: limit._offset - index._offset) + maxCount: Swift.min(limit._offset - index._offset, maxCount)) index._offset = endOffset return _contents.span.extracting(startOffset ..< endOffset) } From 95395ad9d2b99374b24bacb2baf55a07f0ad3153 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 20 Jul 2026 11:51:43 -0700 Subject: [PATCH 41/50] Add BidirectionalContainer.spanBoundary(before:maxDistance:limitedBy:) and make it the core primitive --- .../RigidArray/RigidArray+Container.swift | 17 ++- .../UniqueArray/UniqueArray+Container.swift | 17 ++- .../Conformances/InputSpan+Container.swift | 15 +- .../Conformances/MutableSpan+Container.swift | 13 +- .../Conformances/OutputSpan+Container.swift | 15 +- .../Conformances/Span+Container.swift | 17 ++- .../Container/BidirectionalContainer.swift | 141 +++++++++++------- .../RigidDeque/RigidDeque+Container.swift | 17 ++- .../UniqueDeque/UniqueDeque+Container.swift | 12 +- Sources/DequeModule/_UnsafeDequeHandle.swift | 26 ++++ 10 files changed, 214 insertions(+), 76 deletions(-) diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Container.swift b/Sources/BasicContainers/RigidArray/RigidArray+Container.swift index 5e4cf41d..89c8b468 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Container.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Container.swift @@ -463,18 +463,25 @@ extension RigidArray where Element: ~Copyable { } @_alwaysEmitIntoClient - public func spanBoundary(before index: Index, maxDistance: Int) -> Index? { + public func spanBoundary(before index: Index) -> (index: Index, distance: Int) { 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) + return (0, index) } - @inlinable + @_alwaysEmitIntoClient + public func spanBoundary( + before index: Index, maxDistance: Int, limitedBy limit: Index + ) -> (index: Index, distance: Int) { + self.span.spanBoundary( + before: index, maxDistance: maxDistance, limitedBy: limit) + } + + @_alwaysEmitIntoClient @_lifetime(borrow self) public func previousSpan( before index: inout Int, maxCount: Int ) -> Span { + // FIXME: Remove this in favor of the BidirectionalContainer algorithm. _checkValidIndex(index) precondition(maxCount > 0, "maxCount must be positive") let start = index diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift index eb041b82..86f4e4c3 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift @@ -409,15 +409,26 @@ extension UniqueArray where Element: ~Copyable { } @_alwaysEmitIntoClient - public func spanBoundary(before index: Index, maxDistance: Int) -> Index? { - _storage.spanBoundary(before: index, maxDistance: maxDistance) + public func spanBoundary( + before index: Index + ) -> (index: Index, distance: Int) { + _storage.spanBoundary(before: index) } - @inlinable + @_alwaysEmitIntoClient + public func spanBoundary( + before index: Index, maxDistance: Int, limitedBy limit: Index + ) -> (index: Index, distance: Int) { + _storage.spanBoundary( + before: index, maxDistance: maxDistance, limitedBy: limit) + } + + @_alwaysEmitIntoClient @_lifetime(borrow self) public func previousSpan( before index: inout Int, maxCount: Int ) -> Span { + // FIXME: Remove this in favor of the BidirectionalContainer algorithm. _storage.previousSpan(before: &index, maxCount: maxCount) } } diff --git a/Sources/ContainersPreview/Conformances/InputSpan+Container.swift b/Sources/ContainersPreview/Conformances/InputSpan+Container.swift index c6e88a04..75453beb 100644 --- a/Sources/ContainersPreview/Conformances/InputSpan+Container.swift +++ b/Sources/ContainersPreview/Conformances/InputSpan+Container.swift @@ -72,11 +72,20 @@ where Element: ~Copyable } @_alwaysEmitIntoClient - public func spanBoundary(before index: Index, maxDistance: Int) -> Index? { + public func spanBoundary(before index: Index) -> (index: Index, distance: Int) { precondition(index >= 0 && index <= count, "Index out of bounds") + return (0, index) + } + + @_alwaysEmitIntoClient + public func spanBoundary( + before index: Index, maxDistance: Int, limitedBy limit: Index + ) -> (index: Index, distance: Int) { + precondition(index >= 0 && index <= count, "Index out of bounds") + precondition(limit >= 0 && limit <= count, "Index out of bounds") precondition(maxDistance > 0, "maxDistance must be positive") - guard index > 0 else { return nil } - return Swift.max(0, index &- maxDistance) + let p = index._clampedDown(towards: 0, maxDistance: maxDistance, limitedBy: limit) + return (p, index &- p) } } #endif diff --git a/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift b/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift index 25760b26..950f6731 100644 --- a/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift +++ b/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift @@ -71,8 +71,17 @@ extension MutableSpan: RandomAccessContainer where Element: ~Copyable { } @_alwaysEmitIntoClient - public func spanBoundary(before index: Index, maxDistance: Int) -> Index? { - self.span.spanBoundary(before: index, maxDistance: maxDistance) + public func spanBoundary( + before index: Index + ) -> (index: Index, distance: Int) { + self.span.spanBoundary(before: index) + } + + @_alwaysEmitIntoClient + public func spanBoundary( + before index: Index, maxDistance: Int, limitedBy limit: Index + ) -> (index: Index, distance: Int) { + self.span.spanBoundary(before: index, maxDistance: maxDistance, limitedBy: limit) } } diff --git a/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift b/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift index e95408f3..5ac50db2 100644 --- a/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift +++ b/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift @@ -70,11 +70,20 @@ where Element: ~Copyable } @_alwaysEmitIntoClient - public func spanBoundary(before index: Index, maxDistance: Int) -> Index? { + public func spanBoundary(before index: Index) -> (index: Index, distance: Int) { precondition(index >= 0 && index <= count, "Index out of bounds") + return (0, index) + } + + @_alwaysEmitIntoClient + public func spanBoundary( + before index: Index, maxDistance: Int, limitedBy limit: Index + ) -> (index: Index, distance: Int) { + precondition(index >= 0 && index <= count, "Index out of bounds") + precondition(limit >= 0 && limit <= count, "Index out of bounds") precondition(maxDistance > 0, "maxDistance must be positive") - guard index > 0 else { return nil } - return Swift.max(0, index &- maxDistance) + let p = index._clampedDown(towards: 0, maxDistance: maxDistance, limitedBy: limit) + return (p, index &- p) } } #endif diff --git a/Sources/ContainersPreview/Conformances/Span+Container.swift b/Sources/ContainersPreview/Conformances/Span+Container.swift index c20d33cc..dcb2a835 100644 --- a/Sources/ContainersPreview/Conformances/Span+Container.swift +++ b/Sources/ContainersPreview/Conformances/Span+Container.swift @@ -92,11 +92,22 @@ extension Span where Element: ~Copyable { } @_alwaysEmitIntoClient - public func spanBoundary(before index: Index, maxDistance: Int) -> Index? { + public func spanBoundary( + before index: Index + ) -> (index: Index, distance: Int) { precondition(index >= 0 && index <= count, "Index out of bounds") + return (0, index) + } + + @_alwaysEmitIntoClient + public func spanBoundary( + before index: Index, maxDistance: Int, limitedBy limit: Index + ) -> (index: Index, distance: Int) { + precondition(index >= 0 && index <= count, "Index out of bounds") + precondition(limit >= 0 && limit <= count, "Index out of bounds") precondition(maxDistance > 0, "maxDistance must be positive") - guard index > 0 else { return nil } - return Swift.max(0, index &- maxDistance) + let p = index._clampedDown(towards: 0, maxDistance: maxDistance, limitedBy: limit) + return (p, index &- p) } } diff --git a/Sources/ContainersPreview/Protocols/Container/BidirectionalContainer.swift b/Sources/ContainersPreview/Protocols/Container/BidirectionalContainer.swift index e59e52de..591e99cc 100644 --- a/Sources/ContainersPreview/Protocols/Container/BidirectionalContainer.swift +++ b/Sources/ContainersPreview/Protocols/Container/BidirectionalContainer.swift @@ -48,7 +48,11 @@ where Element: ~Copyable, Index: Comparable func formIndex(before i: inout Index) - func spanBoundary(before index: Index, maxDistance: Int) -> Index? + func spanBoundary(before index: Index) -> (index: Index, distance: Int) + + func spanBoundary( + before index: Index, maxDistance: Int, limitedBy limit: Index + ) -> (index: Index, distance: Int) override func index(after index: Index) -> Index @@ -67,45 +71,54 @@ where Element: ~Copyable, Index: Comparable extension BidirectionalContainer where Self: ~Copyable & ~Escapable, Element: ~Copyable { @_alwaysEmitIntoClient - public func spanBoundary(before index: Index) -> Index? { - self.spanBoundary(before: index, maxDistance: Int.max) + @_transparent + public func spanBoundary( + before index: Index + ) -> (index: Index, distance: Int) { + self.spanBoundary( + before: index, + maxDistance: Int.max, + limitedBy: self.endIndex) } @_alwaysEmitIntoClient - @_lifetime(borrow self) - public func previousSpan(before index: inout Index) -> Span { - previousSpan(before: &index, maxCount: Int.max) + @_transparent + public func spanBoundary( + before index: Index, + maxDistance: Int + ) -> (index: Index, distance: Int) { + self.spanBoundary( + before: index, + maxDistance: maxDistance, + limitedBy: self.endIndex) } @_alwaysEmitIntoClient + @_transparent @_lifetime(borrow self) public func previousSpan( - before index: inout Index, maxCount: Int + before index: inout Index, + maxCount: Int = Int.max ) -> Span { - guard let i = spanBoundary(before: index, maxDistance: maxCount) else { - return .init() - } - var j = i - let span = nextSpan(after: &j, maxCount: maxCount) - precondition(j == index, "Invalid BidirectionalContainer") - index = i - return span + self.previousSpan( + before: &index, + maxCount: maxCount, + limitedBy: self.endIndex) } @_alwaysEmitIntoClient @_lifetime(borrow self) public func previousSpan( before index: inout Index, + maxCount: Int = Int.max, limitedBy limit: Index ) -> Span { - var j = index - let span = self.previousSpan(before: &j) - if limit <= index, limit > j { - let d = self.distance(from: limit, to: index) - index = limit - return span.extracting(last: d) - } - index = j + let (i, d) = spanBoundary(before: index, maxDistance: maxCount, limitedBy: limit) + if d == 0 { return .init() } + var j = i + let span = nextSpan(after: &j, limitedBy: index) + precondition(j == index && span.count <= maxCount, "Invalid BidirectionalContainer") + index = i return span } } @@ -113,6 +126,11 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { @available(SwiftStdlib 6.4, *) extension BidirectionalContainer where Self: ~Copyable & ~Escapable, Element: ~Copyable { + @_alwaysEmitIntoClient + public func index(before i: Index) -> Index { + self.spanBoundary(before: i, maxDistance: 1).index + } + @_alwaysEmitIntoClient public func formIndex(before i: inout Index) { i = self.index(before: i) @@ -122,16 +140,20 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { public func index(_ index: Index, offsetBy n: Int) -> Index { var index = index var n = n + let end = self.endIndex if n >= 0 { while n > 0 { - self.formIndex(after: &index) - n &-= 1 - } - } else { - while n < 0 { - self.formIndex(before: &index) - n &+= 1 + let c = self.nextSpan(after: &index, maxCount: n, limitedBy: end).count + precondition(c > 0, "Cannot advance index beyond the end of the container") + n &-= c } + return index + } + n = -n + while n > 0 { + let r = self.spanBoundary(before: index, maxDistance: n, limitedBy: end) + index = r.index + n &-= r.distance } return index } @@ -143,35 +165,22 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { var n = n if n >= 0 { while n > 0 { - var j = index - let c = self.nextSpan(after: &j, limitedBy: limit).count - if c == 0 { - // We hit the limit (or the end) - break - } - if c > n { - index = self.index(index, offsetBy: n) - n = 0 - break - } - index = j + let c = self.nextSpan(after: &index, maxCount: n, limitedBy: limit).count + precondition(c <= n, "Invalid container") + guard c > 0 else { break } n &-= c } return } - // Note: Don't negate `n` -- it may be `Int.min`. - while n < 0 { - let c = self.previousSpan(before: &index, limitedBy: limit).count - if c == 0 { + n = -n + while n > 0 { + let r = self.spanBoundary(before: index, maxDistance: n, limitedBy: limit) + if r.distance == 0 { // We hit the limit (or the start) return } - n &+= c - if n > 0 { - index = self.index(index, offsetBy: n) - n = 0 - return - } + n &+= r.distance + index = r.index } } @@ -189,6 +198,34 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { // Note: `distance(from:to:)` comes from `Container where Index: Comparable`. } +extension Strideable { + @_alwaysEmitIntoClient + package func _clampedUp( + towards boundary: Self, maxDistance: Stride, limitedBy limit: Self + ) -> Self { + assert(self <= boundary) + assert(maxDistance >= 0) + let limit = (limit >= self ? Swift.min(limit, boundary) : boundary) + if limit.distance(to: self) <= maxDistance { + return limit + } + return self.advanced(by: maxDistance) + } + + @_alwaysEmitIntoClient + package func _clampedDown( + towards boundary: Self, maxDistance: Stride, limitedBy limit: Self + ) -> Self { + assert(self >= boundary) + assert(maxDistance >= 0) + let limit = (limit <= self ? Swift.max(limit, boundary) : boundary) + if self.distance(to: limit) <= maxDistance { + return limit + } + return self.advanced(by: -maxDistance) + } +} + // FIXME: Add ambiguity resolvers against BidirectionCollection algorithms. #endif diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift index 6b513d6d..72a26205 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift @@ -195,16 +195,27 @@ extension RigidDeque where Element: ~Copyable { } @_alwaysEmitIntoClient - public func spanBoundary(before index: Index, maxDistance: Int) -> Index? { + public func spanBoundary(before index: Index) -> (index: Index, distance: Int) { precondition(index >= 0 && index <= count, "Index out of bounds") + let r = self._handle.spanBoundary(before: index) + return (r.offset, r.distance) + } + + @_alwaysEmitIntoClient + public func spanBoundary( + before index: Index, maxDistance: Int, limitedBy limit: Index + ) -> (index: Index, distance: Int) { + precondition(index >= 0 && index <= count, "Index out of bounds") + precondition(limit >= 0 && limit <= count, "Index out of bounds") precondition(maxDistance > 0, "maxDistance must be positive") - guard index > 0 else { return nil } - return Swift.max(0, index &- maxDistance) + let r = self._handle.spanBoundary(before: index, maxDistance: maxDistance, limitedBy: limit) + return (r.offset, r.distance) } @_alwaysEmitIntoClient @_lifetime(borrow self) public func previousSpan(before index: inout Int, maxCount: Int) -> Span { + // FIXME: Remove this in favor of the BidirectionalContainer algorithm. _checkValidIndex(index) precondition(maxCount > 0, "maxCount must be positive") let segment = self._handle diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift index 373a9ace..42b06bde 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift @@ -121,13 +121,21 @@ extension UniqueDeque where Element: ~Copyable { } @_alwaysEmitIntoClient - public func spanBoundary(before index: Index, maxDistance: Int) -> Index? { - _storage.spanBoundary(before: index, maxDistance: maxDistance) + public func spanBoundary(before index: Index) -> (index: Index, distance: Int) { + _storage.spanBoundary(before: index) + } + + @_alwaysEmitIntoClient + public func spanBoundary( + before index: Index, maxDistance: Int, limitedBy limit: Index + ) -> (index: Index, distance: Int) { + _storage.spanBoundary(before: index, maxDistance: maxDistance, limitedBy: limit) } @_alwaysEmitIntoClient @_lifetime(borrow self) public func previousSpan(before index: inout Int, maxCount: Int) -> Span { + // FIXME: Remove this in favor of the BidirectionalContainer algorithm. _storage.previousSpan(before: &index, maxCount: maxCount) } } diff --git a/Sources/DequeModule/_UnsafeDequeHandle.swift b/Sources/DequeModule/_UnsafeDequeHandle.swift index 3281eb17..f686da1c 100644 --- a/Sources/DequeModule/_UnsafeDequeHandle.swift +++ b/Sources/DequeModule/_UnsafeDequeHandle.swift @@ -369,6 +369,32 @@ extension _UnsafeDequeHandle where Element: ~Copyable { count: position - capacity) } + @_alwaysEmitIntoClient + internal func spanBoundary( + before startOffset: Int + ) -> (offset: Int, distance: Int) { + assert(startOffset >= 0 && startOffset <= count) + let wrapOffset = capacity &- startSlot.position + if startOffset <= wrapOffset { + return (0, startOffset) + } + return (wrapOffset, startOffset &- wrapOffset) + } + + @_alwaysEmitIntoClient + internal func spanBoundary( + before startOffset: Int, maxDistance: Int, limitedBy limitOffset: Int + ) -> (offset: Int, distance: Int) { + assert(startOffset >= 0 && startOffset <= count) + assert(limitOffset >= 0 && limitOffset <= count) + let wrapOffset = capacity &- startSlot.position + let p = startOffset._clampedDown( + towards: startOffset <= wrapOffset ? 0 : wrapOffset, + maxDistance: maxDistance, + limitedBy: limitOffset) + return (p, p &- startOffset) + } + @_alwaysEmitIntoClient internal func segments() -> _UnsafeDequeSegments { guard _buffer.baseAddress != nil else { From ef0fba7f7fadd1b9aba38734a89365ba9b263950 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 20 Jul 2026 15:42:11 -0700 Subject: [PATCH 42/50] Resolve some implementation issues --- .../RigidArray/RigidArray+Container.swift | 2 +- .../Conformances/Span+Container.swift | 4 +- .../Container/BidirectionalContainer.swift | 28 ------------- .../Container/Strideable+Limits.swift | 28 +++++++++++++ .../RigidDeque/RigidDeque+Container.swift | 13 ++----- Sources/DequeModule/_UnsafeDequeHandle.swift | 39 +++++++++++++------ 6 files changed, 64 insertions(+), 50 deletions(-) diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Container.swift b/Sources/BasicContainers/RigidArray/RigidArray+Container.swift index 89c8b468..dafdc0cb 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Container.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Container.swift @@ -486,7 +486,7 @@ extension RigidArray where Element: ~Copyable { precondition(maxCount > 0, "maxCount must be positive") let start = index index = start &- Swift.min(maxCount, start) - return _span(in: Range(uncheckedBounds: (index, start))) + return _span(in: Range(uncheckedBounds: (start, index))) } } diff --git a/Sources/ContainersPreview/Conformances/Span+Container.swift b/Sources/ContainersPreview/Conformances/Span+Container.swift index dcb2a835..55cdd921 100644 --- a/Sources/ContainersPreview/Conformances/Span+Container.swift +++ b/Sources/ContainersPreview/Conformances/Span+Container.swift @@ -80,7 +80,9 @@ extension Span where Element: ~Copyable { if limit >= index, limit < end { end = limit } - return self.extracting(unchecked: Range(uncheckedBounds: (index, end))) + let r = self.extracting(unchecked: Range(uncheckedBounds: (index, end))) + index = end + return r } @_alwaysEmitIntoClient diff --git a/Sources/ContainersPreview/Protocols/Container/BidirectionalContainer.swift b/Sources/ContainersPreview/Protocols/Container/BidirectionalContainer.swift index 591e99cc..d3b80be4 100644 --- a/Sources/ContainersPreview/Protocols/Container/BidirectionalContainer.swift +++ b/Sources/ContainersPreview/Protocols/Container/BidirectionalContainer.swift @@ -198,34 +198,6 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { // Note: `distance(from:to:)` comes from `Container where Index: Comparable`. } -extension Strideable { - @_alwaysEmitIntoClient - package func _clampedUp( - towards boundary: Self, maxDistance: Stride, limitedBy limit: Self - ) -> Self { - assert(self <= boundary) - assert(maxDistance >= 0) - let limit = (limit >= self ? Swift.min(limit, boundary) : boundary) - if limit.distance(to: self) <= maxDistance { - return limit - } - return self.advanced(by: maxDistance) - } - - @_alwaysEmitIntoClient - package func _clampedDown( - towards boundary: Self, maxDistance: Stride, limitedBy limit: Self - ) -> Self { - assert(self >= boundary) - assert(maxDistance >= 0) - let limit = (limit <= self ? Swift.max(limit, boundary) : boundary) - if self.distance(to: limit) <= maxDistance { - return limit - } - return self.advanced(by: -maxDistance) - } -} - // FIXME: Add ambiguity resolvers against BidirectionCollection algorithms. #endif diff --git a/Sources/ContainersPreview/Protocols/Container/Strideable+Limits.swift b/Sources/ContainersPreview/Protocols/Container/Strideable+Limits.swift index 0e090a09..ff29f1e0 100644 --- a/Sources/ContainersPreview/Protocols/Container/Strideable+Limits.swift +++ b/Sources/ContainersPreview/Protocols/Container/Strideable+Limits.swift @@ -11,6 +11,34 @@ // //===----------------------------------------------------------------------===// +extension Strideable { + @_alwaysEmitIntoClient + package func _clampedUp( + towards boundary: Self, maxDistance: Stride, limitedBy limit: Self + ) -> Self { + assert(self <= boundary) + assert(maxDistance >= 0) + let limit = (limit >= self ? Swift.min(limit, boundary) : boundary) + if limit.distance(to: self) <= maxDistance { + return limit + } + return self.advanced(by: maxDistance) + } + + @_alwaysEmitIntoClient + package func _clampedDown( + towards boundary: Self, maxDistance: Stride, limitedBy limit: Self + ) -> Self { + assert(self >= boundary) + assert(maxDistance >= 0) + let limit = (limit <= self ? Swift.max(limit, boundary) : boundary) + if self.distance(to: limit) <= maxDistance { + return limit + } + return self.advanced(by: -maxDistance) + } +} + extension Strideable { @inlinable package mutating func _advance( diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift index 72a26205..c54ee4c4 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift @@ -168,15 +168,10 @@ extension RigidDeque where Element: ~Copyable { ) -> Span { _checkValidIndex(index) _checkValidIndex(limit) - let segment = self._handle - .nextSegment(after: index) - ._extracting(first: maxCount) - var span = _overrideLifetime(Span(_unsafeElements: segment), borrowing: self) - if limit >= index, span.count > limit &- index { - span = span.extracting(first: limit &- index) - } - index &+= span.count - return span + precondition(maxCount > 0, "maxCount must be positive") + let segment = self._handle.nextSegment( + after: &index, maxCount: maxCount, limitedBy: limit) + return _overrideLifetime(Span(_unsafeElements: segment), borrowing: self) } @_lifetime(&self) diff --git a/Sources/DequeModule/_UnsafeDequeHandle.swift b/Sources/DequeModule/_UnsafeDequeHandle.swift index f686da1c..23769e1a 100644 --- a/Sources/DequeModule/_UnsafeDequeHandle.swift +++ b/Sources/DequeModule/_UnsafeDequeHandle.swift @@ -331,17 +331,17 @@ extension _UnsafeDequeHandle where Element: ~Copyable { extension _UnsafeDequeHandle where Element: ~Copyable { @_alwaysEmitIntoClient internal func nextSegment( - after startOffset: Int + after offset: Int ) -> UnsafeBufferPointer { - assert(startOffset >= 0 && startOffset <= count) + assert(offset >= 0 && offset <= count) guard _buffer.baseAddress != nil else { return .init(._empty) } - let position = startSlot.position &+ startOffset + let position = startSlot.position &+ offset if position < capacity { return UnsafeBufferPointer( start: ptr(at: Slot(at: position)), - count: Swift.min(count &- startOffset, capacity &- position)) + count: Swift.min(count &- offset, capacity &- position)) } // We're after the wrap return UnsafeBufferPointer( @@ -350,23 +350,40 @@ extension _UnsafeDequeHandle where Element: ~Copyable { } @_alwaysEmitIntoClient - internal func previousSegment( - before startOffset: Int + internal func nextSegment( + after offset: inout Int, + maxCount: Int, + limitedBy limit: Int ) -> UnsafeBufferPointer { - assert(startOffset >= 0 && startOffset <= count) + assert(limit >= 0 && limit <= count) + assert(maxCount > 0) + var segment = self.nextSegment(after: offset) + ._extracting(first: maxCount) + if limit >= offset, segment.count > limit &- offset { + segment = segment._extracting(first: limit &- offset) + } + offset &+= segment.count + return segment + } + + @_alwaysEmitIntoClient + internal func previousSegment( + before offset: Int + ) -> UnsafeBufferPointer { + assert(offset >= 0 && offset <= count) guard _buffer.baseAddress != nil else { return .init(._empty) } - let position = startSlot.position &+ startOffset - if position <= capacity { + let slot = startSlot.position &+ offset + if slot <= capacity { return UnsafeBufferPointer( start: ptr(at: startSlot), - count: startOffset) + count: offset) } // We're after the wrap return UnsafeBufferPointer( start: ptr(at: Slot(at: 0)), - count: position - capacity) + count: slot - capacity) } @_alwaysEmitIntoClient From e75f053e46ab6876c640c79709cfec170ce4c94b Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 20 Jul 2026 15:44:35 -0700 Subject: [PATCH 43/50] Update MutableContainer - Add `nextMutableSpan(after:)` and `nextMutableSpan(after:maxCount:limitedBy)`, replacing `nextMutableSpan(after:maxCount:)` as the core access primitives - Add `previousMutableSpan` default algorithms on bidirectional mutable containers --- .../RigidArray/RigidArray+Container.swift | 18 +- .../RigidArray/RigidArray+Deprecated.swift | 5 +- .../UniqueArray/UniqueArray+Container.swift | 4 +- .../UniqueArray/UniqueArray+Deprecated.swift | 5 +- .../Conformances/InputSpan+Container.swift | 16 +- .../Conformances/MutableSpan+Container.swift | 60 +++- .../Conformances/OutputSpan+Container.swift | 15 +- .../Container/MutableContainer.swift | 71 +++- .../RigidDeque/RigidDeque+Container.swift | 21 +- .../UniqueDeque/UniqueDeque+Container.swift | 12 +- Tests/DequeTests/RigidDequeCrashTests.swift | 8 +- Tests/DequeTests/RigidDequeTests.swift | 307 +++++++++--------- 12 files changed, 350 insertions(+), 192 deletions(-) diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Container.swift b/Sources/BasicContainers/RigidArray/RigidArray+Container.swift index dafdc0cb..4eb17ccf 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Container.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Container.swift @@ -453,13 +453,23 @@ extension RigidArray where Element: ~Copyable { @inlinable @_lifetime(&self) public mutating func nextMutableSpan( - after index: inout Int, maxCount: Int + after index: inout Int ) -> MutableSpan { _checkValidIndex(index) + return _mutableSpan(in: Range(uncheckedBounds: (index, count))) + } + + @inlinable + @_lifetime(&self) + public mutating func nextMutableSpan( + after index: inout Int, maxCount: Int, limitedBy limit: Int + ) -> MutableSpan { + _checkValidIndex(index) + _checkValidIndex(limit) precondition(maxCount > 0, "maxCount must be positive") - let start = index - index = start &+ Swift.min(maxCount, _count &- start) - return _mutableSpan(in: Range(uncheckedBounds: (start, index))) + let end = index._clampedUp( + towards: count, maxDistance: maxCount, limitedBy: limit) + return _mutableSpan(in: Range(uncheckedBounds: (index, end))) } @_alwaysEmitIntoClient diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Deprecated.swift b/Sources/BasicContainers/RigidArray/RigidArray+Deprecated.swift index 0aadedd8..3719fbbe 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Deprecated.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Deprecated.swift @@ -33,7 +33,10 @@ extension RigidArray where Element: ~Copyable { public mutating func nextMutableSpan( after index: inout Int, maximumCount: Int ) -> MutableSpan { - self.nextMutableSpan(after: &index, maxCount: maximumCount) + self.nextMutableSpan( + after: &index, + maxCount: maximumCount, + limitedBy: self.endIndex) } @available(*, deprecated, renamed: "previousSpan(before:maxCount:)") diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift index 86f4e4c3..255e3e3b 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift @@ -403,9 +403,9 @@ extension UniqueArray where Element: ~Copyable { @inlinable @_lifetime(&self) public mutating func nextMutableSpan( - after index: inout Int, maxCount: Int + after index: inout Int, maxCount: Int, limitedBy limit: Int ) -> MutableSpan { - _storage.nextMutableSpan(after: &index, maxCount: maxCount) + _storage.nextMutableSpan(after: &index, maxCount: maxCount, limitedBy: limit) } @_alwaysEmitIntoClient diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Deprecated.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Deprecated.swift index 21a47b37..9142329a 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Deprecated.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Deprecated.swift @@ -33,7 +33,10 @@ extension UniqueArray where Element: ~Copyable { public mutating func nextMutableSpan( after index: inout Int, maximumCount: Int ) -> MutableSpan { - self.nextMutableSpan(after: &index, maxCount: maximumCount) + self.nextMutableSpan( + after: &index, + maxCount: maximumCount, + limitedBy: self.endIndex) } @available(*, deprecated, renamed: "previousSpan(before:maxCount:)") diff --git a/Sources/ContainersPreview/Conformances/InputSpan+Container.swift b/Sources/ContainersPreview/Conformances/InputSpan+Container.swift index 75453beb..51652cb7 100644 --- a/Sources/ContainersPreview/Conformances/InputSpan+Container.swift +++ b/Sources/ContainersPreview/Conformances/InputSpan+Container.swift @@ -62,13 +62,17 @@ where Element: ~Copyable @_alwaysEmitIntoClient @_lifetime(&self) public mutating func nextMutableSpan( - after index: inout Index, maxCount: Int + after index: inout Index ) -> MutableSpan { - precondition(index >= 0 && index <= count, "Index out of bounds") - precondition(maxCount > 0, "maxCount must be positive") - let c = Swift.min(count &- index, maxCount) - let start = capacity &- count &+ index - return _uncheckedMutableSpan(in: Range(uncheckedBounds: (start, start &+ c))) + self.mutableSpan._nextMutableSpan(after: &index) + } + + @_alwaysEmitIntoClient + @_lifetime(&self) + public mutating func nextMutableSpan( + after index: inout Index, maxCount: Int, limitedBy limit: Index + ) -> MutableSpan { + self.mutableSpan._nextMutableSpan(after: &index, maxCount: maxCount, limitedBy: limit) } @_alwaysEmitIntoClient diff --git a/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift b/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift index 950f6731..1a1292f5 100644 --- a/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift +++ b/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift @@ -88,14 +88,64 @@ extension MutableSpan: RandomAccessContainer where Element: ~Copyable { @available(SwiftStdlib 6.4, *) extension MutableSpan: MutableContainer where Element: ~Copyable { @_alwaysEmitIntoClient - @_lifetime(&self) - public mutating func nextMutableSpan( - after index: inout Int, maxCount: Int + @_lifetime(copy self) + public consuming func _nextMutableSpan( + after index: inout Int ) -> MutableSpan { precondition(index >= 0 && index <= count, "Index out of bounds") + let end = self.count + let r = self._consumingExtracting(unchecked: Range(uncheckedBounds: (index, end))) + index = end + return r + } + + @_alwaysEmitIntoClient + @_lifetime(&self) + public mutating func nextMutableSpan( + after index: inout Int + ) -> MutableSpan { + precondition(index >= 0 && index <= count, "Index out of bounds") + let end = self.count + let r = self._mutatingExtracting( + unchecked: Range(uncheckedBounds: (index, end))) + index = end + return r + } + + @_alwaysEmitIntoClient + @_lifetime(copy self) + public consuming func _nextMutableSpan( + after index: inout Int, maxCount: Int, limitedBy limit: Int + ) -> MutableSpan { + precondition(index >= 0 && index <= count, "Index out of bounds") + precondition(limit >= 0 && limit <= count, "Index out of bounds") precondition(maxCount > 0, "maxCount must be positive") - let limit = index &+ Swift.min(maxCount, count &- index) - return self._mutatingExtracting(unchecked: Range(uncheckedBounds: (index, limit))) + var end = index &+ Swift.min(maxCount, count &- index) + if limit >= index, limit < end { + end = limit + } + let r = self._consumingExtracting( + unchecked: Range(uncheckedBounds: (index, end))) + index = end + return r + } + + @_alwaysEmitIntoClient + @_lifetime(&self) + public mutating func nextMutableSpan( + after index: inout Int, maxCount: Int, limitedBy limit: Int + ) -> MutableSpan { + precondition(index >= 0 && index <= count, "Index out of bounds") + precondition(limit >= 0 && limit <= count, "Index out of bounds") + precondition(maxCount > 0, "maxCount must be positive") + var end = index &+ Swift.min(maxCount, count &- index) + if limit >= index, limit < end { + end = limit + } + let r = self._mutatingExtracting( + unchecked: Range(uncheckedBounds: (index, end))) + index = end + return r } } diff --git a/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift b/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift index 5ac50db2..4ce98bdf 100644 --- a/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift +++ b/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift @@ -61,12 +61,17 @@ where Element: ~Copyable @_alwaysEmitIntoClient @_lifetime(&self) public mutating func nextMutableSpan( - after index: inout Index, maxCount: Int + after index: inout Index ) -> MutableSpan { - 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.mutableSpan._consumingExtracting(Range(uncheckedBounds: (index, limit))) + self.mutableSpan._nextMutableSpan(after: &index) + } + + @_alwaysEmitIntoClient + @_lifetime(&self) + public mutating func nextMutableSpan( + after index: inout Index, maxCount: Int, limitedBy limit: Index + ) -> MutableSpan { + self.mutableSpan._nextMutableSpan(after: &index, maxCount: maxCount, limitedBy: limit) } @_alwaysEmitIntoClient diff --git a/Sources/ContainersPreview/Protocols/Container/MutableContainer.swift b/Sources/ContainersPreview/Protocols/Container/MutableContainer.swift index 2cc9b208..aa844857 100644 --- a/Sources/ContainersPreview/Protocols/Container/MutableContainer.swift +++ b/Sources/ContainersPreview/Protocols/Container/MutableContainer.swift @@ -27,7 +27,11 @@ where /// - Complexity: O(1) subscript(index: Index) -> Element { borrow mutate } - /// Return a mutable span over the container's storage that begins with the + @_alwaysEmitIntoClient + @_lifetime(&self) + mutating func nextMutableSpan(after index: inout Index) -> MutableSpan + + /// Return a mutable span over the container's storage that begins with the /// element at the given index, and extends to the end of the contiguous /// storage chunk that contains it, but no more than `maxCount` items. /// @@ -93,7 +97,8 @@ where @_lifetime(&self) mutating func nextMutableSpan( after index: inout Index, - maxCount: Int + maxCount: Int, + limitedBy limit: Index ) -> MutableSpan } @@ -103,10 +108,66 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(&self) - mutating func nextMutableSpan( - after index: inout Index, + public mutating func nextMutableSpan( + after index: inout Index ) -> MutableSpan { - nextMutableSpan(after: &index, maxCount: Int.max) + nextMutableSpan(after: &index, maxCount: Int.max, limitedBy: self.endIndex) + } + + @_alwaysEmitIntoClient + @_lifetime(&self) + public mutating func nextMutableSpan( + after index: inout Index, + limitedBy limit: Index + ) -> MutableSpan { + nextMutableSpan(after: &index, maxCount: Int.max, limitedBy: limit) + } + + @_alwaysEmitIntoClient + @_lifetime(&self) + public mutating func nextMutableSpan( + after index: inout Index, + maxCount: Int + ) -> MutableSpan { + nextMutableSpan(after: &index, maxCount: maxCount, limitedBy: self.endIndex) + } +} + +@available(SwiftStdlib 6.4, *) +extension MutableContainer +where + Self: BidirectionalContainer & ~Copyable & ~Escapable, + Element: ~Copyable +{ + @_alwaysEmitIntoClient + @_lifetime(&self) + public mutating func previousMutableSpan( + before index: inout Index + ) -> MutableSpan { + let start = self.spanBoundary(before: index).index + var i = start + let span = self.nextMutableSpan(after: &i, limitedBy: index) + precondition(i == index, "Invalid BidirectionalContainer") + return span + } + + @_alwaysEmitIntoClient + @_lifetime(&self) + public mutating func previousMutableSpan( + before index: inout Index, + maxCount: Int, + limitedBy limit: Index + ) -> MutableSpan { + let start = self.spanBoundary( + before: index, + maxDistance: maxCount, + limitedBy: limit + ).index + var i = start + let span = self.nextMutableSpan(after: &i, limitedBy: index) + precondition(i == index, "Invalid BidirectionalContainer") + index = start + return span } } diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift index c54ee4c4..c0f5750b 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift @@ -176,19 +176,30 @@ extension RigidDeque where Element: ~Copyable { @_lifetime(&self) public mutating func nextMutableSpan( - after index: inout Int, maxCount: Int + after index: inout Int ) -> MutableSpan { _checkValidIndex(index) - precondition(maxCount > 0, "maxCount must be positive") - let segment = self._handle - .nextSegment(after: index) - ._extracting(first: maxCount) + let segment = self._handle.nextSegment(after: index) index &+= segment.count return _overrideLifetime( MutableSpan(_unsafeElements: .init(mutating: segment)), mutating: &self) } + @_lifetime(&self) + public mutating func nextMutableSpan( + after index: inout Int, maxCount: Int, limitedBy limit: Int + ) -> MutableSpan { + _checkValidIndex(index) + _checkValidIndex(limit) + precondition(maxCount > 0, "maxCount must be positive") + let segment = self._handle.nextSegment( + after: &index, maxCount: maxCount, limitedBy: limit) + return _overrideLifetime( + MutableSpan(_unsafeElements: .init(mutating: segment)), + mutating: &self) + } + @_alwaysEmitIntoClient public func spanBoundary(before index: Index) -> (index: Index, distance: Int) { precondition(index >= 0 && index <= count, "Index out of bounds") diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift index 42b06bde..8ee86f4f 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift @@ -115,9 +115,17 @@ extension UniqueDeque where Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(&self) public mutating func nextMutableSpan( - after index: inout Int, maxCount: Int + after index: inout Int ) -> MutableSpan { - _storage.nextMutableSpan(after: &index, maxCount: maxCount) + _storage.nextMutableSpan(after: &index) + } + + @_alwaysEmitIntoClient + @_lifetime(&self) + public mutating func nextMutableSpan( + after index: inout Int, maxCount: Int, limitedBy limit: Int + ) -> MutableSpan { + _storage.nextMutableSpan(after: &index, maxCount: maxCount, limitedBy: limit) } @_alwaysEmitIntoClient diff --git a/Tests/DequeTests/RigidDequeCrashTests.swift b/Tests/DequeTests/RigidDequeCrashTests.swift index 95615425..2151213c 100644 --- a/Tests/DequeTests/RigidDequeCrashTests.swift +++ b/Tests/DequeTests/RigidDequeCrashTests.swift @@ -85,12 +85,12 @@ struct RigidDequeCrashTests { await #expect(processExitsWith: .failure) { var deque = RigidDeque(copying: [1, 2, 3]) var index = -1 - _ = deque.nextMutableSpan(after: &index, maxCount: 1) + _ = deque.nextMutableSpan(after: &index, maxCount: 1, limitedBy: deque.endIndex) } await #expect(processExitsWith: .failure) { var deque = RigidDeque(copying: [1, 2, 3]) var index = 4 // valid range is 0...3 (count == 3) - _ = deque.nextMutableSpan(after: &index, maxCount: 1) + _ = deque.nextMutableSpan(after: &index, maxCount: 1, limitedBy: deque.endIndex) } } @@ -99,12 +99,12 @@ struct RigidDequeCrashTests { await #expect(processExitsWith: .failure) { var deque = RigidDeque(copying: [1, 2, 3]) var index = 0 - _ = deque.nextMutableSpan(after: &index, maxCount: 0) + _ = deque.nextMutableSpan(after: &index, maxCount: 0, limitedBy: deque.endIndex) } await #expect(processExitsWith: .failure) { var deque = RigidDeque(copying: [1, 2, 3]) var index = 0 - _ = deque.nextMutableSpan(after: &index, maxCount: -1) + _ = deque.nextMutableSpan(after: &index, maxCount: -1, limitedBy: deque.endIndex) } } } diff --git a/Tests/DequeTests/RigidDequeTests.swift b/Tests/DequeTests/RigidDequeTests.swift index 0a3ce02d..24cab3bf 100644 --- a/Tests/DequeTests/RigidDequeTests.swift +++ b/Tests/DequeTests/RigidDequeTests.swift @@ -116,7 +116,7 @@ final class RigidDequeTests: CollectionTestCase { let value: Int init(_ value: Int) { self.value = value } } - + func test_testingSPIs() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withLifetimeTracking { tracker in @@ -132,10 +132,10 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_basicProperties() { var deque = RigidDeque(capacity: 10) - + // Empty deque expectEqual(deque.isEmpty, true) expectEqual(deque.isFull, false) @@ -145,12 +145,12 @@ final class RigidDequeTests: CollectionTestCase { expectEqual(deque.startIndex, 0) expectEqual(deque.endIndex, 0) expectEqual(deque.indices, 0 ..< 0) - + // Add some elements deque.append(1) deque.append(2) deque.append(3) - + expectEqual(deque.isEmpty, false) expectEqual(deque.isFull, false) expectEqual(deque.count, 3) @@ -159,19 +159,19 @@ final class RigidDequeTests: CollectionTestCase { expectEqual(deque.startIndex, 0) expectEqual(deque.endIndex, 3) expectEqual(deque.indices, 0 ..< 3) - + // Fill to capacity for i in 4...10 { deque.append(i) } - + expectEqual(deque.isEmpty, false) expectEqual(deque.isFull, true) expectEqual(deque.count, 10) expectEqual(deque.freeCapacity, 0) expectEqual(deque.indices, 0 ..< 10) } - + func test_subscriptBorrow() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withLifetimeTracking { tracker in @@ -182,7 +182,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_subscriptMutate() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withEvery("i", in: 0 ..< layout.count) { i in @@ -196,7 +196,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_swapAt() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5]) { layout in withEvery("i", in: 0 ..< layout.count) { i in @@ -211,7 +211,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_reallocate() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withEvery( @@ -221,7 +221,7 @@ final class RigidDequeTests: CollectionTestCase { withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) data.deque.reallocate(capacity: newCapacity) - + expectEqual(data.deque.capacity, newCapacity) expectEqual(data.deque.count, layout.count) expectEqual(tracker.instances, layout.count) @@ -230,7 +230,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_reserveCapacity() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withEvery( @@ -240,7 +240,7 @@ final class RigidDequeTests: CollectionTestCase { withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) data.deque.reserveCapacity(newCapacity) - + expectEqual(data.deque.capacity, Swift.max(layout.capacity, newCapacity)) expectEqual(data.deque.count, layout.count) expectEqual(tracker.instances, layout.count) @@ -249,7 +249,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_initWithCapacity() { withEvery("capacity", in: [0, 1, 2, 3, 5, 10]) { capacity in let deque = RigidDeque(capacity: capacity) @@ -261,7 +261,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_initEmpty() { let deque = RigidDeque() expectEqual(deque.capacity, 0) @@ -269,7 +269,7 @@ final class RigidDequeTests: CollectionTestCase { expectEqual(deque.freeCapacity, 0) expectNil(deque._handle._buffer.baseAddress) // No allocations } - + func test_initWithClosure_Full() { withEvery("capacity", in: 0 ..< 10) { capacity in withLifetimeTracking { tracker in @@ -283,14 +283,14 @@ final class RigidDequeTests: CollectionTestCase { withEvery("i", in: 0 ..< capacity) { i in expectEqual(deque[i].payload, i) } - + expectEqual(tracker.instances, capacity) _ = consume deque expectEqual(tracker.instances, 0) } } } - + func test_initWithClosure_Partial() { withEvery("capacity", in: 0 ..< 10) { capacity in withEvery("count", in: [0, capacity / 2, max(capacity - 1, 0)] as Set) { count in @@ -305,7 +305,7 @@ final class RigidDequeTests: CollectionTestCase { withEvery("i", in: 0 ..< count) { i in expectEqual(deque[i].payload, i) } - + expectEqual(tracker.instances, count) _ = consume deque expectEqual(tracker.instances, 0) @@ -313,7 +313,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_initWithClosure_Failing() { withEvery("capacity", in: 1 ..< 10 as Range) { capacity -> Void in withEvery("count", in: [0, capacity / 2, max(capacity - 1, 0)] as Set) { count -> Void in @@ -337,7 +337,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_init_consumingUniqueDeque() { withLifetimeTracking { tracker in let ud = UniqueDeque(copying: tracker.instances(for: 0 ..< 10)) @@ -345,17 +345,17 @@ final class RigidDequeTests: CollectionTestCase { expectEqual(tracker.instances, 10) let buffer = ud._storage._handle._buffer expectNotNil(buffer.baseAddress) - + let rd = RigidDeque(consuming: ud) expectEqual(rd.count, 10) expectEqual(tracker.instances, 10) expectEqual(rd._handle._buffer.baseAddress, buffer.baseAddress) - + _ = consume rd expectEqual(tracker.instances, 0) } } - + #if compiler(>=6.4) && UnstableContainersPreview func test_initFromProducer() { withEvery("count", in: 0 ..< 10) { count in @@ -369,13 +369,13 @@ final class RigidDequeTests: CollectionTestCase { defer { invocations += 1 } return tracker.structInstance(for: invocations) } - + let deque = RigidDeque(capacity: capacity, from: &producer) expectEqual(invocations, count) expectEqual(deque.count, count) expectEqual(tracker.instances, count) expectEqual(invocations, count) - + for i in 0 ..< count { expectEqual(deque[i].payload, i) } @@ -383,7 +383,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_initFromThrowingProducer() { withEvery("count", in: 0 ..< 10) { (count: Int) in withLifetimeTracking { tracker in @@ -396,7 +396,7 @@ final class RigidDequeTests: CollectionTestCase { defer { invocations += 1 } return tracker.structInstance(for: invocations) } - + expectThrows { () throws(TestError) in let _ = try RigidDeque(capacity: count + 10, from: &producer) } @@ -408,7 +408,7 @@ final class RigidDequeTests: CollectionTestCase { } } #endif - + func test_initRepeatingValue() { withEvery("c", in: 0 ..< 10) { c in withLifetimeTracking { tracker in @@ -433,11 +433,11 @@ final class RigidDequeTests: CollectionTestCase { withLifetimeTracking { tracker in let values = RigidArray(copying: tracker.instances(for: 0 ..< c)) let deque = RigidDeque(capacity: capacity, copying: values) - + expectEqual(deque.count, c) expectEqual(deque.capacity, capacity) expectIterablePayloads(deque, equalTo: 0 ..< c) - + expectEqual(tracker.instances, c) _ = consume values expectEqual(tracker.instances, c) @@ -448,7 +448,7 @@ final class RigidDequeTests: CollectionTestCase { } } #endif - + func test_initCopyingSequence() { withEvery("c", in: 0 ..< 10) { c in withEvery("capacity", in: [c, c + 1]) { capacity in @@ -457,13 +457,13 @@ final class RigidDequeTests: CollectionTestCase { let contents = MinimalSequence( elements: values, underestimatedCount: .value(0)) - + let deque = RigidDeque(capacity: capacity, copying: contents) - + expectEqual(deque.count, c) expectEqual(deque.capacity, capacity) expectRigidDequeContents(deque, equalTo: values) - + expectEqual(tracker.instances, c) _ = consume values _ = consume contents @@ -474,20 +474,20 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_initCopyingCollection() { withEvery("c", in: 0 ..< 10) { c in withEvery("capacity", in: [c, c + 1]) { capacity in withLifetimeTracking { tracker in let values = tracker.instances(for: 0 ..< c) let contents = MinimalCollection(values) - + let deque = RigidDeque(capacity: capacity, copying: contents) - + expectEqual(deque.count, c) expectEqual(deque.capacity, capacity) expectRigidDequeContents(deque, equalTo: values) - + expectEqual(tracker.instances, c) _ = consume values _ = consume contents @@ -498,34 +498,34 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_initCopyingRange_classic() { // With a deployment target <6.2, this tests the Collection initializer withEvery("c", in: 0 ..< 10) { c in withEvery("capacity", in: [c, c + 1]) { capacity in let deque = RigidDeque(capacity: capacity, copying: 0 ..< c) - + expectEqual(deque.count, c) expectEqual(deque.capacity, capacity) expectRigidDequeContents(deque, equalTo: 0 ..< c) } } } - + @available(SwiftStdlib 6.2, *) func test_initCopyingRange_modern() { // With a deployment target >=6.2, this tests the BorrowingSequence initializer withEvery("c", in: 0 ..< 10) { c in withEvery("capacity", in: [c, c + 1]) { capacity in let deque = RigidDeque(capacity: capacity, copying: 0 ..< c) - + expectEqual(deque.count, c) expectEqual(deque.capacity, capacity) expectRigidDequeContents(deque, equalTo: 0 ..< c) } } } - + func test_popFirst() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withLifetimeTracking { tracker in @@ -549,7 +549,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_prepend() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withLifetimeTracking { tracker in @@ -562,7 +562,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_append() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withLifetimeTracking { tracker in @@ -575,15 +575,15 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_pushFirst() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) let extra = tracker.instance(for: layout.count) - + let result = data.deque.pushFirst(extra) - + if layout.count == layout.capacity { expectEqual(result, extra) expectRigidDequeContents(data.deque, equalTo: data.contents) @@ -594,15 +594,15 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_pushLast() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) let extra = tracker.instance(for: layout.count) - + let result = data.deque.pushLast(extra) - + if layout.count == layout.capacity { expectEqual(result, extra) expectRigidDequeContents(data.deque, equalTo: data.contents) @@ -613,17 +613,17 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_prepend_initializingWith_full() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withEvery("prependCount", in: 0 ..< layout.freeCapacity) { prependCount in withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) - + let extras = tracker.instances(for: layout.count ..< layout.count + prependCount) - + data.contents.insert(contentsOf: extras, at: 0) - + var i = 0 data.deque.prepend(addingCount: prependCount) { target in while !target.isFull { @@ -631,23 +631,23 @@ final class RigidDequeTests: CollectionTestCase { i += 1 } } - + expectRigidDequeContents(data.deque, equalTo: data.contents) } } } } - + func test_append_initializingWith_full() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withEvery("prependCount", in: 0 ..< layout.freeCapacity) { prependCount in withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) - + let extras = tracker.instances(for: layout.count ..< layout.count + prependCount) - + data.contents.append(contentsOf: extras) - + var i = 0 data.deque.append(addingCount: prependCount) { target in while !target.isFull { @@ -655,23 +655,23 @@ final class RigidDequeTests: CollectionTestCase { i += 1 } } - + expectRigidDequeContents(data.deque, equalTo: data.contents) } } } } - + func test_prepend_initializingWith_partial() { withEveryDeque("layout", ofCapacities: [1, 2, 3, 5, 10]) { layout in withEvery("prependCount", in: 0 ..< layout.freeCapacity) { prependCount in withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) - + let extras = tracker.instances(for: layout.count ..< layout.count + prependCount) - + data.contents.insert(contentsOf: extras, at: 0) - + var i = 0 data.deque.prepend(addingCount: layout.freeCapacity) { target in while !target.isFull, i < prependCount { @@ -685,17 +685,17 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_append_initializingWith_partial() { withEveryDeque("layout", ofCapacities: [1, 2, 3, 5, 10]) { layout in withEvery("prependCount", in: 0 ..< layout.freeCapacity) { prependCount in withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) - + let extras = tracker.instances(for: layout.count ..< layout.count + prependCount) - + data.contents.append(contentsOf: extras) - + var i = 0 data.deque.append(addingCount: layout.freeCapacity) { target in while !target.isFull, i < prependCount { @@ -709,18 +709,18 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_prepend_initializingWith_failing() { withEveryDeque("layout", ofCapacities: [1, 2, 3, 5, 10]) { layout in if layout.freeCapacity == 0 { return } withEvery("prependCount", in: 0 ..< layout.freeCapacity) { prependCount in withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) - + let extras = tracker.instances(for: layout.count ..< layout.count + prependCount) - + data.contents.insert(contentsOf: extras, at: 0) - + expectThrows { () throws(TestError) in var i = 0 try data.deque.prepend( @@ -743,19 +743,19 @@ final class RigidDequeTests: CollectionTestCase { } } } - - + + func test_append_initializingWith_failing() { withEveryDeque("layout", ofCapacities: [1, 2, 3, 5, 10]) { layout in if layout.freeCapacity == 0 { return } withEvery("prependCount", in: 0 ..< layout.freeCapacity) { prependCount in withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) - + let extras = tracker.instances(for: layout.count ..< layout.count + prependCount) - + data.contents.append(contentsOf: extras) - + expectThrows { () throws(TestError) in var i = 0 try data.deque.append( @@ -778,23 +778,23 @@ final class RigidDequeTests: CollectionTestCase { } } } - + #if compiler(>=6.4) && UnstableContainersPreview func test_prepend_Producer_full() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5]) { layout in withEvery("producerSize", in: 0 ..< 6) { producerSize in withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) - + var extras = tracker.instances(for: 0 ..< producerSize) - + data.contents.insert(contentsOf: extras.prefix(layout.freeCapacity), at: 0) - + var producer = CustomProducer, Never> { guard !extras.isEmpty else { return nil } return extras.removeFirst() } - + data.deque.prepend(from: &producer) expectEqual(extras.count, max(0, producerSize - layout.freeCapacity)) expectRigidDequeContents(data.deque, equalTo: data.contents) @@ -803,23 +803,23 @@ final class RigidDequeTests: CollectionTestCase { } } #endif - + #if compiler(>=6.4) && UnstableContainersPreview func test_append_Producer() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5]) { layout in withEvery("producerSize", in: 0 ..< layout.freeCapacity) { producerSize in withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) - + var extras = tracker.instances(for: 0 ..< producerSize) - + data.contents.append(contentsOf: extras) - + var producer = CustomProducer, Never> { guard !extras.isEmpty else { return nil } return extras.removeFirst() } - + data.deque.append(from: &producer) expectEqual(extras.count, max(0, producerSize - layout.freeCapacity)) expectRigidDequeContents(data.deque, equalTo: data.contents) @@ -828,7 +828,7 @@ final class RigidDequeTests: CollectionTestCase { } } #endif - + #if compiler(>=6.4) && UnstableContainersPreview func test_prepend_Producer_failing() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5]) { layout in @@ -836,16 +836,16 @@ final class RigidDequeTests: CollectionTestCase { withEvery("producerSize", in: 0 ..< layout.freeCapacity - 1) { producerSize in withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) - + var extras = tracker.instances(for: 0 ..< producerSize) - + data.contents.insert(contentsOf: extras, at: 0) - + var producer = CustomProducer, TestError> { () throws(TestError) in guard !extras.isEmpty else { throw TestError(23) } return extras.removeFirst() } - + expectThrows { () throws(TestError) in try data.deque.prepend(from: &producer) } @@ -859,7 +859,7 @@ final class RigidDequeTests: CollectionTestCase { } } #endif - + #if compiler(>=6.4) && UnstableContainersPreview func test_append_Producer_failing() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5]) { layout in @@ -867,16 +867,16 @@ final class RigidDequeTests: CollectionTestCase { withEvery("producerSize", in: 0 ..< layout.freeCapacity - 1) { producerSize in withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) - + var extras = tracker.instances(for: 0 ..< producerSize) - + data.contents.append(contentsOf: extras) - + var producer = CustomProducer, TestError> { () throws(TestError) in guard !extras.isEmpty else { throw TestError(23) } return extras.removeFirst() } - + expectThrows { () throws(TestError) in try data.deque.append(from: &producer) } @@ -890,7 +890,7 @@ final class RigidDequeTests: CollectionTestCase { } } #endif - + func test_prepend_MinimalSequence() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withEvery("c", in: 0 ..< layout.freeCapacity) { c in @@ -907,7 +907,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_append_MinimalSequence() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withEvery("c", in: 0 ..< layout.freeCapacity) { c in @@ -924,7 +924,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_prepend_MinimalCollection() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withEvery("c", in: 0 ..< layout.freeCapacity) { c in @@ -939,7 +939,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_append_MinimalCollection() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withEvery("c", in: 0 ..< layout.freeCapacity) { c in @@ -954,7 +954,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_prepend_ContiguousArray_asCollection() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withEvery("c", in: 0 ..< layout.freeCapacity) { c in @@ -969,7 +969,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_append_ContiguousArray_asCollection() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withEvery("c", in: 0 ..< layout.freeCapacity) { c in @@ -984,7 +984,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_prepend_ContiguousArray_asSequence() { // This calls the Sequence-based `Deque.prepend` overload, even if // `elements` happens to be of a Collection type. @@ -994,7 +994,7 @@ final class RigidDequeTests: CollectionTestCase { ) { deque.prepend(copying: elements) } - + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withEvery("c", in: 0 ..< layout.freeCapacity) { c in withLifetimeTracking { tracker in @@ -1008,7 +1008,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_append_ContiguousArray_asSequence() { // This calls the Sequence-based `Deque.append` overload, even if // `elements` happens to be of a Collection type. @@ -1018,7 +1018,7 @@ final class RigidDequeTests: CollectionTestCase { ) { deque.append(copying: elements) } - + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withEvery("c", in: 0 ..< layout.freeCapacity) { c in withLifetimeTracking { tracker in @@ -1032,7 +1032,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_prepend_BridgedArray() { // https://github.com/apple/swift-collections/issues/27 withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in @@ -1055,7 +1055,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_append_BridgedArray() { // https://github.com/apple/swift-collections/issues/27 withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in @@ -1078,7 +1078,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_insert() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withEvery("offset", in: 0 ... layout.count) { offset in @@ -1100,11 +1100,11 @@ final class RigidDequeTests: CollectionTestCase { withEvery("c", in: 0 ..< layout.freeCapacity) { c in withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) - + let extras = tracker.instances(for: layout.count ..< layout.count + c) - + data.contents.insert(contentsOf: extras, at: i) - + var j = 0 data.deque.insert(addingCount: c, at: i) { target in expectLessThanOrEqual(target.count, extras.count - j) @@ -1121,7 +1121,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_insert_initializingWith_partial() { withEveryDeque("layout", ofCapacities: [1, 2, 3, 5, 10]) { layout in guard layout.freeCapacity > 0 else { return } @@ -1129,11 +1129,11 @@ final class RigidDequeTests: CollectionTestCase { withEvery("c", in: 0 ..< layout.freeCapacity - 1) { c in withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) - + let extras = tracker.instances(for: layout.count ..< layout.count + c) - + data.contents.insert(contentsOf: extras, at: i) - + var j = 0 data.deque.insert(addingCount: layout.freeCapacity, at: i) { target in while !target.isFull, j < c { @@ -1148,7 +1148,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_insert_initializingWith_failing() { withEveryDeque("layout", ofCapacities: [1, 2, 3, 5, 10]) { layout in if layout.freeCapacity == 0 { return } @@ -1156,11 +1156,11 @@ final class RigidDequeTests: CollectionTestCase { withEvery("c", in: 0 ..< layout.freeCapacity - 1) { c in withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) - + let extras = tracker.instances(for: layout.count ..< layout.count + c) - + data.contents.insert(contentsOf: extras, at: i) - + expectThrows { () throws(TestError) in var j = 0 try data.deque.insert( @@ -1193,18 +1193,18 @@ final class RigidDequeTests: CollectionTestCase { withEvery("c", in: 0 ..< 6) { c in withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) - + var extras = tracker.instances(for: 0 ..< c) - + data.contents.insert( contentsOf: extras.prefix(layout.freeCapacity), at: i) - + var producer = CustomProducer, Never> { guard !extras.isEmpty else { return nil } return extras.removeFirst() } - + data.deque.insert( addingCount: layout.freeCapacity, from: &producer, @@ -1217,7 +1217,7 @@ final class RigidDequeTests: CollectionTestCase { } } #endif - + #if compiler(>=6.4) && UnstableContainersPreview func test_insert_fromProducer_failing() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5]) { layout in @@ -1226,16 +1226,16 @@ final class RigidDequeTests: CollectionTestCase { withEvery("c", in: 0 ..< layout.freeCapacity - 1) { c in withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) - + var extras = tracker.instances(for: 0 ..< c) - + data.contents.insert(contentsOf: extras, at: i) - + var producer = CustomProducer, TestError> { () throws(TestError) in guard !extras.isEmpty else { throw TestError(23) } return extras.removeFirst() } - + expectThrows { () throws(TestError) in try data.deque.insert( addingCount: layout.freeCapacity, @@ -1304,7 +1304,7 @@ final class RigidDequeTests: CollectionTestCase { withEvery("c", in: 0 ..< subrange.count + layout.freeCapacity) { c in withLifetimeTracking { tracker in var a = tracker.rigidDeque(with: layout).consume() - + var i = 0 a.replace(removing: subrange, addingCount: c) { target in while !target.isFull { @@ -1313,12 +1313,12 @@ final class RigidDequeTests: CollectionTestCase { } } expectEqual(i, c) - + var expected = Array(0 ..< layout.count) expected.replaceSubrange( subrange, with: layout.count ..< layout.count + c) - + expectRigidDequeContents( a, equivalentTo: expected, @@ -1338,7 +1338,7 @@ final class RigidDequeTests: CollectionTestCase { withEvery("n", in: 0 ..< c - 1) { n in withLifetimeTracking { tracker in var a = tracker.rigidDeque(with: layout).consume() - + var i = 0 a.replace(removing: subrange, addingCount: c) { target in while !target.isFull, i < n { @@ -1347,12 +1347,12 @@ final class RigidDequeTests: CollectionTestCase { } } expectEqual(i, n) - + var expected = Array(0 ..< layout.count) expected.replaceSubrange( subrange, with: layout.count ..< layout.count + n) - + expectRigidDequeContents( a, equivalentTo: expected, @@ -1372,7 +1372,7 @@ final class RigidDequeTests: CollectionTestCase { withEvery("c", in: 0 ..< subrange.count + layout.freeCapacity) { c in withLifetimeTracking { tracker in var a = tracker.rigidDeque(with: layout).consume() - + var i = subrange.lowerBound var j = 0 a.replace( @@ -1398,7 +1398,7 @@ final class RigidDequeTests: CollectionTestCase { expected.replaceSubrange( subrange, with: layout.count ..< layout.count + c) - + expectRigidDequeContents( a, equivalentTo: expected, @@ -1420,7 +1420,7 @@ final class RigidDequeTests: CollectionTestCase { withEvery("n", in: 0 ..< c - 1) { n in withLifetimeTracking { tracker in var a = tracker.rigidDeque(with: layout).consume() - + var i = subrange.lowerBound var j = 0 a.replace( @@ -1441,12 +1441,12 @@ final class RigidDequeTests: CollectionTestCase { }) expectEqual(i, subrange.upperBound) expectEqual(j, n) - + var expected = Array(0 ..< layout.count) expected.replaceSubrange( subrange, with: layout.count ..< layout.count + n) - + expectRigidDequeContents( a, equivalentTo: expected, @@ -1473,7 +1473,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_removeSubrange() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withEveryRange("range", in: 0 ..< layout.count) { range in @@ -1486,7 +1486,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_removeLast() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in guard layout.count > 0 else { return } @@ -1499,7 +1499,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_removeLast_many() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in guard layout.count > 0 else { return } @@ -1513,7 +1513,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_removeFirst_one() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in guard layout.count > 0 else { return } @@ -1526,7 +1526,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_removeFirst_many() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in guard layout.count > 0 else { return } @@ -1540,7 +1540,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_removeAll_keepingCapacity() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withEvery("isShared", in: [false, true]) { isShared in @@ -1575,7 +1575,7 @@ final class RigidDequeTests: CollectionTestCase { } } - func test_nextMutableSpan() { + func test_nextMutableSpan_maxCount() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withEvery("maxCount", in: [1, 2, 3, 5, 100]) { maxCount in var deque = RigidDeque(layout: layout, contents: layout.valueRange) @@ -1583,7 +1583,10 @@ final class RigidDequeTests: CollectionTestCase { var totalSeen = 0 while index < deque.endIndex { let oldIndex = index - var span = deque.nextMutableSpan(after: &index, maxCount: maxCount) + var span = deque.nextMutableSpan( + after: &index, + maxCount: maxCount, + limitedBy: deque.endIndex) expectGreaterThan(span.count, 0) expectLessThanOrEqual(span.count, maxCount) expectEqual(index, oldIndex + span.count) From ea64e6332f020582acef9665d002cc8195748424 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 20 Jul 2026 15:45:32 -0700 Subject: [PATCH 44/50] Update RandomAccessContainer - Require Index to be Comparable - Add `formIndex(_:offsetBy:limitedBy:)` algorithm --- .../Protocols/Container/RandomAccessContainer.swift | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/Sources/ContainersPreview/Protocols/Container/RandomAccessContainer.swift b/Sources/ContainersPreview/Protocols/Container/RandomAccessContainer.swift index 5443bb20..35979738 100644 --- a/Sources/ContainersPreview/Protocols/Container/RandomAccessContainer.swift +++ b/Sources/ContainersPreview/Protocols/Container/RandomAccessContainer.swift @@ -16,7 +16,7 @@ @available(SwiftStdlib 6.4, *) public protocol RandomAccessContainer : BidirectionalContainer, ~Copyable, ~Escapable -where Element: ~Copyable { +where Element: ~Copyable, Index: Comparable { // Note: Some requirements are redeclared to help associated type inference; // others are kept separate with `@_nonoverride`. // @@ -247,6 +247,15 @@ where // Note: Range checks are deferred until element access. index.advanced(by: n) } + + @_alwaysEmitIntoClient + @inline(__always) + 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) + } } #endif From 98bc1f99651ba2a6b4a97fd66f0832ef57745ca2 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 20 Jul 2026 16:23:31 -0700 Subject: [PATCH 45/50] Fix some issues on earlier toolchains --- .../Conformances/InputSpan+Container.swift | 8 ++++++-- .../Conformances/MutableSpan+Container.swift | 18 ++++++++++++++---- .../Conformances/OutputSpan+Container.swift | 2 +- .../Conformances/Span+Container.swift | 4 ++-- .../ContainersPreview/Types/UniqueBox.swift | 8 +------- 5 files changed, 24 insertions(+), 16 deletions(-) diff --git a/Sources/ContainersPreview/Conformances/InputSpan+Container.swift b/Sources/ContainersPreview/Conformances/InputSpan+Container.swift index 51652cb7..a65d2637 100644 --- a/Sources/ContainersPreview/Conformances/InputSpan+Container.swift +++ b/Sources/ContainersPreview/Conformances/InputSpan+Container.swift @@ -15,8 +15,7 @@ import InternalCollectionsUtilities #endif -#if compiler(>=6.2) && UnstableContainersPreview - +#if compiler(>=6.4) && UnstableContainersPreview @available(SwiftStdlib 6.4, *) extension InputSpan: RandomAccessContainer, MutableContainer where Element: ~Copyable @@ -36,7 +35,12 @@ where Element: ~Copyable public func currentIndex(of iterator: borrowing BorrowingIterator_) -> Index { self.span.currentIndex(of: iterator) } +} +#endif +#if compiler(>=6.2) && UnstableContainersPreview +@available(SwiftStdlib 5.0, *) +extension InputSpan where Element: ~Copyable { @_alwaysEmitIntoClient @inline(__always) public var startIndex: Index { 0 } diff --git a/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift b/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift index 1a1292f5..9f61e033 100644 --- a/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift +++ b/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift @@ -11,12 +11,11 @@ // //===----------------------------------------------------------------------===// -#if compiler(>=6.4) && UnstableContainersPreview - #if !COLLECTIONS_SINGLE_MODULE import InternalCollectionsUtilities #endif +#if compiler(>=6.4) && UnstableContainersPreview @available(SwiftStdlib 6.4, *) extension MutableSpan: RandomAccessContainer where Element: ~Copyable { @_alwaysEmitIntoClient @@ -43,7 +42,12 @@ extension MutableSpan: RandomAccessContainer where Element: ~Copyable { "Invalid iterator") return iterator._start } +} +#endif +#if compiler(>=6.2) && UnstableContainersPreview +@available(SwiftStdlib 5.0, *) +extension MutableSpan where Element: ~Copyable { @_alwaysEmitIntoClient public var startIndex: Int { 0 @@ -84,9 +88,16 @@ extension MutableSpan: RandomAccessContainer where Element: ~Copyable { self.span.spanBoundary(before: index, maxDistance: maxDistance, limitedBy: limit) } } +#endif +#if compiler(>=6.4) && UnstableContainersPreview @available(SwiftStdlib 6.4, *) -extension MutableSpan: MutableContainer where Element: ~Copyable { +extension MutableSpan: MutableContainer where Element: ~Copyable {} +#endif + +#if compiler(>=6.2) && UnstableContainersPreview +@available(SwiftStdlib 5.0, *) +extension MutableSpan where Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(copy self) public consuming func _nextMutableSpan( @@ -148,5 +159,4 @@ extension MutableSpan: MutableContainer where Element: ~Copyable { return r } } - #endif diff --git a/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift b/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift index 4ce98bdf..a73894e7 100644 --- a/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift +++ b/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift @@ -15,7 +15,7 @@ import InternalCollectionsUtilities #endif -#if compiler(>=6.2) && UnstableContainersPreview +#if compiler(>=6.4) && UnstableContainersPreview @available(SwiftStdlib 6.4, *) extension OutputSpan: RandomAccessContainer, MutableContainer where Element: ~Copyable diff --git a/Sources/ContainersPreview/Conformances/Span+Container.swift b/Sources/ContainersPreview/Conformances/Span+Container.swift index 55cdd921..b6f872db 100644 --- a/Sources/ContainersPreview/Conformances/Span+Container.swift +++ b/Sources/ContainersPreview/Conformances/Span+Container.swift @@ -12,7 +12,6 @@ //===----------------------------------------------------------------------===// #if compiler(>=6.4) && UnstableContainersPreview - @available(SwiftStdlib 6.4, *) extension Span: RandomAccessContainer where Element: ~Copyable { @_alwaysEmitIntoClient @@ -39,7 +38,9 @@ extension Span: RandomAccessContainer where Element: ~Copyable { return iterator._start } } +#endif +#if compiler(>=6.2) @available(SwiftStdlib 5.0, *) extension Span where Element: ~Copyable { @_alwaysEmitIntoClient @@ -112,5 +113,4 @@ extension Span where Element: ~Copyable { return (p, index &- p) } } - #endif diff --git a/Sources/ContainersPreview/Types/UniqueBox.swift b/Sources/ContainersPreview/Types/UniqueBox.swift index 2e646b83..1ef213ad 100644 --- a/Sources/ContainersPreview/Types/UniqueBox.swift +++ b/Sources/ContainersPreview/Types/UniqueBox.swift @@ -28,19 +28,13 @@ public struct UniqueBox: ~Copyable { public typealias T = Value @usableFromInline - internal let _pointer: UnsafeMutablePointer + internal let _pointer: UnsafeMutablePointer @_alwaysEmitIntoClient @_transparent public init(_ value: consuming Value) { fatalError() } - - @_alwaysEmitIntoClient - @inlinable - deinit { - fatalError() - } } #else From 232dc7f9eedfe88f235362f114888f496ccc0bde Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 21 Jul 2026 15:21:45 -0700 Subject: [PATCH 46/50] Add second parameter to `Container.makeBorrowingIterator(from:to:)` --- .../RigidArray/RigidArray+Container.swift | 8 +- .../UniqueArray/UniqueArray+Container.swift | 4 +- .../Conformances/InputSpan+Container.swift | 5 +- .../Conformances/MutableSpan+Container.swift | 12 +-- .../Conformances/OutputSpan+Container.swift | 8 +- .../Conformances/Span+Container.swift | 21 +++-- .../Conformances/Span+Iterable.swift | 10 +++ .../Protocols/Container/Container.swift | 86 ++++++++++++++----- .../Container/ContainerIterator.swift | 23 +++-- .../Container/MutableContainer.swift | 1 - .../RigidDeque/RigidDeque+Container.swift | 24 +++--- .../UniqueDeque/UniqueDeque+Container.swift | 4 +- .../MinimalTypes/StaccatoContainer.swift | 15 ++-- 13 files changed, 140 insertions(+), 81 deletions(-) diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Container.swift b/Sources/BasicContainers/RigidArray/RigidArray+Container.swift index 4eb17ccf..dc72b4df 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Container.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Container.swift @@ -40,12 +40,10 @@ extension RigidArray: Container where Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(borrow self) public func makeBorrowingIterator( - from start: Index + from start: Index, to end: Index ) -> BorrowingIterator_ { - let span = self.span - let it = span.makeBorrowingIterator(from: start) - // FIXME: `it` is borrowing `span`, not self - return _overrideLifetime(it, borrowing: self) + // FIXME: `makeBorrowingIterator` would be borrowing the temporary `span`, not self + self.span._makeBorrowingIterator(from: start, to: end) } @_alwaysEmitIntoClient diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift index 255e3e3b..53116a7c 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift @@ -40,9 +40,9 @@ extension UniqueArray: Container where Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(borrow self) public func makeBorrowingIterator( - from start: Index + from start: Index, to end: Index ) -> BorrowingIterator_ { - _storage.makeBorrowingIterator(from: start) + _storage.makeBorrowingIterator(from: start, to: end) } @_alwaysEmitIntoClient diff --git a/Sources/ContainersPreview/Conformances/InputSpan+Container.swift b/Sources/ContainersPreview/Conformances/InputSpan+Container.swift index a65d2637..6a88e605 100644 --- a/Sources/ContainersPreview/Conformances/InputSpan+Container.swift +++ b/Sources/ContainersPreview/Conformances/InputSpan+Container.swift @@ -23,10 +23,11 @@ where Element: ~Copyable @_alwaysEmitIntoClient @_lifetime(borrow self) public func makeBorrowingIterator( - from start: Index + from start: Index, + to end: Index ) -> BorrowingIterator_ { let span = self.span - let it = span.makeBorrowingIterator(from: start) + let it = span.makeBorrowingIterator(from: start, to: end) // FIXME: `it` is borrowing `span`, not self return _overrideLifetime(it, borrowing: self) } diff --git a/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift b/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift index 9f61e033..ed5625ff 100644 --- a/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift +++ b/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift @@ -21,16 +21,10 @@ extension MutableSpan: RandomAccessContainer where Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(borrow self) public func makeBorrowingIterator( - from start: Int + from start: Int, to end: Int ) -> BorrowingIterator_ { - var it = Span.BorrowingIterator_(self.span) - var remainder = start - while remainder > 0 { - let d = it.skip_(by: remainder) - precondition(d > 0) - remainder &-= d - } - return it + // FIXME: `makeBorrowingIterator` would be borrowing the temporary `span`, not self + self.span._makeBorrowingIterator(from: start, to: end) } @_alwaysEmitIntoClient diff --git a/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift b/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift index a73894e7..f048680a 100644 --- a/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift +++ b/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift @@ -23,12 +23,10 @@ where Element: ~Copyable @_alwaysEmitIntoClient @_lifetime(borrow self) public func makeBorrowingIterator( - from start: Index + from start: Index, to end: Index ) -> BorrowingIterator_ { - let span = self.span - let it = span.makeBorrowingIterator(from: start) - // FIXME: `it` is borrowing `span`, not self - return _overrideLifetime(it, borrowing: self) + // FIXME: `makeBorrowingIterator` would be borrowing the temporary `span`, not self + self.span._makeBorrowingIterator(from: start, to: end) } @_alwaysEmitIntoClient diff --git a/Sources/ContainersPreview/Conformances/Span+Container.swift b/Sources/ContainersPreview/Conformances/Span+Container.swift index b6f872db..95fac5e1 100644 --- a/Sources/ContainersPreview/Conformances/Span+Container.swift +++ b/Sources/ContainersPreview/Conformances/Span+Container.swift @@ -14,19 +14,18 @@ #if compiler(>=6.4) && UnstableContainersPreview @available(SwiftStdlib 6.4, *) extension Span: RandomAccessContainer where Element: ~Copyable { + @_alwaysEmitIntoClient + @_lifetime(copy self) + package func _makeBorrowingIterator(from start: Int, to end: Int) -> BorrowingIterator_ { + // Note: This is declared `copy self` so that types can forward to it without having to override lifetimes. + // FIXME: SpanIterator needs to have a public "slicing" initializer + BorrowingIterator_(self, from: start, to: end) + } + @_alwaysEmitIntoClient @_lifetime(borrow self) - public func makeBorrowingIterator(from start: Int) -> BorrowingIterator_ { - precondition(start >= 0 && start <= self.count, "Index out of bounds") - // FIXME: SpanIterator needs to have a direct initializer that takes `start` - var it = BorrowingIterator_(self) - var remainder = start - while remainder > 0 { - let d = it.skip_(by: remainder) - precondition(d > 0) - remainder &-= d - } - return it + public func makeBorrowingIterator(from start: Int, to end: Int) -> BorrowingIterator_ { + _makeBorrowingIterator(from: start, to: end) } @_alwaysEmitIntoClient diff --git a/Sources/ContainersPreview/Conformances/Span+Iterable.swift b/Sources/ContainersPreview/Conformances/Span+Iterable.swift index 256c41ae..f841bc26 100644 --- a/Sources/ContainersPreview/Conformances/Span+Iterable.swift +++ b/Sources/ContainersPreview/Conformances/Span+Iterable.swift @@ -51,6 +51,16 @@ extension Span where Element: ~Copyable { _count = elements.count } + @_lifetime(copy elements) + public init(_ elements: Span, from start: Int, to end: Int) { + precondition(start >= 0 && start <= elements.count, "Index out of bounds") + precondition(end >= 0 && end <= elements.count, "Index out of bounds") + precondition(start <= end, "start index must be less than or equal to end index") + _span = elements + _start = start + _count = end &- start + } + @_alwaysEmitIntoClient @_lifetime(&self) @_lifetime(self: copy self) diff --git a/Sources/ContainersPreview/Protocols/Container/Container.swift b/Sources/ContainersPreview/Protocols/Container/Container.swift index 36213044..51c8e534 100644 --- a/Sources/ContainersPreview/Protocols/Container/Container.swift +++ b/Sources/ContainersPreview/Protocols/Container/Container.swift @@ -22,7 +22,7 @@ public protocol Container: Iterable_, ~Copyable, ~Escapable where Element: ~Copyable, Element == Element_, Failure_ == Never { - associatedtype Element: ~Copyable + override associatedtype Element: ~Copyable /// Indices are expected to implement `==` and `hash(into:)` with /// constant complexity. @@ -45,7 +45,7 @@ public protocol Container: /// - Complexity: Recommended to be O(1); conforming types must clearly /// document deviations from this expectation. @_lifetime(borrow self) - func makeBorrowingIterator(from start: Index) -> BorrowingIterator_ + func makeBorrowingIterator(from start: Index, to end: Index) -> BorrowingIterator_ /// - Complexity: Recommended to be O(1); conforming types must clearly /// document deviations from this expectation. @@ -188,6 +188,18 @@ public protocol Container: limitedBy limit: Index ) -> Span + /// Accesses the element at the specified position. + /// + /// You can subscript a collection with any valid index other than the + /// collection’s end index. The end index refers to the position one past the + /// last element of a collection, so it doesn’t correspond with an element. + /// + /// - Parameter position: The position of the element to access. + /// `position` must be a valid index of the container that is not equal + /// to the `endIndex` property. + /// - Complexity: O(1). This is a hard requirement. + subscript(index: Index) -> Element { borrow } + /// Returns the position immediately after the given index. /// /// - Parameter index: A valid index of the container. `i` must be less @@ -259,18 +271,6 @@ public protocol Container: /// expectation. func distance(from start: Index, to end: Index) -> Int - /// Accesses the element at the specified position. - /// - /// You can subscript a collection with any valid index other than the - /// collection’s end index. The end index refers to the position one past the - /// last element of a collection, so it doesn’t correspond with an element. - /// - /// - Parameter position: The position of the element to access. - /// `position` must be a valid index of the container that is not equal - /// to the `endIndex` property. - /// - Complexity: O(1). This is a hard requirement. - subscript(index: Index) -> Element { borrow } - func _customIndexOfEquatableElement(_ element: borrowing Element) -> Index?? func _customLastIndexOfEquatableElement(_ element: borrowing Element) -> Index?? } @@ -280,6 +280,20 @@ extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { @_alwaysEmitIntoClient @_transparent public var underestimatedCount_: Int { count } + + @_alwaysEmitIntoClient + @_transparent + @_lifetime(borrow self) + public func makeBorrowingIterator_() -> BorrowingIterator_ { + self.makeBorrowingIterator(from: self.startIndex, to: self.endIndex) + } + + @_alwaysEmitIntoClient + @_transparent + @_lifetime(borrow self) + public func makeBorrowingIterator_(from start: Index) -> BorrowingIterator_ { + self.makeBorrowingIterator(from: start, to: self.endIndex) + } } @available(SwiftStdlib 6.4, *) @@ -398,18 +412,44 @@ extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { @_alwaysEmitIntoClient public func distance(from start: Index, to end: Index) -> Int { - // This variant allows bulk iteration, but as we can't decide if - // start <= end, we have to measure distances from both ends. +#if true + // This variant allows start to follow end, but as indices aren't + // comparable, we have to measure distances from both ends. var d1 = 0 var d2 = 0 - var i = start - 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 } + var i1 = start + var i2 = end + var forward = true + var backward = true + while forward || backward { + if forward { + let c = self.nextSpan(after: &i1, limitedBy: end).count + d1 += c + if i1 == end { return d1 } + if c == 0 { forward = false } + } + if backward { + let c = self.nextSpan(after: &i2, limitedBy: start).count + d2 -= c + if i2 == start { return d2 } + if c == 0 { backward = false } + } } + fatalError("Invalid Container") +#else + // Worse variant: this requires start <= end, but it has no way to quickly + // validate it. Furthermore, the restriction conflicts with Collection's + // more flexible implementation. + var i = start + var d = 0 + while true { + let c = self.nextSpan(after: &i, limitedBy: j).count + d += c + if i == end { break } + precondition(c > 0, "Invalid Container or 'start' does not precede 'end'") + } + return d +#endif } } diff --git a/Sources/ContainersPreview/Protocols/Container/ContainerIterator.swift b/Sources/ContainersPreview/Protocols/Container/ContainerIterator.swift index 3e3f5795..ca71c43f 100644 --- a/Sources/ContainersPreview/Protocols/Container/ContainerIterator.swift +++ b/Sources/ContainersPreview/Protocols/Container/ContainerIterator.swift @@ -23,13 +23,16 @@ where @_alwaysEmitIntoClient @_lifetime(borrow self) public func makeBorrowingIterator_() -> BorrowingIterator_ { - ContainerIterator(_borrowing: self, from: self.startIndex) + ContainerIterator( + _borrowing: self, + from: self.startIndex, + to: self.endIndex) } @_alwaysEmitIntoClient @_lifetime(borrow self) - public func makeBorrowingIterator(from start: Index) -> BorrowingIterator_ { - ContainerIterator(_borrowing: self, from: start) + public func makeBorrowingIterator(from start: Index, to end: Index) -> BorrowingIterator_ { + ContainerIterator(_borrowing: self, from: start, to: end) } @_alwaysEmitIntoClient @@ -49,14 +52,18 @@ where Base.Element: ~Copyable @_alwaysEmitIntoClient package let _base: Ref // FIXME: This doesn't support nonescapable Bases + @_alwaysEmitIntoClient + package let _end: Base.Index + @_alwaysEmitIntoClient package var _position: Base.Index @_alwaysEmitIntoClient @_lifetime(borrow base) - package init(_borrowing base: borrowing Base, from position: Base.Index) { + package init(_borrowing base: borrowing Base, from start: Base.Index, to end: Base.Index) { self._base = Ref(base) - self._position = position + self._end = end + self._position = start } } @@ -72,7 +79,11 @@ where @_unsafeNonescapableResult // FIXME: we cannot convert from a borrow to an inout dependence?! @_lifetime(&self) public mutating func nextSpan_(maxCount: Int) -> Span { - _base.value.nextSpan(after: &self._position, maxCount: maxCount) + _base.value + .nextSpan( + after: &self._position, + maxCount: maxCount, + limitedBy: self._end) } @_alwaysEmitIntoClient diff --git a/Sources/ContainersPreview/Protocols/Container/MutableContainer.swift b/Sources/ContainersPreview/Protocols/Container/MutableContainer.swift index aa844857..9c200bf4 100644 --- a/Sources/ContainersPreview/Protocols/Container/MutableContainer.swift +++ b/Sources/ContainersPreview/Protocols/Container/MutableContainer.swift @@ -27,7 +27,6 @@ where /// - Complexity: O(1) subscript(index: Index) -> Element { borrow mutate } - @_alwaysEmitIntoClient @_lifetime(&self) mutating func nextMutableSpan(after index: inout Index) -> MutableSpan diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift index c0f5750b..3cf99daa 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift @@ -53,16 +53,20 @@ extension RigidDeque where Element: ~Copyable { @_lifetime(borrow _deque) internal init( _deque: borrowing RigidDeque, - from start: Int + from start: Int, + to end: Int ) { precondition(start >= 0 && start <= _deque.count, "Index out of bounds") - self.init(_deque: _deque) - var remainder = start - while remainder > 0 { - let d = self.skip_(by: remainder) - precondition(d > 0) - remainder &-= d - } + precondition(end >= 0 && end <= _deque.count, "Index out of bounds") + precondition(start <= end, "The start must not be greater than the end") + let segments = _deque._handle.segments(forOffsets: start ..< end) + self._currentSegment = _overrideLifetime( + Span(_unsafeElements: segments.first), + borrowing: _deque) + self._nextSegment = _overrideLifetime( + Span( + _unsafeElements: segments.second ?? UnsafeBufferPointer._empty), + borrowing: _deque) self._position = start } @@ -94,9 +98,9 @@ extension RigidDeque: Container where Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(borrow self) public func makeBorrowingIterator( - from start: Index + from start: Index, to end: Index ) -> BorrowingIterator_ { - BorrowingIterator(_deque: self, from: start) + BorrowingIterator(_deque: self, from: start, to: end) } @_alwaysEmitIntoClient diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift index 8ee86f4f..dfa485a2 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift @@ -38,9 +38,9 @@ extension UniqueDeque: Container where Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(borrow self) public func makeBorrowingIterator( - from start: Index + from start: Index, to end: Index ) -> BorrowingIterator_ { - _storage.makeBorrowingIterator(from: start) + _storage.makeBorrowingIterator(from: start, to: end) } @_alwaysEmitIntoClient diff --git a/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift b/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift index 19e6cbfb..243d7db2 100644 --- a/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift +++ b/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift @@ -60,7 +60,7 @@ package struct _StaccatoParameters { fromOffset startOffset: Int, maxCount: Int ) -> Int { - precondition(maxCount > 0) + precondition(maxCount >= 0) precondition(startOffset >= 0 && startOffset <= _count) var cycleOffset = startOffset % _modulus var i = 0 @@ -82,21 +82,26 @@ public struct _StaccatoBorrowingIterator: BorrowingIteratorP internal let _contents: Span internal let _params: _StaccatoParameters internal var _offset: Int + internal let _end: Int @_lifetime(copy contents) internal init( contents: Span, params: _StaccatoParameters, - start: _StaccatoIndex = .init(_offset: 0) + start: _StaccatoIndex = .init(_offset: 0), + end: _StaccatoIndex? = nil ) { precondition(start._offset >= 0 && start._offset <= params._count) self._contents = contents self._params = params self._offset = start._offset + self._end = end?._offset ?? params._count } - @_lifetime(&self) // FIXME: Should be `@_lifetime(copy self)` + @_lifetime(&self) public mutating func nextSpan_(maxCount: Int) -> Span { + precondition(maxCount > 0) + let maxCount = Swift.min(maxCount, _end - _offset) let endOffset = _params.endOffset(fromOffset: _offset, maxCount: maxCount) let startOffset = _offset _offset = endOffset @@ -147,8 +152,8 @@ extension StaccatoContainer: Container where Element: ~Copyable { public var count: Int { _params._count } @_lifetime(borrow self) - public func makeBorrowingIterator(from start: Index) -> BorrowingIterator_ { - BorrowingIterator_(contents: _contents.span, params: _params, start: start) + public func makeBorrowingIterator(from start: Index, to end: Index) -> BorrowingIterator_ { + BorrowingIterator_(contents: _contents.span, params: _params, start: start, end: end) } public func currentIndex(of iterator: borrowing BorrowingIterator_) -> Index { From 06f6b6bf49ba53ac28fcaad2f7f905642b6a0827 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 21 Jul 2026 15:22:12 -0700 Subject: [PATCH 47/50] =?UTF-8?q?Use=20borrow=20&=20mutate=20accessors=20i?= =?UTF-8?q?n=20InputSpan=E2=80=99s=20unchecked=20subscript?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ContainersPreview/Types/InputSpan.swift | 25 ++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/Sources/ContainersPreview/Types/InputSpan.swift b/Sources/ContainersPreview/Types/InputSpan.swift index 61bcd472..53df7393 100644 --- a/Sources/ContainersPreview/Types/InputSpan.swift +++ b/Sources/ContainersPreview/Types/InputSpan.swift @@ -279,6 +279,28 @@ extension InputSpan where Element: ~Copyable { } #endif +#if compiler(>=6.4) + /// Accesses the element at the specified position. + /// + /// This subscript does not validate `position`; this is an unsafe operation. + /// + /// - Parameter index: A valid index into this span. + /// + /// - Complexity: O(1) + @unsafe + @_alwaysEmitIntoClient + public subscript(unchecked index: Index) -> Element { + @_unsafeSelfDependentResult + borrow { + unsafe _unsafeAddressOfElement(uncheckedOffset: index).pointee + } + @_unsafeSelfDependentResult + @_lifetime(self: copy self) + mutate { + unsafe &_unsafeAddressOfElement(uncheckedOffset: index).pointee + } + } +#else /// Accesses the element at the specified position. /// /// This subscript does not validate `position`; this is an unsafe operation. @@ -297,6 +319,7 @@ extension InputSpan where Element: ~Copyable { unsafe _unsafeAddressOfElement(uncheckedOffset: index) } } +#endif /// Exchange the elements at the two given offsets /// @@ -585,7 +608,7 @@ extension InputSpan where Element: ~Copyable { } @available(SwiftStdlib 5.0, *) -internal func withTemporaryInputSpan( +internal func _withTemporaryInputSpan( of type: Element.Type, capacity: Int, _ body: (inout InputSpan) throws(E) -> R From 376f4dc0870a626f8e7181049c94437a4fdbcee7 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 21 Jul 2026 15:22:40 -0700 Subject: [PATCH 48/50] Document the container design [draft] --- Documentation/Container-design.md | 998 ++++++++++++++++++++++++++++++ 1 file changed, 998 insertions(+) create mode 100644 Documentation/Container-design.md diff --git a/Documentation/Container-design.md b/Documentation/Container-design.md new file mode 100644 index 00000000..805253df --- /dev/null +++ b/Documentation/Container-design.md @@ -0,0 +1,998 @@ +# An Ownership-Aware Container Model for Swift + + * [Introduction](#introduction) + * [Making Sense of the Design Space](#making-sense-of-the-design-space) + * ["Elementwise Iteration" vs "Bulk Iteration"](#elementwise-iteration-vs-bulk-iteration) + * ["Iteration by Borrowing" vs "Iteration by Taking"](#iteration-by-borrowing-vs-iteration-by-taking) + * ["Generative" vs "Visitative Iteration"](#generative-vs-visitative-iteration) + * [Failability](#failability) + * [Read\-Only Container Model](#read-only-container-model) + * [Counting Elements](#counting-elements) + * [Container Indices](#container-indices) + * [Visitative Iteration](#visitative-iteration) + * [Subscripting](#subscripting) + * [Interaction with Iterable](#interaction-with-iterable) + * [ContainerIterator](#containeriterator) + * [Conversions Between Indices and Iterators](#conversions-between-indices-and-iterators) + * [Default Implementations of Iterable requirements](#default-implementations-of-iterable-requirements) + * [Optional Lookup Hooks](#optional-lookup-hooks) + * [Performance Requirements](#performance-requirements) + * [Conforming to Container](#conforming-to-container) + * [Bidirectional Containers](#bidirectional-containers) + * [Random\-Access Containers](#random-access-containers) + * [Mutable Containers](#mutable-containers) + * [protocol PermutableContainer](#protocol-permutablecontainer) + * [protocol MutableContainer](#protocol-mutablecontainer) + * [Producers](#producers) + * [In\-Place Consumption](#in-place-consumption) + * [struct InputSpan](#struct-inputspan) + * [protocol Drain](#protocol-drain) + * [Range\-Replaceable Containers](#range-replaceable-containers) + * [Index Ranges and Range Expressions](#index-ranges-and-range-expressions) + * [Adding Elements to a Container](#adding-elements-to-a-container) + * [Replacing Subranges](#replacing-subranges) + * [Consuming Subranges](#consuming-subranges) + * [Removing Subranges](#removing-subranges) + * [Dynamic Containers](#dynamic-containers) + * [Rejected Directions](#rejected-directions) + * [Cursors](#cursors) + * [Index Rounding Operations](#index-rounding-operations) + * [Potential Future Directions](#potential-future-directions) + * [Support for Nonescapable Element Types](#support-for-nonescapable-element-types) + * [Factoring Indexing Out of Containers](#factoring-indexing-out-of-containers) + * [A Protocol for Directly Initializing Storage](#a-protocol-for-directly-initializing-storage) + +## Introduction + +Over the last several years, we've been [gradually][BorrowingConsuming] [building][NoncopyableTypes] [up][NoncopyableGenerics] [an][PartialConsumption] [ownership][PatternMatching] [model][NonescapableTypes] [for][SuppressedAssociatedTypes] [Swift][BorrowAndMutate], to simplify the creation of safe high-performance Swift code. Our goal is to fulfill Swift's mandate to become a high-performance systems programming language, suitable for use in all computing tasks, from the smallest microcontrollers to the largest supercomputers. As many of the target environments need to operate within strict performance constraints, developers who specialize on them expect to have precise, predictable control over runtime behavior, even at the cost of some coding flexibility. + +[BorrowingConsuming]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0377-parameter-ownership-modifiers.md +[NoncopyableTypes]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0390-noncopyable-structs-and-enums.md +[NoncopyableGenerics]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0427-noncopyable-generics.md +[PartialConsumption]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0429-partial-consumption.md +[PatternMatching]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0432-noncopyable-switch.md +[NonescapableTypes]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0446-non-escapable.md +[SuppressedAssociatedTypes]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0503-suppressed-associated-types.md +[BorrowAndMutate]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0507-borrow-accessors.md +[YieldingAccessors]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0474-yielding-accessors.md +[TypedThrows]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0413-typed-throws.md + +Crucially, Swift needs to satisfy this need without resorting to unsafe interfaces: our aim is to build constructs that can match (or exceed) the performance of legacy systems programming languages, while also avoiding undefined behavior if the interfaces get misused. + +As of Swift 6.4, we have now implemented a small but quickly growing list of useful data structures that follow these new design priorities: + +- Members of the nonescapable span family provide safe, direct access to "somebody else's" contiguous pieces of memory. + - [`Span`][Span], a read-only reference to fully initialized memory + - [`MutableSpan`][MutableSpan], a mutable reference to fully initialized memory + - [`OutputSpan`][OutputSpan], a safe reference to a fixed-capacity buffer of initializable memory + - (in swift-collections) [`InputSpan`][InputSpan], a safe reference to a fixed-capacity buffer of consumable memory +- We also have ownership-aware implementations of some basic data structures. + - [`InlineArray`][InlineArray] is a homogeneous tuple/vector type + - [`UniqueArray`][UniqueArray] is a dynamically resizing array type + - (in swift-collections) [`RigidArray`][RigidArray] is a fixed-capacity array type + - (in swift-collections) [`RigidDeque`][RigidDeque] and [`UniqueDeque`][UniqueDeque] implement ring buffers + - (in swift-collections) [`RigidSet`][RigidSet] and [`UniqueSet`][UniqueSet] are hashed sets of unique items + - (in swift-collections) [`RigidDictionary`][RigidDictionary] and [`UniqueDictionary`][UniqueDictionary] are hashed dictionary types + +[Span]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0447-span-access-shared-contiguous-storage.md +[InlineArray]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0453-vector.md +[MutableSpan]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0467-MutableSpan.md +[OutputSpan]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0485-outputspan.md +[Iterable]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0516-borrowing-sequence.md +[RefAndMutableRef]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0519-ref-mutableref-types.md +[UniqueArray]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0527-rigidarray-uniquearray.md +[InputSpan]: https://github.com/apple/swift-collections/blob/main/Sources/ContainersPreview/Types/InputSpan.swift +[RigidArray]: https://swiftpackageindex.com/apple/swift-collections/main/documentation/basiccontainers/rigidarray +[RigidSet]: https://github.com/apple/swift-collections/tree/main/Sources/BasicContainers/RigidSet +[UniqueSet]: https://github.com/apple/swift-collections/tree/main/Sources/BasicContainers/UniqueSet +[RigidDictionary]: https://github.com/apple/swift-collections/tree/main/Sources/BasicContainers/RigidDictionary +[UniqueDictionary]: https://github.com/apple/swift-collections/tree/main/Sources/BasicContainers/UniqueDictionary +[RigidDeque]: https://swiftpackageindex.com/apple/swift-collections/main/documentation/dequemodule/rigiddeque +[UniqueDeque]: https://swiftpackageindex.com/apple/swift-collections/main/documentation/dequemodule/uniquedeque + +[BitSet]: https://swiftpackageindex.com/apple/swift-collections/main/documentation/bitcollections/bitset +[BitArray]: https://swiftpackageindex.com/apple/swift-collections/main/documentation/bitcollections/bitarray + +At first glance, these types have the basic shape of a Swift `Collection`: + +- They have a generic `Element` type +- They have the concept of an `Index`, modeling an abstract position within their storage +- They come with `subscript` operations that provide access to the element at a specific index +- They provide familiar operations for advancing an index to the next logical position, calculating distances between indices and similar tasks. + +However, unlike `Collection`s, these types can contain noncopyable elements, and most of them are noncopyable and/or nonescapable types themselves. These are significant complications, as our classic `Collection` protocols have been built upon the assumption of universal copyability and escapability, and it isn't feasible to factor out these assumptions without breaking the protocols. (The `SubSequence` and `Indices` associated types are particularly problematic.) + +## Making Sense of the Design Space + +Swift 6.4 introduced [protocol `Iterable`][Iterable] to enable borrowing for-in loops over these new types. The new protocol made several notable choices in the design space of ownership-aware iteration; it is crucial that we identify them so that we can carefully examine the purpose and consequences of each one, and so that we are able to analyze alternative choices. Each specific choice defines a particular design axis; we'll give them names that reflect their purpose. + +We do this not to criticise the design of `Iterable`, but to understand the use cases for which it is best suited, and to allow us to explore the full design space with intention. Identifying design axes allows us to derive a full set of potential abstractions almost mechanically, so that we can analyze them and develop the ones that seem most useful into concrete protocols in the rest of this document. + +We list the four axes we are considering below. The rest of this introductory section will define each of these in detail, but their names already give us a hint of their purpose: + +1. **Elementwise** versus **bulk** iteration -- iteration may expose a single element at a time, or it may give access to multiple elements all at once. +2. Iteration by **borrowing elements** vs iteration by **taking elements** -- whether iteration transfers ownership of the elements it traverses to the client. +3. **Generative** vs **visitative** iteration -- conforming types may be allowed to materialize their contents on the fly, or iteration may require to merely visit preexisting elements. +4. **Failable** and **non-failable** iteration -- whether iteration is allowed to throw an error. + +Under these terms, our classic `Sequence` models _non-failable, generative, elementwise iteration by taking elements_.
+The new `Iterable` protocol models _failable, generative, bulk iteration by borrowing elements_. + +In the rest of this document, we'll define three additional core protocols, `Container`, `Producer` and `Drain` (as well as a number of auxiliary protocols refining them). The four core protocols have the following properties: + +| Protocol | Elementwise/bulk | Borrowing/taking | Generative/Visitative | Failable | +| :--- | :--- | :---: | :---: | :---: | +| [`Iterable`][Iterable] | bulk (`Span`-based) | borrowing | generative | failable | +| `└╴`[`Container`](#container) | bulk (`Span`-based) | borrowing | visitative | -- | +| [`Producer`](#producer) | bulk (`OutputSpan`-based) | taking | generative | failable | +| `└╴`[`Drain`](#drain) | bulk (`InputSpan`-based) | taking | visitative | -- | + +We can already use this table to gain some interesting observations: + +- Our proposed new protocols all have a strong preference towards bulk (rather than elementwise) iteration. +- "Iteration by borrowing" and "iteration by taking" are independent abstractions; they are both useful enough to deserve their separate protocol hierarchies. +- Both visitative protocols refine their generative counterparts. This indicates a strong relationship between these concepts, with the visitative model providing a richer abstraction, in exchange for putting more restrictions on conforming types. +- Failability is strongly correlated with generative iteration. Neither of our proposed "visitative" protocols are failable. + +Let's now explore this design space a little further, by looking at the benefits and consequences of each decision. + +### "Elementwise Iteration" vs "Bulk Iteration" + +The classic `Sequence` models iteration by exposing elements one by one, through its iterator's `next()` method. + +```swift + mutating func next() -> Element? +``` + +This model of **elementwise iteration** is extremely straightforward to understand, and with a little practice we can write a rich variety of elementwise algorithms (almost) without thinking. However, it is not necessarily the most efficient way to iterate over things -- especially not over containers that organize their elements into piecewise contiguous storage chunks. + +In elementwise iteration, we need to call a protocol's customizable entry point for each and every item we traverse. The entry point needs to load the iteration's current state, and find (or generate) the next element to visit -- precisely what that means varies wildly between each type we want to iterate over. + +This makes it much harder for the compiler to reliably reason about and optimize code using `Sequence` types; this is especially difficult for sequences whose definitions are hidden behind a resiliance boundary. In classic Swift, it isn't uncommon to see performance drop by a factor of hundreds as an operation's implementation moves across resilient module boundaries. As library evolution is a crucial feature of the language, this is rather unfortunate. + +The new `Iterable` protocol resolves this issue by introducing the idea of **bulk iteration**, where each primitive iteration step exposes multiple items all at once to the client, batched up into a `Span` instance. + +```swift + mutating func nextSpan(maximumCount: Int) throws(Failure) -> Span +``` + +`Span` is a small, frozen type in the Swift Standard Library, eminently amenable to optimizations -- efficiently traversing the elements of a span is a drastically simpler problem than iterating over an arbitrary sequence. `Iterable` forcibly forces conforming types to factor iteration into two distinct layers: clients still invoke custom code to retrieve the next batch of items, but once they have them, accessing the individual elements within each batch becomes dependably cheap. + +For iterables that physically store their contents in memory, implementing iteration simply requires exposing spans over their preexisting piecewise contiguous storage chunks -- the bigger the chunks, the more efficient iteration becomes, even if `nextSpan`'s implementation isn't visible to the optimizer. + +
Click to expand footnote +> Of course, it was always possible to factor the implementation of iterators this way, by splitting `next()` into two layers, with judicious use of `@inlinable` or even `@inline(always)` attributes to encourage better performance while we're iterating within a storage chunk. However, this required a deep understanding of the underlying issues, and a large amount of willpower to structure the implementation the right way: this meant that only a select handful of types made an effort, and clients couldn't depend on it. +> +> `Iterable` forces all conforming types to organize their implementation around this idea, drastically improving clients' ability to reason about performance costs, even in generic contexts. +
+ +Bulk iteration is not without drawbacks: it comes with a drastically more complicated interface, increasing the mental load of authoring conforming types, and of solving problems using the protocol. + +To understand how `Iterable` works, we need to learn about what `Span` is, which requires us to also learn at least a little about nonescapable types. We need to figure out how to resolve a whole new class of compiler errors, and ultimately we need to get comfortable reading lifetime dependency declarations, to allow us to predict what operations we can express and architect our solutions without running into constant issues. + +Operations for bulk iteration are full of subtle design problems that often don't seem particularly important, but dismissing them can render the abstraction impossible to use in some contexts. For instance, `nextSpan`'s `maxCount` parameter is there to allow clients to limit the number of elements they receive at a time. Having to accommodate this limit is a significant complication for conforming types, so it is tempting to cut the complexity by force-feeding clients with an arbitrary number of items. (After all, clients often set `maxCount` to `Int.max` anyway, and don't mind having to potentially deal with millions of items at a time.) However, if someone just needs to look at the first three elements to make a decision about what to do with the rest, giving them four thousand items would put them in an awkward position -- they need to stash the leftovers somewhere, and then process them before pulling on the iterator again. The spans that `nextSpan` returns are tied to an exclusively access of the iterator, which (currently at least) makes it impossible to actually store them in any meaningful way: these clients would be drowned in a sea of elements they cannot process. By simplifying conforming implementations, we would significantly limit the usefulness of the protocol. + +

How bulk operations report/handle failures is a similarly subtle but important complication: operations that need to throw errors must be able to properly report partial success, to avoid data loss and to allow clients to identify precisely which element triggered the error. If the fifth element of an `Iterable` instance happens to trigger an error, it still needs to be possible for clients to reliably access the first four elements -- no matter what value they use for `maxCount`.

+ +In this document, we consider this added conceptual complexity a reasonable cost of improving the predictability of Swift performance. We're fully embracing bulk iteration across the full spectrum of container operations. Each flavor of iteration will be primarily built around one of the standard span types: `Span`, `MutableSpan`, `OutputSpan` and `InputSpan`. + +### "Iteration by Borrowing" vs "Iteration by Taking" + +Code iterating over a `Sequence` gains full ownership of the items it accesses. It can arbitrarily decide to store some of them for later processing, and arbitrarily mutate or discard them as it wishes. `Sequence` relinquishes all control over the elements it exposes, as an inherent part of its design. Because its elements are (implicitly) required to be copyable, this places no real restrictions on the kinds of types that can conform to `Sequence`. Conforming types are not _actually_ required to relinquish control over any of the items they contain just because someone is iterating over them: they can simply return copies of each element while also holding on to their "original" copy. + +In contrast, `Iterable` was designed to support noncopyable elements, which do not allow such simple workarounds. Returning a noncopyable instance means transferring unique ownership of it. For container types, this would be a destructive operation, as the contents would have to be physically moved out of the container, emptying it out or entirely consuming it in the process. This would not be workable as the default form of iteration: we naturally expect to be able to iterate over a container multiple times without destroying it in the process. + +To avoid this, `Iterable` instead choses to return _borrowing references_ to the elements it traverses, not the elements themselves. Clients do not get ownership over the items they access -- they get a temporary window that they can peer through to see a batch of items at a time; but they don't get to break the glass (to modify or consume the items), and once the window moves to the next batch, they lose sight to all previously seen items. + +In this document, we'll call the ownership model of `Iterable` **iteration by borrowing**, as clients _borrow_ the elements they traverse. The other way to gain access to something is to _take_ ownership of it -- hence, we'll call the model `Sequence` follows **iteration by taking**. + +
Click to expand footnote + +> People have sometimes referred to "iteration by taking elements" as "consuming iteration". Unfortunately, this is routinely misunderstood to mean that the sequence itself gets consumed, rather than its elements, and that makes it an actively confusing term. "Iteration by taking" is meant to describe what the client does to the _elements_, not what happens to the source of the iteration. + +
+ +Of course, the way `Iterable` only provides read-only, borrowing access to its elements severely limits what clients can do with them. Obviously, we will also need to provide iterator-like constructs that transfer ownership of their elements to the caller, so that it can collect them into a container type, or otherwise mutate/consume them as it wishes. In this document, we are modeling the idea of "iterating by taking elements" with protocol [`Producer`][Producer] + +A variant of the `Iterable` approach is one where instead of borrowing references, we provide mutable references to elements -- we change the unit of iteration from `Span` to `MutableSpan` (or change `Ref` to `MutableRef`). The source of the elements still retains ownership in this case, but clients are allowed to arbitrarily mutate or even replace them. In this document, we are modeling this approach with `MutableContainer`; we are not introducing an `Iterable`-style, generative protocol. + +### "Generative" vs "Visitative Iteration" + +`Sequence` and `Iterable` both allow their elements to be generated on the fly. We'll be calling this style of traversal **generative iteration**. This allows a wide spectrum of conforming types, but it complicates performance analyis, as the variable cost of on-demand generation inherently adds a difficult term to the complexity of element access. + +Additionally, generative iteration by _borrowing_ (as implemented by `Iterable`) has the crucial limitation that the client cannot hold on to generated items as they come out of the iterator -- it is only able to see only a single batch of them at a time, and the minute it advances the iterator, it loses sight of all the items it previously encountered. Because `Iterable` allows elements to be generated (and discarded!) on the fly, clients must destroy all references to the elements they see before they can advance to the next batch. This strictly limits the kinds of algorithms we can implement over `Iterable`: in particular, we cannot define lookup or search algorithms that need to return references to specific elements (such as `min()` or `first(where:)`), unless we require `Element` to be copyable. The elements we want to reference may evaporate the moment we advance the iterator! + +Not all iterable types need to generate their items on demand. In particular, many of the most useful data structures physically hold their contents in memory, and they can implement iteration by simply locating their storage chunks and directly exposing spans over them. Arrays, linked lists, hashed sets, hashed dictionaries, ring buffers, search trees, ropes are all examples of such data structures, and of course there are many more. + +Data structures with preexisting storage form a highly useful subset of iterables, and it is worth giving them a name; we'll call such types **containers**, and the traversal they support **visitative iteration**. These terms emphasize that iterating over a container merely visits its preexisting contents, rather than materializing them on the fly. Locating items in preexisting storage is a far simpler task than generating them; and clients can safely extract and work with references to such items as long as they do not mutate the instance that contains them. + +Not all data structures are containers, of course. For example, Swift's standard `String` type is a sequence of `Character` instances, but those instances are not directly stored anywhere in `String`'s storage representation -- they need to be created on the fly, as we iterate over the string instance. `String` therefore implements _generative_ rather than _visitative_ iteration; it is not a container type. (Of course, it would be possible to build a container of text data; but to do it efficiently, we'd likely need to avoid using `Character` as its `Element`.) + +### Failability + +The final design aspect we need to consider is failability: whether we need to allow traversable constructs to throw errors. + +The classic `Sequence` protocol provides no way for conforming types to signal a failure, other than by trapping or by stopping the iteration earlier than expected. For many developers, this feels like a defect -- `Sequence` allows (or even encourages) conforming types to produce their elements by running arbitrarily complex calculations; and of course those calculations can sometimes legitimately encounter non-fatal problems. The inability to properly signal failure leads to awkward workarounds. + +Using the terminology established in the previous section, the ability of fail is therefore a natural expectation for _generative_ constructs. + +The `Iterable` protocol addresses this by defining `Failure` associated type and providing a throwing `nextSpan` method on its iterator. It relies on [typed throws][TypedThrows] so that conforming types that never need to throw can set `Never` as their failure type, enabling clients to avoid writing error handling code that deals with errors that are guaranteed never to happen. + +This potentially allows lazy `Iterable` algorithms (like `filter`) to take throwing closures, and cleanly propagate errors to clients. In exchange, failability greatly complicates the bulk iteration model, as operations need to be able to [properly report partial success](#bulk-failures). + +
Click to expand footnote + +(However, we also expect a filter predicate to be able to throw a _different_ error type than the `Iterable`'s own `Failure`. We currently lack the means to express that, as the `nextSpan` method would need to be able to throw either error. We need to do further language-level work -- such as union error types -- to allow us to express such abstractions in a satisfying way.) + +
+ +On the other hand, the ability to fail is far less important for _visitative_ constructs, like `Container` -- if the items we're visiting already exist in memory at the start of the iteration, there is little reason to take on the complexity of throwing. Therefore, our two visitative protocols (`Container` and `Drain`) do not allow throwing. + +This greatly simplifies the container model, but it does mean that throwing algorithms like our hypothetical lazy `filter` can only produce `Iterable` types -- they cannot return containers, even if their input is one. + +Let us now introduce the actual protocols, starting with `Container` itself. + +## Read-Only Container Model + +Protocol `Container` is our ownership-aware analogue of `Collection`. It defines the abstract shape of a container type that physically holds its contents in memory, and makes them directly accessible to clients. + +The contents of a container can be traversed multiple times, nondestructively. The same container must exhibit identical contents across repeated traversals. Clients must be able to form references to container contents that aren't tied to a specific iteration state, only the container itself. This allows Swift functions to directly return such references to callers, allowing the implementation of a variety of useful container algorithms, including basic search/lookup methods. + +Let's start defining the new protocol. + +```swift +protocol Container: Iterable, ~Copyable, ~Escapable +where + Element: ~Copyable, + Failure == Never +{...} +``` + +The `Container` protocol refines `Iterable`; `Iterable` algorithms are able to work with container types with no extra effort. However, not all iterable types can be containers. The requirement that a container's elements must preexist in memory rules out all iterables that generate items on demand; using the terms [we established above](#generative-iteration-vs-visitative-iteration), we say that iterables model _generative iteration_, while containers are restricted to _visitative_ semantics. + +`Container` requires `Failure` to be set to `Never`: because the contents of a container are required exist in advance within the container instance, they can always be successfully iterated: there is never a need to throw an error. + +Naturally, container types are not required to be copyable, nor escapable. They don't require their elements to be copyable, either. (Support for nonescapable elements is a [highly desirable future direction](#support-for-nonescapable-element-types), but we currently lack the tools to express it.) + +### Counting Elements + +As containers physically store their elements, they inherently always have a specific count. + +```swift +protocol Container: ... { + ... + var count: Int { get } + ... +} +``` + +Repeated invocations of the `count` property on the same container must return the same value. The returned value must match the number of elements that can be accessed by iterating through the container. + +Unlike `Collection`, types conforming to `Container` are **required to produce their `count` in constant complexity**. This reflects the protocol's focus on predictable performance, and avoids a common worry with `Collection`. + +
Click to expand footnote + +A consequence of this requirement is that constructs like lazy filter algorithms cannot practically conform to the protocol. However, they can still be `Iterable`, and that is in fact good enough for the vast majority of their use cases in practice. Notably, custom on-the-fly filtering is inherently incompatible with the expectation of predictable performance. (After all, this protocol exists to focus on high-performance use cases; it would be a mistake to dilute this focus until the protocol becomes indistinguishable from `Collection`.) + +`count` is required to return a finite integer that fits in `Int`. This can be a true limitation, as some containers may have more than `Int.max` elements, despite the protocol's requirement for preexisting storage! The storage requirement does not preclude some containers to link specific storage chunks multiple times (or simply repeat them), without allocating separate storage for each duplicate run. Such repetitions can cause the count of a container to overflow `Int`'s range, without ever overflowing available memory. While such humungous containers are certainly interesting, we do not consider it crucial to provide dedicated support for them. + +In the design we are proposing, humungous containers can choose to either only conform to `Iterable`, or to trigger a trap if they are ever asked for their count. Client code often invokes `count` so that it can preallocate storage for related work; obviously that is not going to end well if a container's count exceeds `Int.max`. (And in fact trapping early is much preferable to allowing the operation to inevitably fail midway through some vast computation.) + +If we wanted to support would be to have `count` return an optional, or to push this property down into a separate `FiniteContainer` protocol. The overwhelming complexity of these options does not feel to be anywhere in proportion to the practical importance of such cases. Which is not to say they don't exist: tree-based ropes in particular (like `Foundation`'s `AttributedString`) can easily grow to humungous sizes, by simply concatenating a rope with itself a few dozen times. However, these are mostly just fun curiosities; such trees are rarely (if ever) practically useful.) + +
+ +As a small nod towards infinite/vast containers, `Container` still provides an `isEmpty` property that avoids problems with integer overflow: + +```swift +protocol Container: ... { + ... + var isEmpty: Bool { get } + ... +} +``` + +This comes with a default implementation that simply checks if `count` is zero. (`Collection` defines a default implementation for its `isEmpty` that compares `startIndex` to `endIndex`. Given that `Container` requires its `count` to have O(1) complexity, it is slightly better to define `isEmpty` in terms of it, as it avoids having to materialize two index instances.) + +### Container Indices + +As `Container` refines `Iterable`, it provides a `BorrowingIterator`, and we can use this iterator to access the elements of a container in batches, starting from its beginning. However, it would be a shame to stop there: `Container` can also provide a more flexible model for element access that acknowledges that its contents survive across iteration steps. To help model this, we introduce a slightly adapted version of `Collection`'s familiar `Index` concept. + +```swift +protocol Container: ... { + ... + associatedtype Index: Equatable, Hashable + ... +} +``` + +Our indices represent abstract positions within containers (just as they do in collections): one useful way to look at them is to say that they're addressing the logical boundaries between neighboring elements, with a "start index" addressing the boundary before the first element, and the "end index" addressing the boundary after the last. A container with five items therefore has six indices, adressing all its various logical positions: + +``` + ┌─────┬─────┬─────┬─────┬─────┐ + │ A │ B │ C │ D │ E │ + └─────┴─────┴─────┴─────┴─────┘ + ↑ ↑ ↑ ↑ ↑ ↑ + 0 1 2 3 4 5 + (start) (end) +``` + +Equivalently, we can say that each index addresses a specific element, with the end index addressing an imaginary empty slot after the last item in the container. + +Over the years, Swift's indices have proven to be extremely successful abstractions. This incarnation preserves them as copyable and escapable types, so that they can be processed without undue friction. Indices are soft references that are allowed to go stale when the underlying container is mutated; therefore, container operations taking indices are still required to carefully validate their inputs to catch misuse. (We could have chosen to replace indices with a nonescapable abstraction that would avoid this; however, in practice we found that direction to be [impractical](#cursors).) + +Every one of the standard container types we've introduced so far (from `Span` to `UniqueArray` and beyond) already defines an index that fits this model. + +`Container` indices are required to be `Equatable`, but unlike `Collection`, they do not need to be `Comparable`. Linked lists are commonly used in systems programming, and this choice allows some linked list implementations to usefully conform to `Container`. The lack of an inherent ordering does complicate the default implementations of some index operations -- [see below](#distance-from-to). + +In exchange, `Container` requires its indices to be `Hashable`. This does not put an undue burden on container implementations, but it does allow indices to be collected in sets or used as dictionary keys, enabling use cases such as dynamic filtering or out-of-band storage of data associated with container elements. (This fixes a small wrinkle with `Collection`, in that it does not require hashable indices.) + +To acknowledge our performance goals, **we require that `Container` indices must be compared for equality and hashed with constant complexity**. If a container's index does happen to be `Comparable`, then it is required that `<` has O(1) complexity as well. + +Now that we have an `Index` type, we can define all the familiar operations that allow us to navigate within a container: + +```swift +protocol Container: ... { + ... + var startIndex: Index { get } + var endIndex: Index { get } + func index(after index: Index) -> Index + func formIndex(after index: inout Index) + func index(_ index: Index, offsetBy n: Int) -> Index + func formIndex(_ index: inout Index, offsetBy n: inout Int, limitedBy limit: Index) + func distance(from start: Index, to end: Index) -> Int + ... +} +``` + +`startIndex` and `endIndex` work exactly like `Collection`'s corresponding properties, defining the bounds of a half-open range: `endIndex` returns a valid index that addresses the logical empty slot following the container's last element, while `startIndex` addresses the container's first element. + +`index(_:offsetBy:)` is the `Container` analogue of `BorrowingIterator`'s `skip(by:)` method. + +Notably, we replace `Collection`'s classic `index(_:offsetBy:limitedBy:)` requirement with an improved variant ([first introduced on `UniqueArray`][formIndex-offsetBy-limitedBy]) that reports the number of steps it managed to take before reaching the limit. This avoids having to figure this out with a separate `distance(from:to:)` invocation, enabling more efficient use of this operation situation that need this data; notably, it allows easy single-pass offsetting across concatenated containers. `Collection`'s original `index(_:offsetBy:limitedBy:)` operation is still available, as a standard algorithm based on the new requirement. + +[formIndex-offsetBy-limitedBy]: https://github.com/swiftlang/swift/blob/swift-6.4.x-DEVELOPMENT-SNAPSHOT-2026-07-06-a/stdlib/public/core/UniqueArray/UniqueArray%2BContainer.swift#L267-L273 + +As `Container` models a forward-only container, its `index(_:offsetBy:)` operation requires a nonnegative offset. (We'll shortly introduce a `BidirectionalContainer` refinement that will relax this constraint.) + +As indices aren't required to be `Comparable`, the default implementation of `distance(from:to:)` cannot quickly validate that its `start` argument precedes `end`. To avoid having to run all the way to end of the container to detect misuse, the algorithm instead iterates forward from both arguments, until it finds the other. This makes the default implementation twice as slow, but it allows it to correctly calculate negative distances. In the common case when `Index` is `Comparable`, we also provide a refined default algorithm that avoids this overhead. + +### Visitative Iteration + +The preferred way to iterate over the contents of a `Container` is to repeatedly invoke its `nextSpan` operation: + +```swift +protocol Container: ... { + ... + @_lifetime(borrow self) + func nextSpan(after index: inout Index) -> Span + ... +} +``` + +Like the corresponding iterator method on `Iterable`, this implements [bulk iteration](#elementwise-iteration-vs-bulk-iteration): it gives clients access to a batch of items all at once, allowing them to quickly iterate over the returned `Span` instance without invoking any other `Container` methods. + +However, this `nextSpan` function is only allowed to mutate an index, not the container itself. Additionally, the spans returned by `nextSpan` are declared to be scoped to a "borrow" of the container, too. This is the crucial difference from `Iterable`, whose spans extend (and are tied to) a particular mutation of the iterator. This is what causes `Container` to fundamentally require its elements to pre-exist in memory -- it isn't possible a `nextSpan` with this signature to materialize items on the fly. Containers are required to implement [visitative iteration](#generative-vs-visitative-iteration). + +`Container.nextSpan` returns a `Span` instance that begins with the container's element that the given index addresses, and runs to the end of the container's storage chunk that contains it. On return, the index is updated to address the item following the last element in the returned span. If the input index is the `endIndex`, then the method returns an empty span, and leaves the index as is. + +This method can be used to efficiently process the items of a container in bulk, by directly iterating over its piecewise contiguous pieces of storage: + +```swift + var index = items.startIndex + while true { + let span = items.nextSpan(after: &index) + if span.isEmpty { break } + // Process items in `span` + } + // `index` is now equal to `items.endIndex` +``` + +We expect that for-in loops over container types will use this iteration style, to allow clients to form `Ref` instances over the element that's currently visited by the loop. + + +The spans returned by `nextSpan` are not guaranteed to be disjunct. Some containers may use the same storage chunk (or parts of a storage chunk) multiple times, to repeat their contents. + +Repeated invocations of `nextSpan` on the same container and index are guaranteed to expose identical elements, in the same order, and grouped into spans of consistent counts. + +Sometimes we don't want to iterate all the way to the end of a container: for instance, we may just want to look at a specific subrange, or we may need to access a specific number of elements. For these cases, `Container` also provides a delimited variant of `nextSpan`, modeled after `formIndex(_:offsetBy:limitedBy:)`: + +```swift +protocol Container: ... { + ... + @_lifetime(borrow self) + func nextSpan(after index: inout Index, maxCount: Int, limitedBy limit: Index) -> Span + ... +} +``` + + +The `maxCount` argument gives the caller control over the number of items it receives from the iterator, while `limit` allows the caller to request that the result never exceed a specific index. These parameters let callers avoid overrunning their target, which would significantly complicate container use. + +Not all containers are contiguous, so `maxCount` only sets an upper bound. To read a specific number of items, the caller usually needs to invoke `nextSpan` in a loop: + +```swift +var items: some Container +var index = items.startIndex +var remainder = numberOfItemsToRead +while remainder > 0 { + let next = items.nextSpan(after: &index, maxCount: remainder) + guard !next.isEmpty else { + // Container does not have enough items + break + } + remainder -= next.count + // Process items in `next` +} +``` + +This more powerful form of `nextSpan` is a core primitive; by default, most other `Container` requirements are implemented in terms of it. For example, here is the default implementation of `index(_:offsetBy:)`: + +```swift +extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { + public func index(_ index: Index, offsetBy n: Int) -> Index { + var index = index + var n = n + let end = self.endIndex + while n > 0 { + let c = self.nextSpan(after: &index, maxCount: n, limitedBy: end).count + precondition(c > 0, "Cannot advance index beyond the end of the container") + n &-= c + } + return index + } +} +``` + +Containers often hold their contents in piecewise contiguous storage chunks; as this default implementation iterates over entire chunks, it can be considerably more efficient than stepping through indices one by one, like `Collection` does. As the elements are required to preexist in memory, materializing spans over them is relatively cheap -- `nextSpan` merely needs to locate storage, not populate its contents. Still, it is often possible to implement required operations more directly, and it is good practice to do so whenever it leads to measureable improvement. + +The default implementation of `distance(from:to:)` poses an interesting problem: `Container` only allows forward iteration, so to measure the distance between two indices, we have to start iterating from the one addressing the earlier one. But container's `Index` is not required to be `Comparable`, which means that we have three options: + +1. Only provide a default `distance` algorithm for containers with comparable indices. + + ```swift + extension Container + where + Self: ~Copyable & ~Escapable, + Element: ~Copyable, + Index: Comparable + { + public func distance(from start: Index, to end: Index) -> Int { + var (i, j, forward): (Index, Index, Bool) = (start <= end + ? (start, end, true) + : (end, start, false)) + var d = 0 + while i < j { + let span = self.nextSpan(after: &i, limitedBy: j) + d += span.count + } + return forward ? d : -d + } + } + ``` + +2. Require `start` to precede `end`, but with no easy way to validate this other than letting iteration go all the way to the end of the container. + + ```swift + extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { + public func distance(from start: Index, to end: Index) -> Int { + var i = start + var d = 0 + while true { + let c = self.nextSpan(after: &i, limitedBy: j).count + d += c + if i == end { break } + precondition(c > 0, "Invalid Container or 'start' does not precede 'end'") + } + return d + } + } + ``` + +3. Allow `start` and `end` to be in any order, but iterate forward from both ends until we find the other: + + ```swift + extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { + public func distance(from start: Index, to end: Index) -> Int { + // This variant allows start to follow end, but as indices aren't + // comparable, we have to measure distances from both ends. + var d1 = 0 + var d2 = 0 + var i1 = start + var i2 = end + var forward = true + var backward = true + while forward || backward { + if forward { + let c = self.nextSpan(after: &i1, limitedBy: end).count + d1 += c + if i1 == end { return d1 } + if c == 0 { forward = false } + } + if backward { + let c = self.nextSpan(after: &i2, limitedBy: start).count + d2 -= c + if i2 == start { return d2 } + if c == 0 { backward = false } + } + } + fatalError("Invalid Container") + } + } + ``` + +To preserve continuity/interoperability with `Collection` (whose distance allows any ordering), `Container` implements option three, while also providing the simpler/faster implementation from option 1, for the common case when `Index` is `Comparable`. + +### Subscripting + +Bulk iteration is nice, but sometimes we do just want to access an individual element addressed by a specific index. For these cases, `Container` provides an indexing subscript with a [`borrow` accessor][BorrowAndMutate]: + +```swift +protocol Container: ... { + ... + subscript(index: Index) -> Element { borrow } + ... +} +``` + +This (alongside all the shared index operations) makes `Container` instantly familiar to developers who have used `Collection`. Of course, this indexing subscript is not the same as the classic `Collection` subscript: it has a `borrow` accessor, not a getter. As of Swift 6.4, we cannot even put its borrowed result in a local variable; to do that, we need to manually create a borrowing reference by wrapping the result in a `Ref` instance: + +```swift +let item = someContainer[index] // error: 'someContainer.subscript' is borrowed and cannot be consumed +let item2 = Ref(someContainer[index]) // OK +``` + +### Interaction with `Iterable` + +#### `ContainerIterator` + +`Container` refines `Iterable`, and its operations allow us to create standard implementations for `Iterable` requirements, allowing developers to avoid creating a custom iterator from scratch each time they need to create a container type. The standard iterator adapter is called `ContainerIterator`, and it serves the same purpose in the `Container` world as `IndexingIterator` does for `Collection`. + +A `ContainerIterator` instance stores a borrowing reference to a container value, alongside a current position inside it: + +```swift +struct ContainerIterator< + Base: Container & ~Copyable /*& ~Escapable*/ +>: ~Copyable, ~Escapable +where Base.Element: ~Copyable +{ + typealias Element = Base.Element + + internal let _base: Ref // Note: This doesn't currently support nonescapable Bases + internal let _end: Base.Index + internal var _position: Base.Index +} + +@available(SwiftStdlib 6.4, *) +extension ContainerIterator: BorrowingIteratorProtocol +where + Base: ~Copyable /*& ~Escapable*/, + Base.Element: ~Copyable +{ + + @_lifetime(&self) + mutating func nextSpan(maxCount: Int) -> Span { + _base.value.nextSpan(after: &self._position, maxCount: maxCount, limitedBy: end) + } + } + + @_lifetime(self: copy self) + mutating func skip(by maximumOffset: Int) -> Int { ... } +} +``` + +Compare this to `IndexingIterator`, which holds a _copy_ of its base collection, plus a current index. `ContainerIterator` implements the same idea, adapted for the borrowing ownership model. (It adds a limiting index to allow iterating over a subrange of elements in a container -- this is intended to substitute for a common use case of `Collection` slices.) + +#### Conversions Between Indices and Iterators + +`Container` resolves a long-standing `Collection` limitation by providing standard operations to start an iterator from a specific index (or between two indices), and to retrieve the current index of an existing iterator: + +```swift +protocol Container: ... { + ... + @_lifetime(borrow self) + func makeBorrowingIterator(from start: Index, to end: Index) -> BorrowingIterator + func currentIndex(of iterator: borrowing BorrowingIterator) -> Index + ... +} + +extension Container +where + Self: ~Copyable & ~Escapable, + Element: ~Copyable, +{ + @_lifetime(borrow self) + func makeBorrowingIterator() -> BorrowingIterator { + self.makeBorrowingIterator(from: self.startIndex, to: self.endIndex) + } + + @_lifetime(borrow self) + func makeBorrowingIterator(from start: Index) -> BorrowingIterator { + self.makeBorrowingIterator(from: start, to: self.endIndex) + } +} +``` + +#### Default Implementations of `Iterable` requirements + +The `underestimatedCount` of a `Container` is simply its count: + +```swift +extension Container +where + Self: ~Copyable, + Element: ~Copyable +{ + var underestimatedCount: Int { self.count } +} +``` + +We'd like the `Container` protocol to declare `ContainerIterator` as its default borrowing iterator type: + +```swift +protocol Container: ... { + ... + associatedtype BorrowingIterator = ContainerIterator + ... +} +``` + +Unfortunately, this isn't currently possible, as `Ref` is not yet able to address nonescapable targets, and `Container` does need to allow nonescapable conforming types (such as `Span`). In its current form, `ContainerIterator` does not work for those, so nonescapable containers will need to manually implement a suitable iterator type. + +However, we can at least supply default implementations for all `Iterable`-related operations when `Iterator` happens to be `ContainerIterator`: + +```swift +extension Container +where + Self: ~Copyable, + Element: ~Copyable, + BorrowingIterator == ContainerIterator +{ + @_lifetime(borrow self) + func makeBorrowingIterator(from start: Index, to end: Index) -> BorrowingIterator { + ContainerIterator(_borrowing: self, from: start, to: end) + } + + func currentIndex(of iterator: borrowing BorrowingIterator) -> Index { + iterator._position + } +} +``` + +### Optional Lookup Hooks + +`Collection` defines two customization hooks for quickly looking up the first and last indices of an `Equatable` element instance. We directly include the same requirements on `Container`: + +```swift +protocol Container: ... { + ... + func _customIndexOfEquatableElement(_ element: borrowing Element) -> Index?? + func _customLastIndexOfEquatableElement(_ element: borrowing Element) -> Index?? + ... +} +``` + +On `Collection`, these hooks allow conforming types to customize the standard `firstIndex(of:)` and `lastIndex(of:)` operations to implement more efficient algorithms than linear search. For instance, a hashed set type may implement these hooks to provide lookup operations with an expected complexity of O(1). + +Like with `Collection`, these operations come with default implementations that simply return `nil`, indicating that there is no shortcut available for looking up elements. + +### Performance Requirements + +To achive predictable performance, `Container` operations are expected to have the following worst-case complexities: + +| Operation | Complexity | +|---|---| +| `isEmpty` | O(1) | +| `count` | O(1) | +| `endIndex` | O(1) (non-negotiable requirement) | +| `startIndex` | O(1) | +| `nextSpan(...)` | O(1) | +| `subscript(_:)` | O(1) | +| `index(after:)` | O(1) | +| `formIndex(after:)` | O(1) | +| `index(_:offsetBy:)` | O(`n`) | +| `formIndex(_:offsetBy:)` | O(`n`) | +| `formIndex(_:offsetBy:limitedBy:)` | O(`n`) | +| `distance(from:to:)` | O(*d*) where *d* is the absolute value of the actual distance | +| `makeBorrowingIterator(...)` | O(1) | +| `currentIndex(of:)` | O(1) | +| `_customIndexOfEquatableElement(_:)` | O(1) | +| `_customLastIndexOfEquatableElement(_:)` | O(1) | + +These correspond to similar (sometimes implicit) expectations on `Collection`'s operations, stated more consistently. Of these, only the constant complexity of `endIndex` is a hard requirement; the others are setting rough expectations that may sometimes need to be violated. All containers are required to clearly document any deviations from the expectations above. + +Common examples of containers with unusually high index navigation costs: + +- Containers with sparsely populated storage may need to scan an arbitrarily large number of empty storage slots between valid elements. + + Hashed containers like the standard `Set` and `Dictionary` types are prominent examples of this -- their `index(after:)` implementation has a worst-case complexity that's linear in their storage capacities, which can be arbitrarily larger than their count. (Even when averaged over iterating over the entire contents of a dictionary, `index(after:)`'s amortized complexity is still O(`capacity`/`count`) i.e., the inverse of the current load factor -- which still has no constant upper bound.) This is difficult to mitigate in practice; for example, implementing a minimum load factor would resolve this, but it would lead to constant allocation churn that (in most cases) would be considered much worse than inconsistent iteration speed. + +- Container types built around balanced trees (such as sorted sets or ropes) commonly need to replace/augment many of these complexities with "O(log(`count`))" terms. + +### The Full `Container` protocol + +```swift +protocol Container: + Iterable, ~Copyable, ~Escapable + where Element: ~Copyable, Failure == Never +{ + associatedtype Index: Equatable, Hashable + /*associatedtype BorrowingIterator = ContainerIterator*/ + + @_lifetime(borrow self) + func makeBorrowingIterator(from start: Index, to end: Index) -> BorrowingIterator + + func currentIndex(of iterator: borrowing BorrowingIterator) -> Index + + var isEmpty: Bool { get } + var count: Int { get } + var startIndex: Index { get } + var endIndex: Index { get } + + @_lifetime(borrow self) + func nextSpan(after index: inout Index) -> Span + + @_lifetime(borrow self) + func nextSpan( + after index: inout Index, + maxCount: Int, + limitedBy limit: Index + ) -> Span + + subscript(index: Index) -> Element { borrow } + + func index(after index: Index) -> Index + func formIndex(after index: inout Index) + func index(_ index: Index, offsetBy n: Int) -> Index + func formIndex(_ index: inout Index, offsetBy n: inout Int, limitedBy limit: Index) + func distance(from start: Index, to end: Index) -> Int + + func _customIndexOfEquatableElement(_ element: borrowing Element) -> Index?? + func _customLastIndexOfEquatableElement(_ element: borrowing Element) -> Index?? +} +``` + +### Conforming to `Container` + +Types that wish to conform to protocol `Container` must, at minimum, complete the following tasks: + +1. Implement an `Index` type, and an index validation strategy. Dereferencing an index must be both safe and highly efficient: it must be possible to reliably and quickly check that an index represents a valid position in the container, and then use the data inside the index to efficiently find the correct element in the container's storage. + +2. Implement `startIndex` and `endIndex` properties. `endIndex` must be as efficient as possible; it is required to have O(1) complexity, on every container type. + +3. Implement a `count` property with O(1) complexity. Often, this requires backing it by a stored property that gets incrementally updated every time the container changes its size. + +2. Choose a `BorrowingIterator` type, and implement the related methods `makeBorrowingIterator(from:to:)` and `currentIndex(of:)`. The most straightforward choice is to use the standard `ContainerIterator` type; it provides a reasonable default for most container types. + +3. Implement the `nextSpan(after:minCount:limitedBy:)` method. This is the core container primitive: the rest of container operations all come with default implementations based on this one. + +4. If the container is able to look up elements by value, provide custom implementations of `_custom[Last]IndexOfEquatableElement` so that standard algorithms can avoid falling back to linear searching. + +4. Implement custom implementations for additional container requirements, as needed. It is often possible to supply hand-optimized implementations that exploit the specific details of the container to provide measurably more efficient code than what the standard implementations achieve. Whether it is worth taking the extra effort to do this up front depends on the kind of container we're building, and its intended target use cases. + +Once a container type ships in source (or ABI) stable code base, its choices for `Index` and `BorrowingIterator` types get baked into its interface, and become tricky (or impossible) to change in future releases. However, it will still be possible to change the implementations of specific operations, for example, to replace the default implementation of an operation with a more efficient alternative. + +### Bidirectional Containers + +```swift +protocol BidirectionalContainer: Container, ~Copyable, ~Escapable +where Element: ~Copyable, Index: Comparable +{ + override associatedtype Element: ~Copyable + override associatedtype Index + + func spanBoundary(before index: Index) -> (index: Index, distance: Int) + + func spanBoundary( + before index: Index, maxDistance: Int, limitedBy limit: Index + ) -> (index: Index, distance: Int) + + func index(before i: Index) -> Index + func formIndex(before i: inout Index) + + override func index(after index: Index) -> Index + override func formIndex(after index: inout Index) + + @_nonoverride func index(_ index: Index, offsetBy n: Int) -> Index + @_nonoverride func formIndex(_ index: inout Index, offsetBy n: inout Int, limitedBy limit: Index) + @_nonoverride func distance(from start: Index, to end: Index) -> Int +} +``` + +Note: Some `Container` requirements are redeclared as `override`s to help associated type inference; others are kept separate with `@_nonoverride`. + +
Click to expand footnote + +`@_nonoverride` creates separate witness table entries, allowing divergent implementations in conditional conformances. This enables conforming types to provide distinct implementations depending on whether the caller is generic over `Container` or `BidirectionalContainer`. + +(Unfortunately, neither `override` nor `@_nonoverride` allows callers that are generic over `Container` to automatically dispatch to a more constrained bidirectional implementation variant. Still, at least `@_nonoverride` enables more refined implementations to take effect when the caller is explicitly generic over `BidirectionalContainer`.) + +`@_nonoverride` should be used on requirements with new semantic constraints in refining protocols. + +Collection types usually do not come with conditional conformances to refining collection protocols (as the resulting behavior can be quite confusing), so the separate witness entries rarely if ever get exercised in practice. I don't expect things would be different with Container. + +FIXME: Consider avoiding using `@_nonoverride`, reducing witness sizes. +
+ +### Random-Access Containers + +``` +public protocol RandomAccessContainer +: BidirectionalContainer, ~Copyable, ~Escapable +where Element: ~Copyable, Index: Comparable { + override associatedtype Element: ~Copyable + override associatedtype Index + + override func index(after index: Index) -> Index + override func index(before index: Index) -> Index + + override func formIndex(after index: inout Index) + override func formIndex(before index: inout Index) + + @_nonoverride func index(_ index: Index, offsetBy n: Int) -> Index + @_nonoverride func formIndex(_ index: inout Index, offsetBy n: inout Int, limitedBy limit: Index) + @_nonoverride func distance(from start: Index, to end: Index) -> Int +} +``` + +
Click to expand footnote +`RandomAccessContainer` should technically redeclare single-steppers like `index(after:)` as `@_nonoverride`, as the protocol adds a semantic requirement for O(1) complexity. However, we emulate `RandomAccessCollection`'s (not necessarily well-justified) decision to leave these marked as overrides, forcing all types to have a single implementation that fulfills the (unique) requirement. (I haven't seen a case where these steppers would need to vary their implementation, while offsetting/distance calculations do sometimes want that, at least in theory. Not so much in practice though -- see e.g. `ZipSequence`'s lack of a conditional (random-access) collection conformance. +
+ +## Mutable Containers + +### `protocol PermutableContainer` + +```swift +public protocol PermutableContainer: Container, ~Copyable, ~Escapable +where Element: ~Copyable +{ + @_lifetime(self: copy self) + mutating func swapAt(_ i: Index, _ j: Index) +} +``` + +### `protocol MutableContainer` + +```swift +public protocol MutableContainer: + PermutableContainer, ~Copyable, ~Escapable +where + Element: ~Copyable +{ + subscript(index: Index) -> Element { borrow mutate } + + @_lifetime(&self) + mutating func nextMutableSpan(after index: inout Index) -> MutableSpan + + @_lifetime(&self) + mutating func nextMutableSpan( + after index: inout Index, + maxCount: Int, + limitedBy limit: Index + ) -> MutableSpan +} +``` + +## Producers + +## In-Place Consumption + +### `struct InputSpan` + +```swift +struct InputSpan: ~Copyable, ~Escapable { + deinit + init() + init(buffer: UnsafeMutableBufferPointer, initializedCount: Int) + consuming func finalize(for buffer: UnsafeMutableBufferPointer) -> Int + + var count: Int { get } + var freeCapacity: Int { get } + var isEmpty: Bool { get } + var isFull: Bool { get } + + typealias Index = Int + var startIndex: Index { get } + var endIndex: Index { get } + var indices: Range { get } + + subscript(_ index: Int) { borrow mutate } + subscript(unchecked index: Int) { borrow mutate } + + mutating func swapAt(_ i: Index, _ j: Index) + mutating func swapAt(unchecked i: Index, unchecked j: Index) + + mutating func prepend(_ value: consuming Element) + mutating func removeFirst() -> Element + mutating func removeFirst(_ k: Int) + mutating func popFirst() -> Element? + mutating func removeAll() + mutating func prepend(moving source: UnsafeMutableBufferPointer) + mutating func prepend(repeating repeatedValue: Element, count: Int) where Element: Copyable + mutating func prepend(copying source: UnsafeBufferPointer) where Element: Copyable + mutating func prepend(copying source: borrowing Span) where Element: Copyable + + var span: Span { get } + var mutableSpan: MutableSpan { @_lifetime(&self) mutating get } + + @_lifetime(self: copy self) + mutating func withUnsafeMutableBufferPointer( + _ body: (UnsafeMutableBufferPointer, inout Int) throws(E) -> R + ) throws(E) -> R + + mutating func consumePrefix(upTo n: Int) -> InputSpan +} +``` + +### `protocol Drain` + +## Range-Replaceable Containers + +### Index Ranges and Range Expressions + +### Adding Elements to a Container + +### Replacing Subranges + +### Consuming Subranges + +### Removing Subranges + +### Dynamic Containers + +## Rejected Directions + +### Cursors + +### Index Rounding Operations + +``` + /// Return the nearest valid index in this container less than or equal to + /// the given index value, which must be valid in at least one view of self. + /// + /// This operation is important for container types that provide multiple + /// alternative projections (or "views") over the same underlying + /// representation, with each view conforming to `Container`, and sharing + /// the same `Index`. (Like `String` does with its UTF-8, UTF-16, + /// Unicode ccalar and character views in the `Collection` world.) + /// This rounding operation enables clients to convert/normalize valid index + /// values in one container view into valid indices in another, allowing them + /// to (easily) decide whether two (potentially misaligned) index values + /// address the same element. + /// + /// The default implementation of this operation simply returns `index`. + /// + /// - Complexity: Recommended to be O(1). Conforming types must clearly + /// document deviations from this expectation. + func index(alignedDown index: Index) -> Index + + /// Return the nearest valid index in this container greater than or equal to + /// the given index value, which must be valid in at least one view of self. + /// + /// This operation is important for container types that provide multiple + /// alternative projections (or "views") over the same underlying + /// representation, with each view conforming to `Container`, and sharing + /// the same `Index`. (Like `String` does with its UTF-8, UTF-16, + /// Unicode ccalar and character views in the `Collection` world.) + /// This rounding operation enables clients to convert/normalize valid index + /// values in one container view into valid indices in another, allowing them + /// to (easily) decide whether two (potentially misaligned) index values + /// address the same element. + /// + /// The default implementation of this operation simply returns `index`. + /// + /// - Complexity: Recommended to be O(1). Conforming types must clearly + /// document deviations from this expectation. + func index(alignedUp index: Index) -> Index +``` + +## Potential Future Directions + +### Support for Nonescapable `Element` Types + +### Factoring Indexing Out of Containers + +(`protocol Indexable` with no element access; allows indexable producers, with the cost of greatly increased conceptual complexity.) + +### A Protocol for Directly Initializing Storage From e7c2b349915e5063345b7e4fa9bd637dc0a73ae5 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 21 Jul 2026 16:38:33 -0700 Subject: [PATCH 49/50] Fix typos and do some basic copy editing --- Documentation/Container-design.md | 195 +++++++++++++++++++----------- 1 file changed, 122 insertions(+), 73 deletions(-) diff --git a/Documentation/Container-design.md b/Documentation/Container-design.md index 805253df..272949dd 100644 --- a/Documentation/Container-design.md +++ b/Documentation/Container-design.md @@ -1,5 +1,11 @@ # An Ownership-Aware Container Model for Swift +* Author: [Karoy Lorentey](https://github.com/lorentey) +* Version history: + - 0.1 (2026-07-21): Initial draft, describing `Container`. + +## Table of Contents + * [Introduction](#introduction) * [Making Sense of the Design Space](#making-sense-of-the-design-space) * ["Elementwise Iteration" vs "Bulk Iteration"](#elementwise-iteration-vs-bulk-iteration) @@ -44,7 +50,7 @@ ## Introduction -Over the last several years, we've been [gradually][BorrowingConsuming] [building][NoncopyableTypes] [up][NoncopyableGenerics] [an][PartialConsumption] [ownership][PatternMatching] [model][NonescapableTypes] [for][SuppressedAssociatedTypes] [Swift][BorrowAndMutate], to simplify the creation of safe high-performance Swift code. Our goal is to fulfill Swift's mandate to become a high-performance systems programming language, suitable for use in all computing tasks, from the smallest microcontrollers to the largest supercomputers. As many of the target environments need to operate within strict performance constraints, developers who specialize on them expect to have precise, predictable control over runtime behavior, even at the cost of some coding flexibility. +Over the last several years, we've been [gradually][BorrowingConsuming] [building][NoncopyableTypes] [up][NoncopyableGenerics] [an][PartialConsumption] [ownership][PatternMatching] [model][NonescapableTypes] [for][SuppressedAssociatedTypes] [Swift][BorrowAndMutate], to simplify the creation of safe high-performance Swift code. Our goal is to fulfill Swift's mandate to become a high-performance systems programming language, suitable for use in all computing tasks, from the smallest microcontrollers to the largest supercomputers. As many of the target environments need to operate within strict performance constraints, developers who specialize in them expect to have precise, predictable control over runtime behavior, even at the cost of some coding flexibility. [BorrowingConsuming]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0377-parameter-ownership-modifiers.md [NoncopyableTypes]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0390-noncopyable-structs-and-enums.md @@ -59,7 +65,7 @@ Over the last several years, we've been [gradually][BorrowingConsuming] [buildin Crucially, Swift needs to satisfy this need without resorting to unsafe interfaces: our aim is to build constructs that can match (or exceed) the performance of legacy systems programming languages, while also avoiding undefined behavior if the interfaces get misused. -As of Swift 6.4, we have now implemented a small but quickly growing list of useful data structures that follow these new design priorities: +As of Swift 6.4, we have implemented a small but quickly growing list of useful data structures that follow these new design priorities: - Members of the nonescapable span family provide safe, direct access to "somebody else's" contiguous pieces of memory. - [`Span`][Span], a read-only reference to fully initialized memory @@ -106,7 +112,7 @@ However, unlike `Collection`s, these types can contain noncopyable elements, and Swift 6.4 introduced [protocol `Iterable`][Iterable] to enable borrowing for-in loops over these new types. The new protocol made several notable choices in the design space of ownership-aware iteration; it is crucial that we identify them so that we can carefully examine the purpose and consequences of each one, and so that we are able to analyze alternative choices. Each specific choice defines a particular design axis; we'll give them names that reflect their purpose. -We do this not to criticise the design of `Iterable`, but to understand the use cases for which it is best suited, and to allow us to explore the full design space with intention. Identifying design axes allows us to derive a full set of potential abstractions almost mechanically, so that we can analyze them and develop the ones that seem most useful into concrete protocols in the rest of this document. +We do this not to criticize the design of `Iterable`, but to understand the use cases for which it is best suited, and to allow us to explore the full design space with intention. Identifying design axes allows us to derive a full set of potential abstractions almost mechanically, so that we can analyze them and develop the ones that seem most useful into concrete protocols in the rest of this document. We list the four axes we are considering below. The rest of this introductory section will define each of these in detail, but their names already give us a hint of their purpose: @@ -118,21 +124,21 @@ We list the four axes we are considering below. The rest of this introductory se Under these terms, our classic `Sequence` models _non-failable, generative, elementwise iteration by taking elements_.
The new `Iterable` protocol models _failable, generative, bulk iteration by borrowing elements_. -In the rest of this document, we'll define three additional core protocols, `Container`, `Producer` and `Drain` (as well as a number of auxiliary protocols refining them). The four core protocols have the following properties: +In the rest of this document, we'll define three additional core protocols, `Container`, `Producer` and `Drain` (as well as a number of auxiliary protocols refining them). The four core protocols have the following properties and relationships: | Protocol | Elementwise/bulk | Borrowing/taking | Generative/Visitative | Failable | | :--- | :--- | :---: | :---: | :---: | | [`Iterable`][Iterable] | bulk (`Span`-based) | borrowing | generative | failable | -| `└╴`[`Container`](#container) | bulk (`Span`-based) | borrowing | visitative | -- | -| [`Producer`](#producer) | bulk (`OutputSpan`-based) | taking | generative | failable | -| `└╴`[`Drain`](#drain) | bulk (`InputSpan`-based) | taking | visitative | -- | +| `└╴`[`Container`](#read-only-container-model) | bulk (`Span`-based) | borrowing | visitative | -- | +| [`Producer`](#producers) | bulk (`OutputSpan`-based) | taking | generative | failable | +| `└╴`[`Drain`](#protocol-drain) | bulk (`InputSpan`-based) | taking | visitative | -- | We can already use this table to gain some interesting observations: - Our proposed new protocols all have a strong preference towards bulk (rather than elementwise) iteration. - "Iteration by borrowing" and "iteration by taking" are independent abstractions; they are both useful enough to deserve their separate protocol hierarchies. -- Both visitative protocols refine their generative counterparts. This indicates a strong relationship between these concepts, with the visitative model providing a richer abstraction, in exchange for putting more restrictions on conforming types. -- Failability is strongly correlated with generative iteration. Neither of our proposed "visitative" protocols are failable. +- The design indicates that the generative iteration model is a "wider" or "weaker" abstraction than the "narrower"/"stronger" visitative one; both visitative protocols refine their generative counterparts. This is, to some extent, intuitively understandable: a protocol that only works with preexisting elements can also implement an interface that allows them to be generated on the fly. In exchange, the visitative protocols can provide richer, more specialized abstractions. +- This design also strongly correlates failability with generative iteration. Neither of our proposed "visitative" protocols is failable. This too follows from the fact that visitative iteration merely accesses elements that already exist; there isn't much possibility for these accesses to fail. Let's now explore this design space a little further, by looking at the benefits and consequences of each decision. @@ -148,15 +154,15 @@ This model of **elementwise iteration** is extremely straightforward to understa In elementwise iteration, we need to call a protocol's customizable entry point for each and every item we traverse. The entry point needs to load the iteration's current state, and find (or generate) the next element to visit -- precisely what that means varies wildly between each type we want to iterate over. -This makes it much harder for the compiler to reliably reason about and optimize code using `Sequence` types; this is especially difficult for sequences whose definitions are hidden behind a resiliance boundary. In classic Swift, it isn't uncommon to see performance drop by a factor of hundreds as an operation's implementation moves across resilient module boundaries. As library evolution is a crucial feature of the language, this is rather unfortunate. +This makes it much harder for the compiler to reliably reason about and optimize code using `Sequence` types; this is especially difficult for sequences whose definitions are hidden behind a resilience boundary. In classic Swift, it isn't uncommon to see performance drop by a factor of hundreds as an operation's implementation moves across resilient module boundaries. As library evolution is a crucial feature of the language, this is rather unfortunate. The new `Iterable` protocol resolves this issue by introducing the idea of **bulk iteration**, where each primitive iteration step exposes multiple items all at once to the client, batched up into a `Span` instance. ```swift - mutating func nextSpan(maximumCount: Int) throws(Failure) -> Span + mutating func nextSpan(maxCount: Int) throws(Failure) -> Span ``` -`Span` is a small, frozen type in the Swift Standard Library, eminently amenable to optimizations -- efficiently traversing the elements of a span is a drastically simpler problem than iterating over an arbitrary sequence. `Iterable` forcibly forces conforming types to factor iteration into two distinct layers: clients still invoke custom code to retrieve the next batch of items, but once they have them, accessing the individual elements within each batch becomes dependably cheap. +`Span` is a small, frozen type in the Swift Standard Library, eminently amenable to optimizations -- efficiently traversing the elements of a span is a drastically simpler problem than iterating over an arbitrary sequence. `Iterable` forces conforming types to factor iteration into two distinct layers: clients still invoke custom code to retrieve the next batch of items, but once they have them, accessing the individual elements within each batch becomes dependably cheap. For iterables that physically store their contents in memory, implementing iteration simply requires exposing spans over their preexisting piecewise contiguous storage chunks -- the bigger the chunks, the more efficient iteration becomes, even if `nextSpan`'s implementation isn't visible to the optimizer. @@ -170,7 +176,13 @@ Bulk iteration is not without drawbacks: it comes with a drastically more compli To understand how `Iterable` works, we need to learn about what `Span` is, which requires us to also learn at least a little about nonescapable types. We need to figure out how to resolve a whole new class of compiler errors, and ultimately we need to get comfortable reading lifetime dependency declarations, to allow us to predict what operations we can express and architect our solutions without running into constant issues. -Operations for bulk iteration are full of subtle design problems that often don't seem particularly important, but dismissing them can render the abstraction impossible to use in some contexts. For instance, `nextSpan`'s `maxCount` parameter is there to allow clients to limit the number of elements they receive at a time. Having to accommodate this limit is a significant complication for conforming types, so it is tempting to cut the complexity by force-feeding clients with an arbitrary number of items. (After all, clients often set `maxCount` to `Int.max` anyway, and don't mind having to potentially deal with millions of items at a time.) However, if someone just needs to look at the first three elements to make a decision about what to do with the rest, giving them four thousand items would put them in an awkward position -- they need to stash the leftovers somewhere, and then process them before pulling on the iterator again. The spans that `nextSpan` returns are tied to an exclusively access of the iterator, which (currently at least) makes it impossible to actually store them in any meaningful way: these clients would be drowned in a sea of elements they cannot process. By simplifying conforming implementations, we would significantly limit the usefulness of the protocol. +Operations for bulk iteration are full of subtle design complications that often don't seem particularly important, but dismissing them can render the abstraction impossible to use in some contexts. For instance, `nextSpan`'s `maxCount` parameter is there to allow clients to limit the number of elements they receive at a time. Having to accommodate this limit is a significant complication for conforming types, so it is tempting to cut the complexity by force-feeding clients an arbitrary number of items. (After all, clients often set `maxCount` to `Int.max` anyway, and don't mind having to potentially deal with millions of items at a time.) + +However, consider a client that just wants to look at the first three elements to make a decision about what to do with the rest. Giving this caller four thousand items would put them in an awkward position: they would need to stash the leftovers somewhere, and then process them all before pulling on the iterator again. The spans that `nextSpan` returns are tied to an exclusive access of the iterator, which (currently at least) makes it impossible to actually store them alongside the iterator in any meaningful way: these clients would be drowned in a sea of elements they cannot process. By simplifying conforming implementations, we would significantly limit the usefulness of the protocol. + +
Click to expand footnote +> Throwing away the iterator and restarting it may seem like a possible workaround, but as `Iterable` types aren't required to produce the same items on repeated iterations, this cannot be a general solution. It only works on some iterable types, such as the containers we are introducing in this document. +

How bulk operations report/handle failures is a similarly subtle but important complication: operations that need to throw errors must be able to properly report partial success, to avoid data loss and to allow clients to identify precisely which element triggered the error. If the fifth element of an `Iterable` instance happens to trigger an error, it still needs to be possible for clients to reliably access the first four elements -- no matter what value they use for `maxCount`.

@@ -182,7 +194,7 @@ Code iterating over a `Sequence` gains full ownership of the items it accesses. In contrast, `Iterable` was designed to support noncopyable elements, which do not allow such simple workarounds. Returning a noncopyable instance means transferring unique ownership of it. For container types, this would be a destructive operation, as the contents would have to be physically moved out of the container, emptying it out or entirely consuming it in the process. This would not be workable as the default form of iteration: we naturally expect to be able to iterate over a container multiple times without destroying it in the process. -To avoid this, `Iterable` instead choses to return _borrowing references_ to the elements it traverses, not the elements themselves. Clients do not get ownership over the items they access -- they get a temporary window that they can peer through to see a batch of items at a time; but they don't get to break the glass (to modify or consume the items), and once the window moves to the next batch, they lose sight to all previously seen items. +To avoid this, `Iterable` instead chooses to return _borrowing references_ to the elements it traverses, not the elements themselves. Clients do not get ownership over the items they access -- they get a temporary window that they can peer through to see a batch of items at a time; but they don't get to break the glass (to modify or consume the items), and once the window moves to the next batch, they lose sight of all previously seen items. In this document, we'll call the ownership model of `Iterable` **iteration by borrowing**, as clients _borrow_ the elements they traverse. The other way to gain access to something is to _take_ ownership of it -- hence, we'll call the model `Sequence` follows **iteration by taking**. @@ -192,21 +204,21 @@ In this document, we'll call the ownership model of `Iterable` **iteration by bo -Of course, the way `Iterable` only provides read-only, borrowing access to its elements severely limits what clients can do with them. Obviously, we will also need to provide iterator-like constructs that transfer ownership of their elements to the caller, so that it can collect them into a container type, or otherwise mutate/consume them as it wishes. In this document, we are modeling the idea of "iterating by taking elements" with protocol [`Producer`][Producer] +Of course, the way `Iterable` only provides read-only, borrowing access to its elements severely limits what clients can do with them. Obviously, we will also need to provide iterator-like constructs that transfer ownership of their elements to the caller, so that it can collect them into a container type, or otherwise mutate/consume them as it wishes. In this document, we are modeling the idea of "iterating by taking elements" with protocol [`Producer`](#producers). A variant of the `Iterable` approach is one where instead of borrowing references, we provide mutable references to elements -- we change the unit of iteration from `Span` to `MutableSpan` (or change `Ref` to `MutableRef`). The source of the elements still retains ownership in this case, but clients are allowed to arbitrarily mutate or even replace them. In this document, we are modeling this approach with `MutableContainer`; we are not introducing an `Iterable`-style, generative protocol. ### "Generative" vs "Visitative Iteration" -`Sequence` and `Iterable` both allow their elements to be generated on the fly. We'll be calling this style of traversal **generative iteration**. This allows a wide spectrum of conforming types, but it complicates performance analyis, as the variable cost of on-demand generation inherently adds a difficult term to the complexity of element access. +`Sequence` and `Iterable` both allow their elements to be generated on the fly. We'll be calling this style of traversal **generative iteration**. This allows a wide spectrum of conforming types, but it complicates performance analysis, as the variable cost of on-demand generation inherently adds a difficult term to the complexity of element access. -Additionally, generative iteration by _borrowing_ (as implemented by `Iterable`) has the crucial limitation that the client cannot hold on to generated items as they come out of the iterator -- it is only able to see only a single batch of them at a time, and the minute it advances the iterator, it loses sight of all the items it previously encountered. Because `Iterable` allows elements to be generated (and discarded!) on the fly, clients must destroy all references to the elements they see before they can advance to the next batch. This strictly limits the kinds of algorithms we can implement over `Iterable`: in particular, we cannot define lookup or search algorithms that need to return references to specific elements (such as `min()` or `first(where:)`), unless we require `Element` to be copyable. The elements we want to reference may evaporate the moment we advance the iterator! +Additionally, generative iteration by _borrowing_ (as implemented by `Iterable`) has the crucial limitation that the client cannot hold on to generated items as they come out of the iterator -- it is only able to see a single batch of them at a time, and the minute it advances the iterator, it loses sight of all the items it previously encountered. Because `Iterable` allows elements to be generated (and discarded!) on the fly, clients must destroy all references to the elements they see before they can advance to the next batch. This strictly limits the kinds of algorithms we can implement over `Iterable`: in particular, we cannot define lookup or search algorithms that need to return references to specific elements (such as `min()` or `first(where:)`), unless we require `Element` to be copyable. The elements we want to reference may evaporate the moment we advance the iterator! Not all iterable types need to generate their items on demand. In particular, many of the most useful data structures physically hold their contents in memory, and they can implement iteration by simply locating their storage chunks and directly exposing spans over them. Arrays, linked lists, hashed sets, hashed dictionaries, ring buffers, search trees, ropes are all examples of such data structures, and of course there are many more. Data structures with preexisting storage form a highly useful subset of iterables, and it is worth giving them a name; we'll call such types **containers**, and the traversal they support **visitative iteration**. These terms emphasize that iterating over a container merely visits its preexisting contents, rather than materializing them on the fly. Locating items in preexisting storage is a far simpler task than generating them; and clients can safely extract and work with references to such items as long as they do not mutate the instance that contains them. -Not all data structures are containers, of course. For example, Swift's standard `String` type is a sequence of `Character` instances, but those instances are not directly stored anywhere in `String`'s storage representation -- they need to be created on the fly, as we iterate over the string instance. `String` therefore implements _generative_ rather than _visitative_ iteration; it is not a container type. (Of course, it would be possible to build a container of text data; but to do it efficiently, we'd likely need to avoid using `Character` as its `Element`.) +Not all data structures are containers in this sense, of course. For example, Swift's standard `String` type is a sequence of `Character` instances, but those instances are not directly stored anywhere in `String`'s storage representation -- they need to be created on the fly, as we iterate over the string instance. `String` therefore implements _generative_ rather than _visitative_ iteration; it is not a container type. (Of course, it would be possible to build a container of text data; but to do it efficiently, we'd likely need to avoid using `Character`-style grapheme clusters as its `Element`.) ### Failability @@ -214,15 +226,15 @@ The final design aspect we need to consider is failability: whether we need to a The classic `Sequence` protocol provides no way for conforming types to signal a failure, other than by trapping or by stopping the iteration earlier than expected. For many developers, this feels like a defect -- `Sequence` allows (or even encourages) conforming types to produce their elements by running arbitrarily complex calculations; and of course those calculations can sometimes legitimately encounter non-fatal problems. The inability to properly signal failure leads to awkward workarounds. -Using the terminology established in the previous section, the ability of fail is therefore a natural expectation for _generative_ constructs. +Using the terminology established in the previous section, the ability to fail is therefore a natural expectation for _generative_ constructs. -The `Iterable` protocol addresses this by defining `Failure` associated type and providing a throwing `nextSpan` method on its iterator. It relies on [typed throws][TypedThrows] so that conforming types that never need to throw can set `Never` as their failure type, enabling clients to avoid writing error handling code that deals with errors that are guaranteed never to happen. +The `Iterable` protocol addresses this by defining a `Failure` associated type and providing a throwing `nextSpan` method on its iterator. It relies on [typed throws][TypedThrows] so that conforming types that never need to throw can set `Never` as their failure type, enabling clients to avoid writing error handling code that deals with errors that are guaranteed never to happen. This potentially allows lazy `Iterable` algorithms (like `filter`) to take throwing closures, and cleanly propagate errors to clients. In exchange, failability greatly complicates the bulk iteration model, as operations need to be able to [properly report partial success](#bulk-failures).
Click to expand footnote -(However, we also expect a filter predicate to be able to throw a _different_ error type than the `Iterable`'s own `Failure`. We currently lack the means to express that, as the `nextSpan` method would need to be able to throw either error. We need to do further language-level work -- such as union error types -- to allow us to express such abstractions in a satisfying way.) +> However, we also expect a filter predicate to be able to throw a _different_ error type than the `Iterable`'s own `Failure`. We currently lack the means to express that, as the `nextSpan` method would need to be able to throw either error. We need to do further language-level work -- such as union error types -- to allow us to express such abstractions in a satisfying way.
@@ -230,6 +242,10 @@ On the other hand, the ability to fail is far less important for _visitative_ co This greatly simplifies the container model, but it does mean that throwing algorithms like our hypothetical lazy `filter` can only produce `Iterable` types -- they cannot return containers, even if their input is one. +
Click to expand footnote +Some readers may note a wrinkle in that we're assuming that accessing storage held in memory cannot possibly fail. While it is true that accessing memory can trigger faults (e.g., consider `mmap`ped regions), we lack the means to turn these faults into recoverable errors in Swift, and it seems unlikely it would be actually desirable to design container protocols around a hypothetical future language direction like that. The pragmatic choice is to assume that container types are stored in memory allocated using Swift's dedicated primitives, and access to them can never fail without crashing the entire process (or an isolated subsystem within it). +
+ Let us now introduce the actual protocols, starting with `Container` itself. ## Read-Only Container Model @@ -250,7 +266,7 @@ where The `Container` protocol refines `Iterable`; `Iterable` algorithms are able to work with container types with no extra effort. However, not all iterable types can be containers. The requirement that a container's elements must preexist in memory rules out all iterables that generate items on demand; using the terms [we established above](#generative-iteration-vs-visitative-iteration), we say that iterables model _generative iteration_, while containers are restricted to _visitative_ semantics. -`Container` requires `Failure` to be set to `Never`: because the contents of a container are required exist in advance within the container instance, they can always be successfully iterated: there is never a need to throw an error. +`Container` requires `Failure` to be set to `Never`: because the contents of a container are required to exist in advance within the container instance, they can always be successfully iterated: there is never a need to throw an error. Naturally, container types are not required to be copyable, nor escapable. They don't require their elements to be copyable, either. (Support for nonescapable elements is a [highly desirable future direction](#support-for-nonescapable-element-types), but we currently lack the tools to express it.) @@ -268,17 +284,17 @@ protocol Container: ... { Repeated invocations of the `count` property on the same container must return the same value. The returned value must match the number of elements that can be accessed by iterating through the container. -Unlike `Collection`, types conforming to `Container` are **required to produce their `count` in constant complexity**. This reflects the protocol's focus on predictable performance, and avoids a common worry with `Collection`. +Unlike `Collection`, types conforming to `Container` are **required to produce their `count` in constant complexity**. This reflects the protocol's focus on predictable performance, and avoids a common worry with `Collection`. Conforming to this requirement typically requires container implementations to cache their count in an easily accessible stored property, and incrementally update it every time the container changes its size.
Click to expand footnote -A consequence of this requirement is that constructs like lazy filter algorithms cannot practically conform to the protocol. However, they can still be `Iterable`, and that is in fact good enough for the vast majority of their use cases in practice. Notably, custom on-the-fly filtering is inherently incompatible with the expectation of predictable performance. (After all, this protocol exists to focus on high-performance use cases; it would be a mistake to dilute this focus until the protocol becomes indistinguishable from `Collection`.) - -`count` is required to return a finite integer that fits in `Int`. This can be a true limitation, as some containers may have more than `Int.max` elements, despite the protocol's requirement for preexisting storage! The storage requirement does not preclude some containers to link specific storage chunks multiple times (or simply repeat them), without allocating separate storage for each duplicate run. Such repetitions can cause the count of a container to overflow `Int`'s range, without ever overflowing available memory. While such humungous containers are certainly interesting, we do not consider it crucial to provide dedicated support for them. - -In the design we are proposing, humungous containers can choose to either only conform to `Iterable`, or to trigger a trap if they are ever asked for their count. Client code often invokes `count` so that it can preallocate storage for related work; obviously that is not going to end well if a container's count exceeds `Int.max`. (And in fact trapping early is much preferable to allowing the operation to inevitably fail midway through some vast computation.) - -If we wanted to support would be to have `count` return an optional, or to push this property down into a separate `FiniteContainer` protocol. The overwhelming complexity of these options does not feel to be anywhere in proportion to the practical importance of such cases. Which is not to say they don't exist: tree-based ropes in particular (like `Foundation`'s `AttributedString`) can easily grow to humungous sizes, by simply concatenating a rope with itself a few dozen times. However, these are mostly just fun curiosities; such trees are rarely (if ever) practically useful.) +> One consequence of this requirement is that constructs like lazy filter algorithms cannot practically conform to the protocol. However, they can still conform to `Iterable`, and that is in fact good enough for the vast majority of their use cases in practice. Notably, custom on-the-fly filtering is inherently incompatible with the expectation of predictable performance. (After all, the `Container` protocol exists to focus on high-performance use cases; it would be a mistake to dilute this focus until the protocol becomes indistinguishable from `Collection`.) +> +> `count` is required to return a finite integer that fits in `Int`. This can be a true limitation, as some containers may have more than `Int.max` elements, despite the protocol's requirement for preexisting storage! The storage requirement does not preclude some containers from linking specific storage chunks multiple times (or simply repeating them), without allocating separate storage for each duplicate run. Such repetitions can cause the count of a container to overflow `Int`'s range, without ever overflowing available memory. While such humongous containers are certainly interesting, we do not consider it crucial to provide dedicated support for them. +> +> In the design we are proposing, humongous containers can choose to either only conform to `Iterable`, or to trigger a trap if they are ever asked for their count. Client code often invokes `count` so that it can preallocate storage for related work; obviously that is not going to end well if a container's count exceeds `Int.max`. (And in fact trapping early is much preferable to allowing the operation to inevitably fail midway through some vast computation.) +> +> If we wanted to support them, one option would be to have `count` return an optional, or to push this property down into a separate `FiniteContainer` protocol. The overwhelming complexity of these options does not feel to be anywhere in proportion to the practical importance of such cases. Which is not to say they don't exist: tree-based ropes in particular (like `Foundation`'s `AttributedString`) can easily grow to humongous sizes, by simply concatenating a rope with itself a few dozen times. However, these are mostly just fun curiosities; such trees are rarely (if ever) practically useful.
@@ -294,6 +310,8 @@ protocol Container: ... { This comes with a default implementation that simply checks if `count` is zero. (`Collection` defines a default implementation for its `isEmpty` that compares `startIndex` to `endIndex`. Given that `Container` requires its `count` to have O(1) complexity, it is slightly better to define `isEmpty` in terms of it, as it avoids having to materialize two index instances.) +Infinite/vast containers can provide their own `isEmpty` implementation that avoids using `count`, for example, by following `Collection`'s pattern. (They also need to provide a custom implementation for `underestimatedCount`, for the same reason.) + ### Container Indices As `Container` refines `Iterable`, it provides a `BorrowingIterator`, and we can use this iterator to access the elements of a container in batches, starting from its beginning. However, it would be a shame to stop there: `Container` can also provide a more flexible model for element access that acknowledges that its contents survive across iteration steps. To help model this, we introduce a slightly adapted version of `Collection`'s familiar `Index` concept. @@ -306,7 +324,7 @@ protocol Container: ... { } ``` -Our indices represent abstract positions within containers (just as they do in collections): one useful way to look at them is to say that they're addressing the logical boundaries between neighboring elements, with a "start index" addressing the boundary before the first element, and the "end index" addressing the boundary after the last. A container with five items therefore has six indices, adressing all its various logical positions: +Our indices represent abstract positions within containers (just as they do in collections): one useful way to look at them is to say that they're addressing the logical boundaries between neighboring elements, with a "start index" addressing the boundary before the first element, and the "end index" addressing the boundary after the last. A container with five items therefore has six indices, addressing all its various logical positions: ``` ┌─────┬─────┬─────┬─────┬─────┐ @@ -347,15 +365,20 @@ protocol Container: ... { `startIndex` and `endIndex` work exactly like `Collection`'s corresponding properties, defining the bounds of a half-open range: `endIndex` returns a valid index that addresses the logical empty slot following the container's last element, while `startIndex` addresses the container's first element. -`index(_:offsetBy:)` is the `Container` analogue of `BorrowingIterator`'s `skip(by:)` method. - -Notably, we replace `Collection`'s classic `index(_:offsetBy:limitedBy:)` requirement with an improved variant ([first introduced on `UniqueArray`][formIndex-offsetBy-limitedBy]) that reports the number of steps it managed to take before reaching the limit. This avoids having to figure this out with a separate `distance(from:to:)` invocation, enabling more efficient use of this operation situation that need this data; notably, it allows easy single-pass offsetting across concatenated containers. `Collection`'s original `index(_:offsetBy:limitedBy:)` operation is still available, as a standard algorithm based on the new requirement. - -[formIndex-offsetBy-limitedBy]: https://github.com/swiftlang/swift/blob/swift-6.4.x-DEVELOPMENT-SNAPSHOT-2026-07-06-a/stdlib/public/core/UniqueArray/UniqueArray%2BContainer.swift#L267-L273 +`index(_:offsetBy:)` is the `Container` analogue of `BorrowingIterator`'s `skip(by:)` method. It has slightly different semantics though, as it follows `Collection`'s behavior: `index(_:offsetBy:)` always takes exactly the specified number of steps, and it traps if it runs off the end of the container. As `Container` models a forward-only container, its `index(_:offsetBy:)` operation requires a nonnegative offset. (We'll shortly introduce a `BidirectionalContainer` refinement that will relax this constraint.) -As indices aren't required to be `Comparable`, the default implementation of `distance(from:to:)` cannot quickly validate that its `start` argument precedes `end`. To avoid having to run all the way to end of the container to detect misuse, the algorithm instead iterates forward from both arguments, until it finds the other. This makes the default implementation twice as slow, but it allows it to correctly calculate negative distances. In the common case when `Index` is `Comparable`, we also provide a refined default algorithm that avoids this overhead. +As indices aren't required to be `Comparable`, the default implementation of `distance(from:to:)` cannot quickly validate that its `start` argument precedes `end`. To avoid having to run all the way to the end of the container to detect misuse, the algorithm instead iterates forward from both arguments, until it finds the other. This makes the default implementation twice as slow, but it allows it to correctly calculate negative distances. In the common case when `Index` is `Comparable`, we also provide a refined default algorithm that avoids this overhead. + +Notably, we replace `Collection`'s classic `index(_:offsetBy:limitedBy:)` requirement with an improved variant ([first introduced on `UniqueArray`][formIndex-offsetBy-limitedBy]) that reports the number of steps it was unable to take when reaching the limit. This avoids having to figure this out with a separate `distance(from:to:)` invocation, enabling more efficient use of this operation in situations that need this data; for example, it allows easy single-pass offsetting across concatenated containers. `Collection`'s original `index(_:offsetBy:limitedBy:)` operation is still available, as a standard algorithm based on the new requirement. + + +The `limit` argument here (and also elsewhere throughout the `Container` interface surface) means a **limiting index**, intended to cause the operation to stop if it encounters the limit during its execution. A limit of this sort only stops the operation if it needs to actively iterate over the corresponding position; a limit that the operation never needs to visit has no effect, whether it happens to address a position before or after the visited range. For example, if we're trying to iterate forward by `n` steps, a limit that's behind the start position has no effect. These specific semantics allow types that cannot provide comparable indices to still correctly conform to the protocol. (For example, linked lists usually cannot determine relative ordering between their indices without actively iterating through the list in linear time, as we've seen with `distance(from:to:)`.) + + +[formIndex-offsetBy-limitedBy]: https://github.com/swiftlang/swift/blob/swift-6.4.x-DEVELOPMENT-SNAPSHOT-2026-07-06-a/stdlib/public/core/UniqueArray/UniqueArray%2BContainer.swift#L267-L273 + ### Visitative Iteration @@ -372,7 +395,7 @@ protocol Container: ... { Like the corresponding iterator method on `Iterable`, this implements [bulk iteration](#elementwise-iteration-vs-bulk-iteration): it gives clients access to a batch of items all at once, allowing them to quickly iterate over the returned `Span` instance without invoking any other `Container` methods. -However, this `nextSpan` function is only allowed to mutate an index, not the container itself. Additionally, the spans returned by `nextSpan` are declared to be scoped to a "borrow" of the container, too. This is the crucial difference from `Iterable`, whose spans extend (and are tied to) a particular mutation of the iterator. This is what causes `Container` to fundamentally require its elements to pre-exist in memory -- it isn't possible a `nextSpan` with this signature to materialize items on the fly. Containers are required to implement [visitative iteration](#generative-vs-visitative-iteration). +However, this `nextSpan` function is only allowed to mutate an index, not the container itself. Additionally, the spans returned by `nextSpan` are declared to be scoped to a "borrow" of the container, too. This is the crucial difference from `Iterable`, whose spans extend (and are tied to) a particular mutation of the iterator. This is what causes `Container` to fundamentally require its elements to preexist in memory -- it isn't possible for a `nextSpan` with this signature to materialize items on the fly. Containers are required to implement [visitative iteration](#generative-vs-visitative-iteration). `Container.nextSpan` returns a `Span` instance that begins with the container's element that the given index addresses, and runs to the end of the container's storage chunk that contains it. On return, the index is updated to address the item following the last element in the returned span. If the input index is the `endIndex`, then the method returns an empty span, and leaves the index as is. @@ -430,7 +453,7 @@ This more powerful form of `nextSpan` is a core primitive; by default, most othe ```swift extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { - public func index(_ index: Index, offsetBy n: Int) -> Index { + func index(_ index: Index, offsetBy n: Int) -> Index { var index = index var n = n let end = self.endIndex @@ -444,9 +467,9 @@ extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { } ``` -Containers often hold their contents in piecewise contiguous storage chunks; as this default implementation iterates over entire chunks, it can be considerably more efficient than stepping through indices one by one, like `Collection` does. As the elements are required to preexist in memory, materializing spans over them is relatively cheap -- `nextSpan` merely needs to locate storage, not populate its contents. Still, it is often possible to implement required operations more directly, and it is good practice to do so whenever it leads to measureable improvement. +Containers often hold their contents in piecewise contiguous storage chunks. As this default implementation iterates over entire chunks, it can be considerably more efficient than stepping through indices one by one, like `Collection` does. As the elements are required to preexist in memory, materializing spans over them is relatively cheap -- `nextSpan` merely needs to locate storage, not populate its contents. Still, it is often possible to implement required operations more directly, and it is good practice to do so whenever it leads to measurable improvement. -The default implementation of `distance(from:to:)` poses an interesting problem: `Container` only allows forward iteration, so to measure the distance between two indices, we have to start iterating from the one addressing the earlier one. But container's `Index` is not required to be `Comparable`, which means that we have three options: +The default implementation of `distance(from:to:)` poses an interesting problem: `Container` only allows forward iteration, so to measure the distance between two indices, we have to start iterating from the one addressing the earlier one. But container does not require its `Index` to be `Comparable`, so that's not something we can easily check. We have three options to resolve this: 1. Only provide a default `distance` algorithm for containers with comparable indices. @@ -457,13 +480,14 @@ The default implementation of `distance(from:to:)` poses an interesting problem: Element: ~Copyable, Index: Comparable { - public func distance(from start: Index, to end: Index) -> Int { + func distance(from start: Index, to end: Index) -> Int { var (i, j, forward): (Index, Index, Bool) = (start <= end ? (start, end, true) : (end, start, false)) var d = 0 while i < j { - let span = self.nextSpan(after: &i, limitedBy: j) + let span = self.nextSpan(after: &i, maxCount: .max, limitedBy: j) + precondition(span.count > 0, "Invalid Container") d += span.count } return forward ? d : -d @@ -471,15 +495,17 @@ The default implementation of `distance(from:to:)` poses an interesting problem: } ``` + This visits exactly as many storage chunks as exist between the indices, so it is the most efficient way to calculate the distance. (Without knowing more about the internals of the container.) + 2. Require `start` to precede `end`, but with no easy way to validate this other than letting iteration go all the way to the end of the container. ```swift extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { - public func distance(from start: Index, to end: Index) -> Int { + func distance(from start: Index, to end: Index) -> Int { var i = start var d = 0 while true { - let c = self.nextSpan(after: &i, limitedBy: j).count + let c = self.nextSpan(after: &i, maxCount: .max, limitedBy: end).count d += c if i == end { break } precondition(c > 0, "Invalid Container or 'start' does not precede 'end'") @@ -489,11 +515,13 @@ The default implementation of `distance(from:to:)` poses an interesting problem: } ``` + This option is equivalent to the previous one if `start` happens to come before `end`, but it runs all the way to the end of the container and then traps if they are in the wrong order. `Collection`'s original `distance` had no trouble returning negative values, so choosing this option could invite accidental misuse. + 3. Allow `start` and `end` to be in any order, but iterate forward from both ends until we find the other: ```swift extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { - public func distance(from start: Index, to end: Index) -> Int { + func distance(from start: Index, to end: Index) -> Int { // This variant allows start to follow end, but as indices aren't // comparable, we have to measure distances from both ends. var d1 = 0 @@ -521,7 +549,27 @@ The default implementation of `distance(from:to:)` poses an interesting problem: } ``` -To preserve continuity/interoperability with `Collection` (whose distance allows any ordering), `Container` implements option three, while also providing the simpler/faster implementation from option 1, for the common case when `Index` is `Comparable`. + This option has to visit (at worst) twice as many items as the previous two in their regular execution, as the `limitedBy:` arguments [have no effect if the specified `limit` lies behind the start position](#limiting-index-semantics). + +To preserve continuity/interoperability with `Collection` (whose distance allows any ordering), `Container` implements option 3, while also providing the simpler/faster implementation from option 1, for the common case when `Index` is `Comparable`. + +For convenience, `Container` provides overloads that (effectively) make `nextSpan`'s `maxCount` and `limit` arguments optional: + +```swift +extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { + @_lifetime(borrow self) + func nextSpan(after index: inout Index, maxCount: Int) -> Span { + self.nextSpan(after: &index, maxCount: maxCount, limitedBy: self.endIndex) + } + + @_lifetime(borrow self) + func nextSpan(after index: inout Index, limitedBy limit: Index) -> Span { + self.nextSpan(after: &index, maxCount: .max, limitedBy: limit) + } +} +``` + +(The snippets above have already relied on these to avoid spelling out `maxCount`.) ### Subscripting @@ -572,8 +620,7 @@ where @_lifetime(&self) mutating func nextSpan(maxCount: Int) -> Span { - _base.value.nextSpan(after: &self._position, maxCount: maxCount, limitedBy: end) - } + _base.value.nextSpan(after: &self._position, maxCount: maxCount, limitedBy: _end) } @_lifetime(self: copy self) @@ -599,7 +646,7 @@ protocol Container: ... { extension Container where Self: ~Copyable & ~Escapable, - Element: ~Copyable, + Element: ~Copyable { @_lifetime(borrow self) func makeBorrowingIterator() -> BorrowingIterator { @@ -620,7 +667,7 @@ The `underestimatedCount` of a `Container` is simply its count: ```swift extension Container where - Self: ~Copyable, + Self: ~Copyable & ~Escapable, Element: ~Copyable { var underestimatedCount: Int { self.count } @@ -678,7 +725,7 @@ Like with `Collection`, these operations come with default implementations that ### Performance Requirements -To achive predictable performance, `Container` operations are expected to have the following worst-case complexities: +To achieve predictable performance, `Container` operations are expected to have the following worst-case complexities: | Operation | Complexity | |---|---| @@ -762,18 +809,20 @@ Types that wish to conform to protocol `Container` must, at minimum, complete th 3. Implement a `count` property with O(1) complexity. Often, this requires backing it by a stored property that gets incrementally updated every time the container changes its size. -2. Choose a `BorrowingIterator` type, and implement the related methods `makeBorrowingIterator(from:to:)` and `currentIndex(of:)`. The most straightforward choice is to use the standard `ContainerIterator` type; it provides a reasonable default for most container types. +4. Choose a `BorrowingIterator` type, and implement the related methods `makeBorrowingIterator(from:to:)` and `currentIndex(of:)`. The most straightforward choice is to use the standard `ContainerIterator` type; it provides a reasonable default for most container types. -3. Implement the `nextSpan(after:minCount:limitedBy:)` method. This is the core container primitive: the rest of container operations all come with default implementations based on this one. +5. Implement the `nextSpan(after:maxCount:limitedBy:)` method. This is the core container primitive: the rest of container operations all come with default implementations based on this one. -4. If the container is able to look up elements by value, provide custom implementations of `_custom[Last]IndexOfEquatableElement` so that standard algorithms can avoid falling back to linear searching. +6. If the container is able to look up elements by value, provide custom implementations of `_custom[Last]IndexOfEquatableElement` so that standard algorithms can avoid falling back to linear searching. -4. Implement custom implementations for additional container requirements, as needed. It is often possible to supply hand-optimized implementations that exploit the specific details of the container to provide measurably more efficient code than what the standard implementations achieve. Whether it is worth taking the extra effort to do this up front depends on the kind of container we're building, and its intended target use cases. +7. Implement custom implementations for additional container requirements, as needed. It is often possible to supply hand-optimized implementations that exploit the specific details of the container to provide measurably more efficient code than what the standard implementations achieve. Whether it is worth taking the extra effort to do this up front depends on the kind of container we're building, and its intended target use cases. Once a container type ships in source (or ABI) stable code base, its choices for `Index` and `BorrowingIterator` types get baked into its interface, and become tricky (or impossible) to change in future releases. However, it will still be possible to change the implementations of specific operations, for example, to replace the default implementation of an operation with a more efficient alternative. ### Bidirectional Containers +Note: This and the following sections are not yet complete. + ```swift protocol BidirectionalContainer: Container, ~Copyable, ~Escapable where Element: ~Copyable, Index: Comparable @@ -803,21 +852,21 @@ Note: Some `Container` requirements are redeclared as `override`s to help associ
Click to expand footnote -`@_nonoverride` creates separate witness table entries, allowing divergent implementations in conditional conformances. This enables conforming types to provide distinct implementations depending on whether the caller is generic over `Container` or `BidirectionalContainer`. - -(Unfortunately, neither `override` nor `@_nonoverride` allows callers that are generic over `Container` to automatically dispatch to a more constrained bidirectional implementation variant. Still, at least `@_nonoverride` enables more refined implementations to take effect when the caller is explicitly generic over `BidirectionalContainer`.) - -`@_nonoverride` should be used on requirements with new semantic constraints in refining protocols. - -Collection types usually do not come with conditional conformances to refining collection protocols (as the resulting behavior can be quite confusing), so the separate witness entries rarely if ever get exercised in practice. I don't expect things would be different with Container. - -FIXME: Consider avoiding using `@_nonoverride`, reducing witness sizes. +> `@_nonoverride` creates separate witness table entries, allowing divergent implementations in conditional conformances. This enables conforming types to provide distinct implementations depending on whether the caller is generic over `Container` or `BidirectionalContainer`. +> +> (Unfortunately, neither `override` nor `@_nonoverride` allows callers that are generic over `Container` to automatically dispatch to a more constrained bidirectional implementation variant. Still, at least `@_nonoverride` enables more refined implementations to take effect when the caller is explicitly generic over `BidirectionalContainer`.) +> +> `@_nonoverride` should be used on requirements with new semantic constraints in refining protocols. +> +> Collection types usually do not come with conditional conformances to refining collection protocols (as the resulting behavior can be quite confusing), so the separate witness entries rarely if ever get exercised in practice. I don't expect things would be different with `Container`. +> +> FIXME: Consider avoiding using `@_nonoverride`, reducing witness sizes.
### Random-Access Containers ``` -public protocol RandomAccessContainer +protocol RandomAccessContainer : BidirectionalContainer, ~Copyable, ~Escapable where Element: ~Copyable, Index: Comparable { override associatedtype Element: ~Copyable @@ -836,7 +885,7 @@ where Element: ~Copyable, Index: Comparable { ```
Click to expand footnote -`RandomAccessContainer` should technically redeclare single-steppers like `index(after:)` as `@_nonoverride`, as the protocol adds a semantic requirement for O(1) complexity. However, we emulate `RandomAccessCollection`'s (not necessarily well-justified) decision to leave these marked as overrides, forcing all types to have a single implementation that fulfills the (unique) requirement. (I haven't seen a case where these steppers would need to vary their implementation, while offsetting/distance calculations do sometimes want that, at least in theory. Not so much in practice though -- see e.g. `ZipSequence`'s lack of a conditional (random-access) collection conformance. +> `RandomAccessContainer` should technically redeclare single-steppers like `index(after:)` as `@_nonoverride`, as the protocol adds a semantic requirement for O(1) complexity. However, we emulate `RandomAccessCollection`'s (not necessarily well-justified) decision to leave these marked as overrides, forcing all types to have a single implementation that fulfills the (unique) requirement. (I haven't seen a case where these steppers would need to vary their implementation, while offsetting/distance calculations do sometimes want that, at least in theory. Not so much in practice though -- see e.g. `ZipSequence`'s lack of a conditional (random-access) collection conformance.)
## Mutable Containers @@ -844,7 +893,7 @@ where Element: ~Copyable, Index: Comparable { ### `protocol PermutableContainer` ```swift -public protocol PermutableContainer: Container, ~Copyable, ~Escapable +protocol PermutableContainer: Container, ~Copyable, ~Escapable where Element: ~Copyable { @_lifetime(self: copy self) @@ -855,7 +904,7 @@ where Element: ~Copyable ### `protocol MutableContainer` ```swift -public protocol MutableContainer: +protocol MutableContainer: PermutableContainer, ~Copyable, ~Escapable where Element: ~Copyable @@ -897,8 +946,8 @@ struct InputSpan: ~Copyable, ~Escapable { var endIndex: Index { get } var indices: Range { get } - subscript(_ index: Int) { borrow mutate } - subscript(unchecked index: Int) { borrow mutate } + subscript(_ index: Int) -> Element { borrow mutate } + subscript(unchecked index: Int) -> Element { borrow mutate } mutating func swapAt(_ i: Index, _ j: Index) mutating func swapAt(unchecked i: Index, unchecked j: Index) @@ -955,7 +1004,7 @@ struct InputSpan: ~Copyable, ~Escapable { /// alternative projections (or "views") over the same underlying /// representation, with each view conforming to `Container`, and sharing /// the same `Index`. (Like `String` does with its UTF-8, UTF-16, - /// Unicode ccalar and character views in the `Collection` world.) + /// Unicode scalar and character views in the `Collection` world.) /// This rounding operation enables clients to convert/normalize valid index /// values in one container view into valid indices in another, allowing them /// to (easily) decide whether two (potentially misaligned) index values @@ -974,7 +1023,7 @@ struct InputSpan: ~Copyable, ~Escapable { /// alternative projections (or "views") over the same underlying /// representation, with each view conforming to `Container`, and sharing /// the same `Index`. (Like `String` does with its UTF-8, UTF-16, - /// Unicode ccalar and character views in the `Collection` world.) + /// Unicode scalar and character views in the `Collection` world.) /// This rounding operation enables clients to convert/normalize valid index /// values in one container view into valid indices in another, allowing them /// to (easily) decide whether two (potentially misaligned) index values From 978e8a54a56edca4fe92a4a1a6a35214140c6ad0 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 21 Jul 2026 19:21:09 -0700 Subject: [PATCH 50/50] Additional fixes --- Documentation/Container-design.md | 28 +++++++++++++++++++++------- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/Documentation/Container-design.md b/Documentation/Container-design.md index 272949dd..a2e5acbe 100644 --- a/Documentation/Container-design.md +++ b/Documentation/Container-design.md @@ -167,9 +167,11 @@ The new `Iterable` protocol resolves this issue by introducing the idea of **bul For iterables that physically store their contents in memory, implementing iteration simply requires exposing spans over their preexisting piecewise contiguous storage chunks -- the bigger the chunks, the more efficient iteration becomes, even if `nextSpan`'s implementation isn't visible to the optimizer.
Click to expand footnote + > Of course, it was always possible to factor the implementation of iterators this way, by splitting `next()` into two layers, with judicious use of `@inlinable` or even `@inline(always)` attributes to encourage better performance while we're iterating within a storage chunk. However, this required a deep understanding of the underlying issues, and a large amount of willpower to structure the implementation the right way: this meant that only a select handful of types made an effort, and clients couldn't depend on it. > > `Iterable` forces all conforming types to organize their implementation around this idea, drastically improving clients' ability to reason about performance costs, even in generic contexts. +
Bulk iteration is not without drawbacks: it comes with a drastically more complicated interface, increasing the mental load of authoring conforming types, and of solving problems using the protocol. @@ -181,7 +183,9 @@ Operations for bulk iteration are full of subtle design complications that often However, consider a client that just wants to look at the first three elements to make a decision about what to do with the rest. Giving this caller four thousand items would put them in an awkward position: they would need to stash the leftovers somewhere, and then process them all before pulling on the iterator again. The spans that `nextSpan` returns are tied to an exclusive access of the iterator, which (currently at least) makes it impossible to actually store them alongside the iterator in any meaningful way: these clients would be drowned in a sea of elements they cannot process. By simplifying conforming implementations, we would significantly limit the usefulness of the protocol.
Click to expand footnote + > Throwing away the iterator and restarting it may seem like a possible workaround, but as `Iterable` types aren't required to produce the same items on repeated iterations, this cannot be a general solution. It only works on some iterable types, such as the containers we are introducing in this document. +

How bulk operations report/handle failures is a similarly subtle but important complication: operations that need to throw errors must be able to properly report partial success, to avoid data loss and to allow clients to identify precisely which element triggered the error. If the fifth element of an `Iterable` instance happens to trigger an error, it still needs to be possible for clients to reliably access the first four elements -- no matter what value they use for `maxCount`.

@@ -243,7 +247,9 @@ On the other hand, the ability to fail is far less important for _visitative_ co This greatly simplifies the container model, but it does mean that throwing algorithms like our hypothetical lazy `filter` can only produce `Iterable` types -- they cannot return containers, even if their input is one.
Click to expand footnote -Some readers may note a wrinkle in that we're assuming that accessing storage held in memory cannot possibly fail. While it is true that accessing memory can trigger faults (e.g., consider `mmap`ped regions), we lack the means to turn these faults into recoverable errors in Swift, and it seems unlikely it would be actually desirable to design container protocols around a hypothetical future language direction like that. The pragmatic choice is to assume that container types are stored in memory allocated using Swift's dedicated primitives, and access to them can never fail without crashing the entire process (or an isolated subsystem within it). + +> Some readers may note a problem with the assumption that accessing storage held in memory cannot possibly fail. While it is true that accessing memory can trigger faults (e.g., consider `mmap`ped regions), we lack the means to turn these faults into recoverable errors in Swift, and it seems unlikely it would be actually desirable to design container protocols around a hypothetical future language direction like that. The pragmatic choice is to assume that container types are stored in memory allocated using Swift's dedicated heap allocation primitives, and access to them can never fail without crashing the entire process (or at least bringing down an isolated subsystem within it). +
Let us now introduce the actual protocols, starting with `Container` itself. @@ -294,7 +300,7 @@ Unlike `Collection`, types conforming to `Container` are **required to produce t > > In the design we are proposing, humongous containers can choose to either only conform to `Iterable`, or to trigger a trap if they are ever asked for their count. Client code often invokes `count` so that it can preallocate storage for related work; obviously that is not going to end well if a container's count exceeds `Int.max`. (And in fact trapping early is much preferable to allowing the operation to inevitably fail midway through some vast computation.) > -> If we wanted to support them, one option would be to have `count` return an optional, or to push this property down into a separate `FiniteContainer` protocol. The overwhelming complexity of these options does not feel to be anywhere in proportion to the practical importance of such cases. Which is not to say they don't exist: tree-based ropes in particular (like `Foundation`'s `AttributedString`) can easily grow to humongous sizes, by simply concatenating a rope with itself a few dozen times. However, these are mostly just fun curiosities; such trees are rarely (if ever) practically useful. +> If we wanted to support such containers better, one option would be to have `count` return an optional; another would be to push the property down into a separate `FiniteContainer` protocol. The overwhelming complexity of these options does not feel to be anywhere in proportion to the practical importance of such cases. Which is not to say they don't exist: tree-based ropes in particular (like `Foundation`'s `AttributedString`) can easily grow to humongous sizes, by simply concatenating a rope with itself a few dozen times. However, these are mostly just curiosities; such trees are rarely (if ever) practically useful. @@ -343,7 +349,7 @@ Every one of the standard container types we've introduced so far (from `Span` t `Container` indices are required to be `Equatable`, but unlike `Collection`, they do not need to be `Comparable`. Linked lists are commonly used in systems programming, and this choice allows some linked list implementations to usefully conform to `Container`. The lack of an inherent ordering does complicate the default implementations of some index operations -- [see below](#distance-from-to). -In exchange, `Container` requires its indices to be `Hashable`. This does not put an undue burden on container implementations, but it does allow indices to be collected in sets or used as dictionary keys, enabling use cases such as dynamic filtering or out-of-band storage of data associated with container elements. (This fixes a small wrinkle with `Collection`, in that it does not require hashable indices.) +In exchange, `Container` requires its indices to be `Hashable`. This does not put an undue burden on container implementations, but it does allow indices to be collected in sets or used as dictionary keys, enabling use cases such as dynamic filtering or out-of-band storage of data associated with container elements. (Not guaranteeing hashable indices is an old `Collection`wrinkle.) To acknowledge our performance goals, **we require that `Container` indices must be compared for equality and hashed with constant complexity**. If a container's index does happen to be `Comparable`, then it is required that `<` has O(1) complexity as well. @@ -369,12 +375,18 @@ protocol Container: ... { As `Container` models a forward-only container, its `index(_:offsetBy:)` operation requires a nonnegative offset. (We'll shortly introduce a `BidirectionalContainer` refinement that will relax this constraint.) -As indices aren't required to be `Comparable`, the default implementation of `distance(from:to:)` cannot quickly validate that its `start` argument precedes `end`. To avoid having to run all the way to the end of the container to detect misuse, the algorithm instead iterates forward from both arguments, until it finds the other. This makes the default implementation twice as slow, but it allows it to correctly calculate negative distances. In the common case when `Index` is `Comparable`, we also provide a refined default algorithm that avoids this overhead. + + +As indices aren't required to be `Comparable`, the default implementation of `distance(from:to:)` cannot quickly validate that its `start` argument precedes `end`. To avoid having to run all the way to the end of the container to detect misuse, the algorithm instead iterates forward from both arguments, until it finds the other. This makes the default implementation twice as slow, but it allows it to correctly calculate negative distances. In the common case when `Index` is `Comparable`, we also provide a refined default algorithm that avoids this overhead. + + Notably, we replace `Collection`'s classic `index(_:offsetBy:limitedBy:)` requirement with an improved variant ([first introduced on `UniqueArray`][formIndex-offsetBy-limitedBy]) that reports the number of steps it was unable to take when reaching the limit. This avoids having to figure this out with a separate `distance(from:to:)` invocation, enabling more efficient use of this operation in situations that need this data; for example, it allows easy single-pass offsetting across concatenated containers. `Collection`'s original `index(_:offsetBy:limitedBy:)` operation is still available, as a standard algorithm based on the new requirement. + The `limit` argument here (and also elsewhere throughout the `Container` interface surface) means a **limiting index**, intended to cause the operation to stop if it encounters the limit during its execution. A limit of this sort only stops the operation if it needs to actively iterate over the corresponding position; a limit that the operation never needs to visit has no effect, whether it happens to address a position before or after the visited range. For example, if we're trying to iterate forward by `n` steps, a limit that's behind the start position has no effect. These specific semantics allow types that cannot provide comparable indices to still correctly conform to the protocol. (For example, linked lists usually cannot determine relative ordering between their indices without actively iterating through the list in linear time, as we've seen with `distance(from:to:)`.) + [formIndex-offsetBy-limitedBy]: https://github.com/swiftlang/swift/blob/swift-6.4.x-DEVELOPMENT-SNAPSHOT-2026-07-06-a/stdlib/public/core/UniqueArray/UniqueArray%2BContainer.swift#L267-L273 @@ -430,7 +442,7 @@ protocol Container: ... { ``` -The `maxCount` argument gives the caller control over the number of items it receives from the iterator, while `limit` allows the caller to request that the result never exceed a specific index. These parameters let callers avoid overrunning their target, which would significantly complicate container use. +The `maxCount` argument gives the caller control over the number of items it receives from the iterator, while `limit` allows the caller to request that the result never step over a specific index. These parameters let callers avoid overrunning their target, which would significantly complicate container use. Not all containers are contiguous, so `maxCount` only sets an upper bound. To read a specific number of items, the caller usually needs to invoke `nextSpan` in a loop: @@ -467,9 +479,9 @@ extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { } ``` -Containers often hold their contents in piecewise contiguous storage chunks. As this default implementation iterates over entire chunks, it can be considerably more efficient than stepping through indices one by one, like `Collection` does. As the elements are required to preexist in memory, materializing spans over them is relatively cheap -- `nextSpan` merely needs to locate storage, not populate its contents. Still, it is often possible to implement required operations more directly, and it is good practice to do so whenever it leads to measurable improvement. +Containers often hold their contents in piecewise contiguous storage chunks. As this default implementation iterates over entire chunks, it can be considerably more efficient than stepping through indices one by one, like `Collection` does. As the elements are required to preexist in memory, materializing spans over them is relatively cheap -- `nextSpan` merely needs to locate storage, not populate its contents. Still, it is often possible to implement `Container` operations more directly, and it is good practice to do so whenever it leads to measurable improvement. -The default implementation of `distance(from:to:)` poses an interesting problem: `Container` only allows forward iteration, so to measure the distance between two indices, we have to start iterating from the one addressing the earlier one. But container does not require its `Index` to be `Comparable`, so that's not something we can easily check. We have three options to resolve this: +The default implementation of `distance(from:to:)` poses an interesting problem: `Container` only allows forward iteration, so to measure the distance between two indices, we have to start iterating from the one addressing the earlier one. But `Container` does not require its `Index` to be `Comparable`, so we cannot easily decide which index goes first! We have three options to resolve this: 1. Only provide a default `distance` algorithm for containers with comparable indices. @@ -885,7 +897,9 @@ where Element: ~Copyable, Index: Comparable { ```
Click to expand footnote + > `RandomAccessContainer` should technically redeclare single-steppers like `index(after:)` as `@_nonoverride`, as the protocol adds a semantic requirement for O(1) complexity. However, we emulate `RandomAccessCollection`'s (not necessarily well-justified) decision to leave these marked as overrides, forcing all types to have a single implementation that fulfills the (unique) requirement. (I haven't seen a case where these steppers would need to vary their implementation, while offsetting/distance calculations do sometimes want that, at least in theory. Not so much in practice though -- see e.g. `ZipSequence`'s lack of a conditional (random-access) collection conformance.) +
## Mutable Containers