From 030f751515d077637313c3f0baf1be3159d0198f Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 3 Feb 2026 14:06:03 -0800 Subject: [PATCH] [BasicContainers] RigidArray, UniqueArray: Fill out missing indexing APIs --- Sources/BasicContainers/CMakeLists.txt | 1 + .../RigidArray/RigidArray+Container.swift | 122 +++++++++++ .../UniqueArray/UniqueArray+Container.swift | 198 ++++++++++++++++++ .../Protocols/Container.swift | 57 ++++- .../RigidArrayTests.swift | 4 +- Xcode/Collections.xcodeproj/project.pbxproj | 4 + 6 files changed, 382 insertions(+), 4 deletions(-) create mode 100644 Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift diff --git a/Sources/BasicContainers/CMakeLists.txt b/Sources/BasicContainers/CMakeLists.txt index 4cd43f19..3b5f438c 100644 --- a/Sources/BasicContainers/CMakeLists.txt +++ b/Sources/BasicContainers/CMakeLists.txt @@ -33,6 +33,7 @@ target_sources(${module_name} PRIVATE "RigidArray/RigidArray+Replacements.swift" "UniqueArray/UniqueArray.swift" "UniqueArray/UniqueArray+Append.swift" + "UniqueArray/UniqueArray+Container.swift" "UniqueArray/UniqueArray+Experimental.swift" "UniqueArray/UniqueArray+Initializers.swift" "UniqueArray/UniqueArray+Insertions.swift" diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Container.swift b/Sources/BasicContainers/RigidArray/RigidArray+Container.swift index 4391f2fc..d50057cf 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Container.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Container.swift @@ -42,20 +42,122 @@ extension RigidArray: Container where Element: ~Copyable { @available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { + /// Returns the position immediately after the given index. + /// + /// - Note: To improve performance, this method does not validate that the + /// index is valid before incrementing it. Index validation is + /// deferred until the resulting index is used to access an element. + /// This optimization may be removed in future versions; do not rely on it. + /// + /// - Parameter index: A valid index of the array. `i` must be less + /// than `endIndex`. + /// - Returns: The index immediately following `i`. + /// - Complexity: O(1) @_alwaysEmitIntoClient @inline(__always) public func index(after index: Int) -> Int { index + 1 } + /// Returns the position immediately before the given index. + /// + /// - Note: To improve performance, this method does not validate that the + /// index is valid before decrementing it. Index validation is + /// deferred until the resulting index is used to access an element. + /// This optimization may be removed in future versions; do not rely on it. + /// + /// - Parameter index: A valid index of the array. `i` must be greater + /// than `startIndex`. + /// - Returns: The index immediately preceding `i`. + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @inline(__always) + public func index(before index: Int) -> Int { index - 1 } + + /// Replaces the given index with its successor. + /// + /// - Note: To improve performance, this method does not validate that the + /// given index is valid before incrementing it. Index validation is + /// deferred until the resulting index is used to access an element. + /// This optimization may be removed in future versions; do not rely on it. + /// + /// - Parameter index: A valid index of the array. `i` must be less + /// than `endIndex`. + /// - Complexity: O(1) @_alwaysEmitIntoClient @inline(__always) public func formIndex(after index: inout Int) { index += 1 } + /// Returns an index that is the specified distance from the given index. + /// + /// The value passed as `n` must not offset `index` beyond the bounds of the + /// array. + /// + /// - Note: To improve performance, this method does not validate that the + /// given index is valid before offseting it. Index validation is + /// deferred until the resulting index is used to access an element. + /// This optimization may be removed in future versions; do not rely on it. + /// + /// - Parameter index: A valid index of the array. + /// - Parameter n: The distance by which to offset `index`. + /// - Returns: An index offset by distance from `index`. If `n` is positive, + /// 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: O(1) @_alwaysEmitIntoClient @inline(__always) public func index(_ index: Int, offsetBy n: Int) -> Int { index + n } + /// Returns the distance between two indices. + /// + /// - Note: To improve performance, this method does not validate that the + /// given index is valid before offseting it. Index validation is + /// deferred until the resulting index is used to access an element. + /// This optimization may be removed in future versions; do not rely on it. + /// + /// - Parameter start: A valid index of the collection. + /// - 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: O(1) + @_alwaysEmitIntoClient + @inline(__always) + public func distance(from start: Index, to end: Index) -> Int { + end - start + } + + /// Offsets the given index by the specified distance, but no further than + /// the given limiting index. + /// + /// If the operation was able to offset `index` by exactly the requested + /// number of steps without hitting `limit`, then on return `n` is set to `0`, + /// and `index` is set to the adjusted index. + /// + /// If the operation hits the limit before it can take the requested number + /// of steps, then on return `index` is set to `limit`, and `n` is set + /// to the number of steps that couldn't be taken. + /// + /// The value passed as `n` must not offset `index` beyond the bounds of the + /// container, unless the index passed as `limit` prevents offsetting beyond + /// those bounds. + /// + /// - Note: To improve performance, this method does not validate that the + /// given index is valid before offseting it. Index validation is + /// deferred until the resulting index is used to access an element. + /// This optimization may be removed in future versions; do not rely on it. + /// + /// - Parameter index: A valid index of the array. On return, `index` is + /// set to `limit` if + /// - Parameter n: The distance to offset `index`. + /// 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( _ index: inout Index, offsetBy n: inout Int, limitedBy limit: Index @@ -63,6 +165,26 @@ extension RigidArray where Element: ~Copyable { index._advance(by: &n, limitedBy: limit) } + /// 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. 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` + /// } + /// + /// - Parameter index: A valid index in the array, 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. + /// - Complexity: O(1) @inlinable @_lifetime(borrow self) public func nextSpan( diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift new file mode 100644 index 00000000..7208516d --- /dev/null +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift @@ -0,0 +1,198 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +@available(SwiftStdlib 5.0, *) +extension RigidArray: BorrowingSequence where Element: ~Copyable { + public typealias BorrowingIterator = Span.BorrowingIterator + + @_alwaysEmitIntoClient + @inline(__always) + public var estimatedCount: EstimatedCount { + self._storage.estimatedCount + } + + @_alwaysEmitIntoClient + @inline(__always) + public func makeBorrowingIterator() -> BorrowingIterator { + self._storage.makeBorrowingIterator() + } +} +#endif + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +@available(SwiftStdlib 5.0, *) +extension UniqueArray: Container where Element: ~Copyable { +} +#endif + +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + /// Returns the position immediately after the given index. + /// + /// - Note: To improve performance, this method does not validate that the + /// index is valid before incrementing it. Index validation is + /// deferred until the resulting index is used to access an element. + /// This optimization may be removed in future versions; do not rely on it. + /// + /// - Parameter index: A valid index of the array. `i` must be less + /// than `endIndex`. + /// - Returns: The index immediately following `i`. + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @inline(__always) + public func index(after index: Int) -> Int { index + 1 } + + /// Returns the position immediately before the given index. + /// + /// - Note: To improve performance, this method does not validate that the + /// index is valid before decrementing it. Index validation is + /// deferred until the resulting index is used to access an element. + /// This optimization may be removed in future versions; do not rely on it. + /// + /// - Parameter index: A valid index of the array. `i` must be greater + /// than `startIndex`. + /// - Returns: The index immediately preceding `i`. + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @inline(__always) + public func index(before index: Int) -> Int { index - 1 } + + /// Replaces the given index with its successor. + /// + /// - Note: To improve performance, this method does not validate that the + /// given index is valid before incrementing it. Index validation is + /// deferred until the resulting index is used to access an element. + /// This optimization may be removed in future versions; do not rely on it. + /// + /// - Parameter index: A valid index of the array. `i` must be less + /// than `endIndex`. + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @inline(__always) + public func formIndex(after index: inout Int) { index += 1 } + + /// Returns an index that is the specified distance from the given index. + /// + /// The value passed as `n` must not offset `index` beyond the bounds of the + /// array. + /// + /// - Note: To improve performance, this method does not validate that the + /// given index is valid before offseting it. Index validation is + /// deferred until the resulting index is used to access an element. + /// This optimization may be removed in future versions; do not rely on it. + /// + /// - Parameter index: A valid index of the array. + /// - Parameter n: The distance by which to offset `index`. + /// - Returns: An index offset by distance from `index`. If `n` is positive, + /// 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: O(1) + @_alwaysEmitIntoClient + @inline(__always) + public func index(_ index: Int, offsetBy n: Int) -> Int { + index + n + } + + /// Returns the distance between two indices. + /// + /// - Note: To improve performance, this method does not validate that the + /// given index is valid before offseting it. Index validation is + /// deferred until the resulting index is used to access an element. + /// This optimization may be removed in future versions; do not rely on it. + /// + /// - Parameter start: A valid index of the collection. + /// - 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: O(1) + @_alwaysEmitIntoClient + @inline(__always) + public func distance(from start: Index, to end: Index) -> Int { + end - start + } + + /// Offsets the given index by the specified distance, but no further than + /// the given limiting index. + /// + /// If the operation was able to offset `index` by exactly the requested + /// number of steps without hitting `limit`, then on return `n` is set to `0`, + /// and `index` is set to the adjusted index. + /// + /// If the operation hits the limit before it can take the requested number + /// of steps, then on return `index` is set to `limit`, and `n` is set + /// to the number of steps that couldn't be taken. + /// + /// The value passed as `n` must not offset `index` beyond the bounds of the + /// container, unless the index passed as `limit` prevents offsetting beyond + /// those bounds. + /// + /// - Note: To improve performance, this method does not validate that the + /// given index is valid before offseting it. Index validation is + /// deferred until the resulting index is used to access an element. + /// This optimization may be removed in future versions; do not rely on it. + /// + /// - Parameter index: A valid index of the array. On return, `index` is + /// set to `limit` if + /// - Parameter n: The distance to offset `index`. + /// 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( + _ index: inout Index, offsetBy n: inout Int, limitedBy limit: Index + ) { + _storage.formIndex(&index, offsetBy: &n, limitedBy: limit) + } + + /// 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. 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` + /// } + /// + /// - Parameter index: A valid index in the array, 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. + /// - Complexity: O(1) + @inlinable + @_lifetime(borrow self) + public func nextSpan( + after index: inout Int, maximumCount: Int + ) -> Span { + _storage.nextSpan(after: &index, maximumCount: maximumCount) + } +} + +#endif diff --git a/Sources/ContainersPreview/Protocols/Container.swift b/Sources/ContainersPreview/Protocols/Container.swift index ff635855..c33df66e 100644 --- a/Sources/ContainersPreview/Protocols/Container.swift +++ b/Sources/ContainersPreview/Protocols/Container.swift @@ -19,12 +19,65 @@ public protocol Container: BorrowingSequence, ~Copyable, ~Escapable { var startIndex: Index { get } var endIndex: Index { get } + + /// Returns the position immediately after the given index. + /// + /// - Parameter index: A valid index of the container. `i` must be less + /// than `endIndex`. + /// - Returns: The index immediately following `i`. 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`. func formIndex(after index: inout Index) + + /// Returns an index that is the specified distance from the given index. + /// + /// The value passed as `n` must not offset `index` beyond the bounds of the + /// container. + /// + /// - Parameter index: A valid index of the container. + /// - Parameter n: The distance by which to offset `index`. + /// - Returns: An index offset by distance from `index`. If `n` is positive, + /// 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:)`. func index(_ index: Index, offsetBy n: Int) -> Index + + /// Offsets the given index by the specified distance, but no further than + /// the given limiting index. + /// + /// If the operation was able to offset `index` by exactly the requested + /// number of steps without hitting `limit`, then on return `n` is set to `0`, + /// and `index` is set to the adjusted index. + /// + /// If the operation hits the limit before it can take the requested number + /// of steps, then on return `index` is set to `limit`, and `n` is set + /// to the number of steps that couldn't be taken. + /// + /// The value passed as `n` must not offset `index` beyond the bounds of the + /// container, unless the index passed as `limit` prevents offsetting beyond + /// those bounds. + /// + /// - Parameter index: A valid index of the container. + /// - Parameter n: The distance to offset `index`. `n` must not be negative + /// unless the container conforms to the `BidirectionalContainer` protocol. + /// - Parameter limit: A valid index of the container 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. 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. + /// - 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`. func distance(from start: Index, to end: Index) -> Int /// Return a span over the container's storage that begins with the element at the given index, @@ -41,11 +94,11 @@ public protocol Container: BorrowingSequence, ~Copyable, ~Escapable { /// // Process items in `span` /// } /// - /// Note: The spans returned by this method are not guaranteed to be disjunct. Some containers + /// - 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 + /// - 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 diff --git a/Tests/BasicContainersTests/RigidArrayTests.swift b/Tests/BasicContainersTests/RigidArrayTests.swift index a09c6b33..ee18f8ef 100644 --- a/Tests/BasicContainersTests/RigidArrayTests.swift +++ b/Tests/BasicContainersTests/RigidArrayTests.swift @@ -466,7 +466,7 @@ class RigidArrayTests: CollectionTestCase { withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in withLifetimeTracking { tracker in let a = tracker.rigidArray(layout: layout) - let b = a.copy() + let b = a.clone() expectEqual(b.count, layout.count) expectEqual(b.capacity, layout.count) expectEqual(tracker.instances, layout.count) @@ -492,7 +492,7 @@ class RigidArrayTests: CollectionTestCase { ) { newCapacity in withLifetimeTracking { tracker in let a = tracker.rigidArray(layout: layout) - let b = a.copy(capacity: newCapacity) + let b = a.clone(capacity: newCapacity) expectEqual(b.count, layout.count) expectEqual(b.capacity, newCapacity) expectEqual(tracker.instances, layout.count) diff --git a/Xcode/Collections.xcodeproj/project.pbxproj b/Xcode/Collections.xcodeproj/project.pbxproj index b0d55af6..17064428 100644 --- a/Xcode/Collections.xcodeproj/project.pbxproj +++ b/Xcode/Collections.xcodeproj/project.pbxproj @@ -97,6 +97,7 @@ 7DA23F522F329A2300E4C03A /* UniqueArray+Experimental.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DA23F402F329A2300E4C03A /* UniqueArray+Experimental.swift */; }; 7DA23F532F329A2300E4C03A /* UniqueArray+Insertions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DA23F422F329A2300E4C03A /* UniqueArray+Insertions.swift */; }; 7DA23F542F329A2300E4C03A /* RigidArray.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DA23F352F329A2300E4C03A /* RigidArray.swift */; }; + 7DA23F562F329E9000E4C03A /* UniqueArray+Container.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DA23F552F329E8A00E4C03A /* UniqueArray+Container.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 */; }; @@ -588,6 +589,7 @@ 7DA23F422F329A2300E4C03A /* UniqueArray+Insertions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueArray+Insertions.swift"; sourceTree = ""; }; 7DA23F432F329A2300E4C03A /* UniqueArray+Removals.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueArray+Removals.swift"; sourceTree = ""; }; 7DA23F442F329A2300E4C03A /* UniqueArray+Replacements.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueArray+Replacements.swift"; sourceTree = ""; }; + 7DA23F552F329E8A00E4C03A /* UniqueArray+Container.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueArray+Container.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 = ""; }; @@ -1156,6 +1158,7 @@ children = ( 7DA23F3E2F329A2300E4C03A /* UniqueArray.swift */, 7DA23F3F2F329A2300E4C03A /* UniqueArray+Append.swift */, + 7DA23F552F329E8A00E4C03A /* UniqueArray+Container.swift */, 7DA23F402F329A2300E4C03A /* UniqueArray+Experimental.swift */, 7DA23F412F329A2300E4C03A /* UniqueArray+Initializers.swift */, 7DA23F422F329A2300E4C03A /* UniqueArray+Insertions.swift */, @@ -2302,6 +2305,7 @@ 7DE9215329CA70F4004483EB /* _HashNode+Invariants.swift in Sources */, 7DE9209629CA70F4004483EB /* Rope+Builder.swift in Sources */, 7DE9215129CA70F4004483EB /* _HashNode+Subtree Modify.swift in Sources */, + 7DA23F562F329E9000E4C03A /* UniqueArray+Container.swift in Sources */, 7DE9204729CA70F3004483EB /* _HashTable+Testing.swift in Sources */, 7DE920E929CA70F4004483EB /* BitArray+Invariants.swift in Sources */, 7DE9215429CA70F4004483EB /* _HashNode+UnsafeHandle.swift in Sources */,