From 377d2a55a8b9506d56d4eedefe26565240b208f0 Mon Sep 17 00:00:00 2001 From: Alejandro Alonso Date: Wed, 24 Sep 2025 23:21:02 -0700 Subject: [PATCH 01/16] Fix landing page of collections documentation --- README.md | 6 ++++ .../Collections.docc/Collections.md | 31 +++++-------------- 2 files changed, 13 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index 31d276ee..323df766 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,10 @@ Read more about the package, and the intent behind it, in the [announcement on s The package currently provides the following implementations: +- [`RigidArray`][RigidArray], a fixed capacity and no implicit resizing dynamic non-copyable array capable of storing non-copyable elements. + +- [`UniqueArray`][UniqueArray], an implicitly resizable dynamic non-copyable array capable of storing non-copyable elements. + - [`BitSet`][BitSet] and [`BitArray`][BitArray], dynamic bit collections. - [`Deque`][Deque], a double-ended queue backed by a ring buffer. Deques are range-replaceable, mutable, random-access collections. @@ -22,6 +26,8 @@ The package currently provides the following implementations: - [`TreeSet`][TreeSet] and [`TreeDictionary`][TreeDictionary], persistent hashed collections implementing Compressed Hash-Array Mapped Prefix Trees (CHAMP). These work similar to the standard `Set` and `Dictionary`, but they excel at use cases that mutate shared copies, offering dramatic memory savings and radical time improvements. +[RigidArray]: https://swiftpackageindex.com/apple/swift-collections/documentation/basiccontainers/rigidarray +[UniqueArray]: https://swiftpackageindex.com/apple/swift-collections/documentation/basiccontainers/uniquearray [BitSet]: https://swiftpackageindex.com/apple/swift-collections/documentation/bitcollections/bitset [BitArray]: https://swiftpackageindex.com/apple/swift-collections/documentation/bitcollections/bitarray [Deque]: https://swiftpackageindex.com/apple/swift-collections/documentation/dequemodule/deque diff --git a/Sources/Collections/Collections.docc/Collections.md b/Sources/Collections/Collections.docc/Collections.md index 733249b7..ef2231c0 100644 --- a/Sources/Collections/Collections.docc/Collections.md +++ b/Sources/Collections/Collections.docc/Collections.md @@ -11,28 +11,11 @@ - [`Swift Collections` on GitHub](https://github.com/apple/swift-collections/) - [`Swift Collections` on the Swift Forums](https://forums.swift.org/c/related-projects/collections/72) +### Modules -## Topics - -### Bit Collections - -- ``BitSet`` -- ``BitArray`` - -### Deque Module - -- ``Deque`` - -### Heap Module - -- ``Heap`` - -### Ordered Collections - -- ``OrderedSet`` -- ``OrderedDictionary`` - -### Persistent Hashed Collections - -- ``TreeSet`` -- ``TreeDictionary`` +- [Basic Containers](./basiccontainers) - [`RigidArray`](./basiccontainers/rigidarray), a fixed capacity and no implicit resizing dynamic non-copyable array capable of storing non-copyable elements. [`UniqueArray`](./basiccontainers/uniquearray), an implicitly resizable dynamic non-copyable array capable of storing non-copyable elements. +- [Bit Collections](./bitcollections) - [`BitSet`](./bitcollections/bitset) and [`BitArray`](./bitcollections/bitarray), dynamic bit collections. +- [Deque Module](./dequemodule) - [`Deque`](./dequemodule/deque), a double-ended queue backed by a ring buffer. Deques are range-replaceable, mutable, random-access collections. +- [Heap Module](./heapmodule) - [`Heap`](./heapmodule/heap), a min-max heap backed by an array, suitable for use as a priority queue. +- [Ordered Collections](./orderedcollections) - [`OrderedSet`](./orderedcollections/orderedset), a variant of the standard `Set` where the order of items is well-defined and items can be arbitrarily reordered. Uses a `ContiguousArray` as its backing store, augmented by a separate hash table of bit packed offsets into it. [`OrderedDictionary`](./orderedcollections/ordereddictionary), an ordered variant of the standard `Dictionary`, providing similar benefits. +- [Hash Tree Collections](./hashtreecollections) - [`TreeSet`](./hashtreecollections/treeset) and [`TreeDictionary`](./hashtreecollections/treedictionary), persistent hashed collections implementing Compressed Hash-Array Mapped Prefix Trees (CHAMP). These work similar to the standard `Set` and `Dictionary`, but they excel at use cases that mutate shared copies, offering dramatic memory savings and radical time improvements. From 174efda735d691aa6e591b8c4c06020149a8aeb2 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 26 Sep 2025 17:18:50 -0700 Subject: [PATCH 02/16] RigidArray/UniqueArray: Final API cleanup pass - Set availability to match Span availability - Split implementation into multiple source files - Add OutputSpan-based primitives that can be the bases of all append/insertion/replaceSubrange variants - Add the ability to consume a subrange of items using an InputSpan - Add bulk copying operations generic over the new Container protocol --- Sources/BasicContainers/CMakeLists.txt | 14 +- .../BasicContainers/RigidArray+Append.swift | 312 ++++++ .../RigidArray+Experimental.swift | 378 +------ .../RigidArray+Initializers.swift | 108 ++ .../RigidArray+Insertions.swift | 415 ++++++++ .../BasicContainers/RigidArray+Removals.swift | 187 ++++ .../RigidArray+Replacements.swift | 464 +++++++++ Sources/BasicContainers/RigidArray.swift | 970 +----------------- .../BasicContainers/UniqueArray+Append.swift | 265 +++++ .../UniqueArray+Experimental.swift | 279 +---- .../UniqueArray+Initializers.swift | 91 ++ .../UniqueArray+Insertions.swift | 339 ++++++ .../UniqueArray+Removals.swift | 149 +++ .../UniqueArray+Replacements.swift | 399 +++++++ Sources/BasicContainers/UniqueArray.swift | 840 +-------------- ...nsafeMutableBufferPointer+Extras.swift.gyb | 41 +- .../UnsafeMutableBufferPointer+Extras.swift | 82 +- .../RigidArrayTests.swift | 14 +- .../UniqueArrayTests.swift | 12 +- 19 files changed, 2869 insertions(+), 2490 deletions(-) create mode 100644 Sources/BasicContainers/RigidArray+Append.swift create mode 100644 Sources/BasicContainers/RigidArray+Initializers.swift create mode 100644 Sources/BasicContainers/RigidArray+Insertions.swift create mode 100644 Sources/BasicContainers/RigidArray+Removals.swift create mode 100644 Sources/BasicContainers/RigidArray+Replacements.swift create mode 100644 Sources/BasicContainers/UniqueArray+Append.swift create mode 100644 Sources/BasicContainers/UniqueArray+Initializers.swift create mode 100644 Sources/BasicContainers/UniqueArray+Insertions.swift create mode 100644 Sources/BasicContainers/UniqueArray+Removals.swift create mode 100644 Sources/BasicContainers/UniqueArray+Replacements.swift diff --git a/Sources/BasicContainers/CMakeLists.txt b/Sources/BasicContainers/CMakeLists.txt index d37397ef..94586ef4 100644 --- a/Sources/BasicContainers/CMakeLists.txt +++ b/Sources/BasicContainers/CMakeLists.txt @@ -23,8 +23,18 @@ else() endif() target_sources(${module_name} PRIVATE - "UniqueArray.swift" - "UniqueArray+Experimental.swift" "RigidArray.swift" + "RigidArray+Append.swift" "RigidArray+Experimental.swift" + "RigidArray+Initializers.swift" + "RigidArray+Insertions.swift" + "RigidArray+Removals.swift" + "RigidArray+Replacements.swift" + "UniqueArray.swift" + "UniqueArray+Append.swift" + "UniqueArray+Experimental.swift" + "UniqueArray+Initializers.swift" + "UniqueArray+Insertions.swift" + "UniqueArray+Removals.swift" + "UniqueArray+Replacements.swift" ) diff --git a/Sources/BasicContainers/RigidArray+Append.swift b/Sources/BasicContainers/RigidArray+Append.swift new file mode 100644 index 00000000..ded035f4 --- /dev/null +++ b/Sources/BasicContainers/RigidArray+Append.swift @@ -0,0 +1,312 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + /// Adds an element to the end of the array. + /// + /// If the array does not have sufficient capacity to hold any more elements, + /// then this triggers a runtime error. + /// + /// - Parameter item: The element to append to the collection. + /// + /// - Complexity: O(1) + @inlinable + public mutating func append(_ item: consuming Element) { + precondition(!isFull, "RigidArray capacity overflow") + unsafe _storage.initializeElement(at: _count, to: item) + _count &+= 1 + } + + /// Adds an element to the end of the array, if possible. + /// + /// If the array does not have sufficient capacity to hold any more elements, + /// then this returns the given item without appending it; otherwise it + /// returns nil. + /// + /// - Parameter item: The element to append to the collection. + /// - Returns: `item` if the array is full; otherwise nil. + /// + /// - Complexity: O(1) + @inlinable + public mutating func pushLast(_ item: consuming Element) -> Element? { + // FIXME: Remove this in favor of a standard algorithm. + if isFull { return item } + append(item) + return nil + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + @_alwaysEmitIntoClient + public mutating func append( + count: Int, + initializingWith body: (inout OutputSpan) throws(E) -> Result + ) throws(E) -> Result { + // FIXME: This is extremely similar to `edit()`, except it provides a narrower span. + precondition(freeCapacity >= count, "RigidArray capacity overflow") + let buffer = _freeSpace._extracting(first: count) + var span = OutputSpan(buffer: buffer, initializedCount: 0) + defer { + _count &+= span.finalize(for: buffer) + span = OutputSpan() + } + return try body(&span) + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + /// Moves the elements of a buffer to the end of this array, leaving the + /// buffer uninitialized. + /// + /// If the array does not have sufficient capacity to hold all items in the + /// buffer, then this triggers a runtime error. + /// + /// - Parameters + /// - items: A fully initialized buffer whose contents to move into + /// the array. + /// + /// - Complexity: O(`items.count`) + @_alwaysEmitIntoClient + public mutating func append( + moving items: UnsafeMutableBufferPointer + ) { + precondition(items.count <= freeCapacity, "RigidArray capacity overflow") + guard items.count > 0 else { return } + let c = unsafe _freeSpace._moveInitializePrefix(from: items) + assert(c == items.count) + _count &+= items.count + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @_alwaysEmitIntoClient + public mutating func append( + moving items: inout InputSpan + ) { + items.withUnsafeMutableBufferPointer { buffer, count in + let source = buffer._extracting(last: count) + unsafe self.append(moving: source) + count = 0 + } + } +#endif + + @_alwaysEmitIntoClient + public mutating func append( + moving items: inout OutputSpan + ) { + items.withUnsafeMutableBufferPointer { buffer, count in + let source = buffer._extracting(first: count) + unsafe self.append(moving: source) + count = 0 + } + } + + /// 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. + /// + /// 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: An array whose items to move to the end of this array. + /// + /// - Complexity: O(`items.count`) + @_alwaysEmitIntoClient + public mutating func append( + moving items: inout RigidArray + ) { + // FIXME: Remove this in favor of a generic algorithm over range-replaceable containers + unsafe items._unsafeEdit { buffer, count in + let source = buffer._extracting(first: count) + unsafe self.append(moving: source) + count = 0 + } + } +} + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + /// 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 fully initialized buffer whose contents to move into + /// the 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 { + /// Copies the elements of a buffer to the end of this array. + /// + /// If the array does not have sufficient capacity to hold all items in the + /// buffer, then this triggers a runtime error. + /// + /// - Parameters + /// - newElements: A fully initialized buffer whose contents to copy into + /// the array. + /// + /// - Complexity: O(`newElements.count`) + @_alwaysEmitIntoClient + public mutating func append( + copying newElements: UnsafeBufferPointer + ) { + precondition( + newElements.count <= freeCapacity, + "RigidArray capacity overflow") + guard newElements.count > 0 else { return } + unsafe _freeSpace.baseAddress.unsafelyUnwrapped.initialize( + from: newElements.baseAddress.unsafelyUnwrapped, count: newElements.count) + _count &+= newElements.count + } + + /// Copies the elements of a buffer to the end of this array. + /// + /// If the array does not have sufficient capacity to hold all items in the + /// buffer, then this triggers a runtime error. + /// + /// - Parameters + /// - newElements: A fully initialized buffer whose contents to copy into + /// the array. + /// + /// - Complexity: O(`newElements.count`) + @_alwaysEmitIntoClient + public mutating func append( + copying items: UnsafeMutableBufferPointer + ) { + unsafe self.append(copying: UnsafeBufferPointer(items)) + } + + /// Copies the elements of a span to the end of this array. + /// + /// If the array does not have sufficient capacity to hold all items in the + /// span, then this triggers a runtime error. + /// + /// - Parameters + /// - newElements: A span whose contents to copy into the array. + /// + /// - Complexity: O(`newElements.count`) + @_alwaysEmitIntoClient + public mutating func append(copying items: Span) { + unsafe items.withUnsafeBufferPointer { source in + unsafe self.append(copying: source) + } + } + + @_alwaysEmitIntoClient + @inline(__always) + internal mutating func _append>( + prefixOf items: S + ) -> S.Iterator { + let (it, c) = unsafe items._copyContents(initializing: _freeSpace) + _count += c + return it + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @inlinable + internal mutating func _append< + Source: Container & ~Copyable & ~Escapable + >( + copyingContainer newElements: borrowing Source + ) { + let target = _freeSpace + _count += newElements._copyContents(intoPrefixOf: target) + } +#endif + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Copies the elements of a container to the end of this array. + /// + /// If the array does not have sufficient capacity to hold all items in the + /// source iterable, then this triggers a runtime error. + /// + /// - Parameters + /// - newElements: A container whose contents to copy into the array. + /// + /// - Complexity: O(`newElements.count`) + @_alwaysEmitIntoClient + @inline(__always) + public mutating func append< + Source: Container & ~Copyable & ~Escapable + >( + copying newElements: borrowing Source + ) { + _append(copyingContainer: newElements) + } +#endif + + /// Copies the elements of a sequence to the end of this array. + /// + /// If the array does not have sufficient capacity to hold all items in the + /// sequence, then this triggers a runtime error. + /// + /// - Parameters + /// - newElements: The new elements to copy into the array. + /// + /// - Complexity: O(*m*), where *m* is the length of `newElements`. + @_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 } + + var it = self._append(prefixOf: newElements) + precondition(it.next() == nil, "RigidArray capacity overflow") + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Copies the elements of a container to the end of this array. + /// + /// If the array does not have sufficient capacity to hold all items in the + /// source iterable, then this triggers a runtime error. + /// + /// - Parameters + /// - newElements: The new elements to copy into the array. + /// + /// - Complexity: O(*m*), where *m* is the length of `newElements`. + @_alwaysEmitIntoClient + @inline(__always) + public mutating func append< + Source: Container & Sequence + >(copying newElements: Source) { + _append(copyingContainer: newElements) + } +#endif +} +#endif diff --git a/Sources/BasicContainers/RigidArray+Experimental.swift b/Sources/BasicContainers/RigidArray+Experimental.swift index 8bcf6482..214e0b44 100644 --- a/Sources/BasicContainers/RigidArray+Experimental.swift +++ b/Sources/BasicContainers/RigidArray+Experimental.swift @@ -14,48 +14,10 @@ import InternalCollectionsUtilities import ContainersPreview #endif -#if compiler(>=6.2) -#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +#if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW -extension RigidArray /*where Element: Copyable*/ { -#if FIXME - @_alwaysEmitIntoClient - @inline(__always) - public init & Sequence>( - capacity: Int, - copying contents: C - ) { - self.init(capacity: capacity) - self.append(copying: contents) - } -#endif - -#if FIXME - @_alwaysEmitIntoClient - @inline(__always) - public init & ~Copyable & ~Escapable>( - capacity: Int? = nil, - copying contents: borrowing C - ) { - self.init(capacity: capacity ?? contents.count) - self.append(copying: contents) - } -#endif - -#if FIXME - @_alwaysEmitIntoClient - @inline(__always) - public init & Collection>( - capacity: Int? = nil, - copying contents: C - ) { - self.init(capacity: capacity ?? contents.count) - self.append(copying: contents) - } -#endif -} - -#if FIXME +#if false // FIXME +@available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { @inlinable @_lifetime(borrow self) @@ -69,18 +31,14 @@ extension RigidArray where Element: ~Copyable { } #endif -#if FIXME -extension RigidArray: RandomAccessContainer where Element: ~Copyable { -} -#endif - -#if FIXME +#if false // FIXME +@available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { @inlinable @_lifetime(&self) - public mutating func mutateElement(at index: Int) -> Inout { + public mutating func mutateElement(at index: Int) -> Mut { precondition(index >= 0 && index < _count) - return unsafe Inout( + return unsafe Mut( unsafeAddress: _storage.baseAddress.unsafelyUnwrapped.advanced(by: index), mutating: &self ) @@ -88,13 +46,9 @@ extension RigidArray where Element: ~Copyable { } #endif -#if FIXME -extension RigidArray: MutableContainer where Element: ~Copyable { -} -#endif - +#if false // FIXME +@available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { - @available(SwiftStdlib 5.0, *) @inlinable public mutating func reallocate( capacity: Int, @@ -118,8 +72,10 @@ extension RigidArray where Element: ~Copyable { return try body(&source, &target) } } +#endif -#if FIXME +#if false // FIXME +@available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { /// Removes all the elements that satisfy the given predicate. /// @@ -131,7 +87,6 @@ extension RigidArray where Element: ~Copyable { /// whether the element should be removed from the array. /// /// - Complexity: O(`count`) - @available(SwiftStdlib 6.2, *) @_alwaysEmitIntoClient public mutating func removeAll( where shouldBeRemoved: (borrowing Element) throws(E) -> Bool @@ -143,313 +98,4 @@ extension RigidArray where Element: ~Copyable { } #endif -extension RigidArray where Element: ~Copyable { - @_lifetime(&self) - public mutating func popLast(_ count: Int) -> InputSpan { - let c = Swift.min(count, self.count) - self._count &-= c - let span = InputSpan( - buffer: self._storage._extracting(last: c), - initializedCount: c) - return _overrideLifetime(span, mutating: &self) - } -} - -extension RigidArray where Element: ~Copyable { - @available(SwiftStdlib 5.0, *) - @_alwaysEmitIntoClient - public mutating func append( - moving items: inout InputSpan - ) { - items.withUnsafeMutableBufferPointer { buffer, count in - let source = buffer._extracting(last: count) - unsafe self.append(moving: source) - count = 0 - } - } - - @available(SwiftStdlib 5.0, *) - @_alwaysEmitIntoClient - public mutating func append( - moving items: inout OutputSpan - ) { - items.withUnsafeMutableBufferPointer { buffer, count in - let source = buffer._extracting(first: count) - unsafe self.append(moving: source) - count = 0 - } - } -} - -extension RigidArray { -#if FIXME - @inlinable - internal mutating func _appendContainer< - C: Container & ~Copyable & ~Escapable - >( - copying newElements: borrowing C - ) { - let (copied, end) = unsafe _freeSpace._initializePrefix( - copying: newElements) - precondition(end == newElements.endIndex, "RigidArray capacity overflow") - _count += copied - } -#endif - -#if FIXME - /// Copies the elements of a container to the end of this array. - /// - /// If the array does not have sufficient capacity to hold all items in the - /// container, then this triggers a runtime error. - /// - /// - Parameters - /// - newElements: A container whose contents to copy into the array. - /// - /// - Complexity: O(`newElements.count`) - @_alwaysEmitIntoClient - @inline(__always) - public mutating func append & ~Copyable & ~Escapable>( - copying newElements: borrowing C - ) { - _appendContainer(copying: newElements) - } -#endif - -#if FIXME - /// Copies the elements of a container to the end of this array. - /// - /// If the array does not have sufficient capacity to hold all items in the - /// container, then this triggers a runtime error. - /// - /// - Parameters - /// - newElements: The new elements to copy into the array. - /// - /// - Complexity: O(*m*), where *m* is the length of `newElements`. - @_alwaysEmitIntoClient - @inline(__always) - public mutating func append< - C: Container & Sequence - >(copying newElements: C) { - _appendContainer(copying: newElements) - } -#endif -} - -extension RigidArray where Element: ~Copyable { - @available(SwiftStdlib 5.0, *) - @_alwaysEmitIntoClient - public mutating func insert( - moving items: inout InputSpan, - at index: Int - ) { - items.withUnsafeMutableBufferPointer { buffer, count in - let source = buffer._extracting(last: count) - unsafe self.append(moving: source) - count = 0 - } - } - - @available(SwiftStdlib 5.0, *) - @_alwaysEmitIntoClient - public mutating func insert( - moving items: inout OutputSpan, - at index: Int - ) { - items.withUnsafeMutableBufferPointer { buffer, count in - let source = buffer._extracting(first: count) - unsafe self.append(moving: source) - count = 0 - } - } -} - -extension RigidArray { -#if FIXME - @inlinable - internal mutating func _insertContainer< - C: Container & ~Copyable & ~Escapable - >( - at index: Int, - copying items: borrowing C, - newCount: Int - ) { - precondition(index >= 0 && index <= _count, "Index out of bounds") - precondition(newCount <= freeCapacity, "RigidArray capacity overflow") - let target = unsafe _openGap(at: index, count: newCount) - let (copied, end) = unsafe target._initializePrefix(copying: items) - precondition( - copied == newCount && end == items.endIndex, - "Broken Container: count doesn't match contents") - _count += newCount - } -#endif - -#if FIXME - /// 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(*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 - ) { - _insertContainer( - at: index, copying: newElements, newCount: newElements.count) - } -#endif - -#if FIXME - /// 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(*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 - ) { - _insertContainer( - at: index, copying: newElements, newCount: newElements.count) - } -#endif -} - -extension RigidArray { -#if FIXME - @inlinable - public mutating func _replaceSubrange< - C: Container & ~Copyable & ~Escapable - >( - _ subrange: Range, - copyingContainer newElements: borrowing C, - newCount: Int - ) { - let gap = unsafe _gapForReplacement(of: subrange, withNewCount: newCount) - let (copied, end) = unsafe gap._initializePrefix(copying: newElements) - precondition( - copied == newCount && end == newElements.endIndex, - "Broken Container: count doesn't match contents") - } -#endif - -#if FIXME - /// Replaces the specified subrange of elements by copying the elements of - /// the given container. - /// - /// This method has the effect of removing the specified range of elements - /// from the array and inserting the new elements starting at the same - /// location. The number of new elements need not match the number of elements - /// being removed. - /// - /// If the capacity of the array isn't sufficient to accommodate the new - /// elements, then this method triggers a runtime error. - /// - /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. - /// - /// Likewise, if you pass a zero-length container as the `newElements` - /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. - /// - /// - Parameters: - /// - subrange: The subrange of the array to replace. The bounds of - /// the range must be valid indices in the array. - /// - newElements: The new elements to copy into the collection. - /// - /// - Complexity: O(`self.count` + `newElements.count`) - @inlinable - @inline(__always) - public mutating func replaceSubrange< - C: Container & ~Copyable & ~Escapable - >( - _ subrange: Range, - copying newElements: borrowing C - ) { - _replaceSubrange( - subrange, copyingContainer: newElements, newCount: newElements.count) - } -#endif - -#if FIXME - /// Replaces the specified subrange of elements by copying the elements of - /// the given container. - /// - /// This method has the effect of removing the specified range of elements - /// from the array and inserting the new elements starting at the same - /// location. The number of new elements need not match the number of elements - /// being removed. - /// - /// If the capacity of the array isn't sufficient to accommodate the new - /// elements, then this method triggers a runtime error. - /// - /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. - /// - /// Likewise, if you pass a zero-length container as the `newElements` - /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. - /// - /// - Parameters: - /// - subrange: The subrange of the array to replace. The bounds of - /// the range must be valid indices in the array. - /// - newElements: The new elements to copy into the collection. - /// - /// - Complexity: O(*n* + *m*), where *n* is count of this array and - /// *m* is the count of `newElements`. - @inlinable - @inline(__always) - public mutating func replaceSubrange< - C: Container & Collection - >( - _ subrange: Range, - copying newElements: C - ) { - _replaceSubrange( - subrange, copyingContainer: newElements, newCount: newElements.count) - } -#endif -} - -#endif #endif diff --git a/Sources/BasicContainers/RigidArray+Initializers.swift b/Sources/BasicContainers/RigidArray+Initializers.swift new file mode 100644 index 00000000..dd395144 --- /dev/null +++ b/Sources/BasicContainers/RigidArray+Initializers.swift @@ -0,0 +1,108 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + @inlinable + public init( + capacity: Int, + initializingWith body: (inout OutputSpan) throws(E) -> Void + ) throws(E) { + self.init(capacity: capacity) + try edit(body) + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidArray /*where Element: Copyable*/ { + /// Creates a new array containing the specified number of a single, + /// repeated value. + /// + /// - Parameters: + /// - repeatedValue: The element to repeat. + /// - count: The number of times to repeat the value passed in the + /// `repeating` parameter. `count` must be zero or greater. + public init(repeating repeatedValue: Element, count: Int) { + self.init(capacity: count) + unsafe _freeSpace.initialize(repeating: repeatedValue) + _count = count + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidArray /*where Element: Copyable*/ { + @_alwaysEmitIntoClient + @inline(__always) + public init( + capacity: Int, + copying contents: some Sequence + ) { + self.init(capacity: capacity) + self.append(copying: contents) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @_alwaysEmitIntoClient + @inline(__always) + public init & Sequence>( + capacity: Int, + copying contents: Source + ) { + self.init(capacity: capacity) + self.append(copying: contents) + } +#endif + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @_alwaysEmitIntoClient + @inline(__always) + public init & ~Copyable & ~Escapable>( + capacity: Int? = nil, + copying contents: borrowing Source + ) { + self.init(capacity: capacity ?? contents.count) + self.append(copying: contents) + } +#endif + + @_alwaysEmitIntoClient + @inline(__always) + public init( + capacity: Int? = nil, + copying contents: some Collection + ) { + self.init(capacity: capacity ?? contents.count) + self.append(copying: contents) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @_alwaysEmitIntoClient + @inline(__always) + public init & Collection>( + capacity: Int? = nil, + copying contents: Source + ) { + self.init(capacity: capacity ?? contents.count) + self.append(copying: contents) + } +#endif +} + +// FIXME: Add init(moving:), init(consuming:) + +#endif diff --git a/Sources/BasicContainers/RigidArray+Insertions.swift b/Sources/BasicContainers/RigidArray+Insertions.swift new file mode 100644 index 00000000..c1f076c4 --- /dev/null +++ b/Sources/BasicContainers/RigidArray+Insertions.swift @@ -0,0 +1,415 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + /// Inserts a new element into the array at the specified position. + /// + /// If the array does not have sufficient capacity to hold any more elements, + /// then this triggers a runtime error. + /// + /// The new element is inserted before the element currently at the specified + /// index. If you pass the array's `endIndex` as the `index` parameter, then + /// the new element is appended to the container. + /// + /// All existing elements at or following the specified position are moved to + /// make room for the new item. + /// + /// - Parameter item: The new element to insert into the array. + /// - Parameter i: The position at which to insert the new element. + /// `index` must be a valid index in the array. + /// + /// - Complexity: O(`count`) + @inlinable + public mutating func insert(_ item: consuming Element, at index: Int) { + precondition(index >= 0 && index <= count, "Index out of bounds") + precondition(!isFull, "RigidArray capacity overflow") + if index < count { + let source = unsafe _storage.extracting(index ..< count) + let target = unsafe _storage.extracting(index + 1 ..< count + 1) + let last = unsafe target.moveInitialize(fromContentsOf: source) + assert(last == target.endIndex) + } + unsafe _storage.initializeElement(at: index, to: item) + _count += 1 + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + @inlinable + public mutating func insert( + count: Int, + at index: Int, + initializingWith body: (inout OutputSpan) -> Result + ) -> Result { + // FIXME: This does not allow `body` to throw, to prevent having to move the tail twice. Is that okay? + precondition(index >= 0 && index <= self.count, "Index out of bounds") + precondition(count <= freeCapacity, "RigidArray capacity overflow") + let target = unsafe _openGap(at: index, count: count) + var span = OutputSpan(buffer: target, initializedCount: 0) + defer { + let c = span.finalize(for: target) + precondition(c == count, "Inserted fewer items than promised") + _count &+= c + span = OutputSpan() + } + return body(&span) + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + /// Moves the elements of a fully initialized buffer into this array, + /// starting at the specified position, and leaving the buffer + /// uninitialized. + /// + /// If the array does not have sufficient capacity to hold all items in the + /// buffer, then this triggers a runtime error. + /// + /// - Parameters + /// - items: A fully initialized buffer whose contents to move into + /// the array. + /// + /// - Complexity: O(`count` + `items.count`) + @_alwaysEmitIntoClient + public mutating func insert( + moving items: UnsafeMutableBufferPointer, + at index: Int + ) { + insert(count: items.count, at: index) { target in + target.withUnsafeMutableBufferPointer { buffer, count in + buffer.moveInitializeAll(fromContentsOf: items) + count = items.count + } + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @_alwaysEmitIntoClient + public mutating func insert( + moving items: inout InputSpan, + at index: Int + ) { + items.withUnsafeMutableBufferPointer { buffer, count in + let source = buffer._extracting(last: count) + unsafe self.insert(moving: source, at: index) + count = 0 + } + } +#endif + + @_alwaysEmitIntoClient + public mutating func insert( + moving items: inout OutputSpan, + at index: Int + ) { + items.withUnsafeMutableBufferPointer { buffer, count in + let source = buffer._extracting(first: count) + unsafe self.insert(moving: source, at: index) + count = 0 + } + } + + /// 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 + /// storage capacity. + /// + /// 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: An array whose contents to move into `self`. + /// + /// - Complexity: O(`count` + `items.count`) + @_alwaysEmitIntoClient + public mutating func insert( + moving items: inout RigidArray, + at index: Int + ) { + insert(count: items.count, at: index) { target in + target.withUnsafeMutableBufferPointer { dst, dstCount in + items.edit { source in + source.withUnsafeMutableBufferPointer { src, srcCount in + dst.moveInitializeAll(fromContentsOf: src) + dstCount = src.count + srcCount = 0 + } + } + } + } + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + /// Inserts the elements of a given array into the given position in 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 fully initialized buffer whose contents to move into + /// the array. + /// + /// - Complexity: O(`count` + `items.count`) + @_alwaysEmitIntoClient + public mutating func insert( + consuming items: consuming RigidArray, + at index: Int + ) { + var items = items + self.insert(moving: &items, at: index) + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidArray { + /// Copies the elements of a fully initialized buffer pointer 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. The buffer + /// must be fully initialized. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of the array. + /// + /// - Complexity: O(`count` + `newElements.count`) + @inlinable + public mutating func insert( + copying newElements: UnsafeBufferPointer, at index: Int + ) { + guard newElements.count > 0 else { return } + self.insert(count: newElements.count, at: index) { target in + target.withUnsafeMutableBufferPointer { buffer, count in + buffer.initializeAll(fromContentsOf: newElements) + count = newElements.count + } + } + } + + /// Copies the elements of a fully initialized buffer pointer 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. The buffer + /// must be fully initialized. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of the array. + /// + /// - Complexity: O(`count` + `newElements.count`) + @inlinable + public mutating func insert( + copying newElements: UnsafeMutableBufferPointer, + at index: Int + ) { + unsafe self.insert(copying: UnsafeBufferPointer(newElements), at: index) + } + + /// Copies the elements of a span 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(`count` + `newElements.count`) + @inlinable + public mutating func insert( + copying newElements: Span, at index: Int + ) { + unsafe newElements.withUnsafeBufferPointer { + unsafe self.insert(copying: $0, at: index) + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @inlinable + internal mutating func _insertContainer< + C: Container & ~Copyable & ~Escapable + >( + at index: Int, + copying items: borrowing C, + newCount: Int + ) { + insert(count: newCount, at: index) { target in + target.withUnsafeMutableBufferPointer { buffer, count in + let copied = items._copyContents(intoPrefixOf: buffer) + precondition( + copied == newCount, + "Broken Container: count doesn't match contents") + count = newCount + } + } + } +#endif + + @inlinable + internal mutating func _insertCollection( + at index: Int, + copying items: some Collection, + newCount: Int + ) { + precondition(index >= 0 && index <= _count, "Index out of bounds") + 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 COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// 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(*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 + ) { + _insertContainer( + at: index, copying: newElements, newCount: newElements.count) + } +#endif + + /// Copies the elements of a collection 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(`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 COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// 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(*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 + ) { + _insertContainer( + at: index, copying: newElements, newCount: newElements.count) + } +#endif +} + +#endif diff --git a/Sources/BasicContainers/RigidArray+Removals.swift b/Sources/BasicContainers/RigidArray+Removals.swift new file mode 100644 index 00000000..888009d0 --- /dev/null +++ b/Sources/BasicContainers/RigidArray+Removals.swift @@ -0,0 +1,187 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + /// Removes all elements from the array, preserving its allocated capacity. + /// + /// - Complexity: O(*n*), where *n* is the original count of the array. + @inlinable + public mutating func removeAll() { + unsafe _items.deinitialize() + _count = 0 + } + + /// Removes and returns the last element of the array. + /// + /// The array must not be empty. + /// + /// - Returns: The last element of the original array. + /// + /// - Complexity: O(1) + @inlinable + @discardableResult + public mutating func removeLast() -> Element { + precondition(!isEmpty, "Cannot remove last element from an empty array") + let old = unsafe _storage.moveElement(from: _count - 1) + _count -= 1 + return old + } + + /// Removes and discards the specified number of elements from the end of the + /// array. + /// + /// Attempting to remove more elements than exist in the array + /// triggers a runtime error. + /// + /// - Parameter k: The number of elements to remove from the array. + /// `k` must be greater than or equal to zero and must not exceed + /// the count of the array. + /// + /// - Complexity: O(`k`) + @inlinable + public mutating func removeLast(_ k: Int) { + if k == 0 { return } + precondition( + k >= 0 && k <= _count, + "Count of elements to remove is out of bounds") + unsafe _storage.extracting( + Range(uncheckedBounds: (_count - k, _count)) + ).deinitialize() + _count &-= k + } + + /// Removes and returns the element at the specified position. + /// + /// All the elements following the specified position are moved to close the + /// gap. + /// + /// - Parameter i: The position of the element to remove. `index` must be + /// a valid index of the array that is not equal to the end index. + /// - Returns: The removed element. + /// + /// - Complexity: O(`count`) + @inlinable + @discardableResult + public mutating func remove(at index: Int) -> Element { + precondition(index >= 0 && index < _count, "Index out of bounds") + let old = unsafe _storage.moveElement(from: index) + _closeGap(at: index, count: 1) + _count -= 1 + return old + } + + /// Removes the specified subrange of elements from the array. + /// + /// All the elements following the specified subrange are moved to close the + /// resulting gap. + /// + /// - Parameter bounds: The subrange of the array to remove. The bounds + /// of the range must be valid indices of the array. + /// + /// - Complexity: O(`count`) + @inlinable + public mutating func removeSubrange(_ bounds: Range) { + precondition( + bounds.lowerBound >= 0 && bounds.upperBound <= _count, + "Subrange out of bounds") + guard !bounds.isEmpty else { return } + unsafe _storage.extracting(bounds).deinitialize() + _closeGap(at: bounds.lowerBound, count: bounds.count) + _count -= bounds.count + } + + /// Removes the specified subrange of elements from the array. + /// + /// - Parameter bounds: The subrange of the array to remove. The bounds of the + /// range must be valid indices of the array. + /// + /// - Complexity: O(`count`) + @_alwaysEmitIntoClient + public mutating func removeSubrange(_ bounds: some RangeExpression) { + // FIXME: Remove this in favor of a standard algorithm. + removeSubrange(bounds.relative(to: indices)) + } +} + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + @_lifetime(&self) + @_alwaysEmitIntoClient + public mutating func consumeAll() -> InputSpan { + let span = InputSpan(buffer: _items, initializedCount: self.count) + self._count = 0 + return _overrideLifetime(span, mutating: &self) + } + + @_lifetime(&self) + @_alwaysEmitIntoClient + public mutating func consumeLast(_ count: Int) -> InputSpan { + precondition(count >= 0, "Cannot consume a negative number of items") + let c = Swift.min(count, self.count) + self._count &-= c + let span = InputSpan( + buffer: self._storage._extracting(first: c), + initializedCount: c) + return _overrideLifetime(span, mutating: &self) + } + + @_alwaysEmitIntoClient + public mutating func consumeSubrange( + _ bounds: Range, + consumingWith body: (inout InputSpan) throws(E) -> Result + ) throws(E) -> Result { + precondition( + bounds.lowerBound >= 0 && bounds.upperBound <= _count, + "Subrange out of bounds") + guard !bounds.isEmpty else { + var span = InputSpan() + return try body(&span) + } + let buffer = unsafe _storage.extracting(bounds) + var span = InputSpan(buffer: buffer, initializedCount: buffer.count) + defer { + let remainder = span.finalize(for: buffer) + buffer._extracting(last: remainder).deinitialize() + _closeGap(at: bounds.lowerBound, count: bounds.count) + _count -= bounds.count + span = InputSpan() + } + return try body(&span) + } +} +#endif + +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + /// 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; + /// otherwise, `nil`. + /// + /// - Complexity: O(1) + @_alwaysEmitIntoClient + public mutating func popLast() -> Element? { + // FIXME: Remove this in favor of a standard algorithm. + if isEmpty { return nil } + return removeLast() + } +} + +#endif diff --git a/Sources/BasicContainers/RigidArray+Replacements.swift b/Sources/BasicContainers/RigidArray+Replacements.swift new file mode 100644 index 00000000..f1541949 --- /dev/null +++ b/Sources/BasicContainers/RigidArray+Replacements.swift @@ -0,0 +1,464 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + @inlinable + public mutating func replaceSubrange( + _ subrange: Range, + newCount: Int, + initializingWith body: (inout OutputSpan) -> Result + ) -> Result { + // FIXME: Should we allow throwing (and a partially filled output span)? + // FIXME: Should we have a version of this with two closures, to allow custom-consuming the old items? + // replaceSubrange(5..<10, newCount: 3, consumingWith: {...}, initializingWith: {...}) + let target = _gapForReplacement(of: subrange, withNewCount: newCount) + var span = OutputSpan(buffer: target, initializedCount: 0) + defer { + let c = span.finalize(for: target) + precondition(c == newCount, "Inserted fewer items than promised") + span = OutputSpan() + } + return body(&span) + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + /// Replaces the specified range of elements by moving the elements of a + /// fully initialized buffer into their place. On return, the buffer is left + /// in an uninitialized state. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: A fully initialized buffer whose contents to move into + /// the array. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + moving newElements: UnsafeMutableBufferPointer, + ) { + replaceSubrange(subrange, newCount: newElements.count) { target in + target.withUnsafeMutableBufferPointer { buffer, count in + count = unsafe buffer._moveInitializePrefix(from: newElements) + } + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + moving items: inout InputSpan + ) { + items.withUnsafeMutableBufferPointer { buffer, count in + let source = buffer._extracting(last: count) + unsafe self.replaceSubrange(subrange, moving: source) + count = 0 + } + } +#endif + + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + moving items: inout OutputSpan + ) { + items.withUnsafeMutableBufferPointer { buffer, count in + let source = buffer._extracting(first: count) + unsafe self.replaceSubrange(subrange, moving: source) + count = 0 + } + } + + /// Replaces the specified range of elements by moving the elements of a + /// another array into their place. On return, the source array + /// becomes empty, but it is not destroyed, and it preserves its original + /// storage capacity. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: An array whose contents to move into `self`. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + moving newElements: inout RigidArray, + ) { + unsafe newElements._unsafeEdit { buffer, count in + let source = buffer._extracting(first: count) + unsafe self.replaceSubrange(subrange, moving: source) + count = 0 + } + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + /// Replaces the specified range of elements by moving the elements of a + /// given array into their place, consuming it in the process. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: An array whose contents to move into `self`. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + consuming newElements: consuming RigidArray, + ) { + replaceSubrange(subrange, moving: &newElements) + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidArray { + /// Replaces the specified subrange of elements by copying the elements of + /// the given buffer pointer, which must be fully initialized. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @inlinable + public mutating func replaceSubrange( + _ subrange: Range, + copying newElements: UnsafeBufferPointer + ) { + replaceSubrange(subrange, newCount: newElements.count) { target in + target.withUnsafeMutableBufferPointer { buffer, count in + count = unsafe buffer._initializePrefix(copying: newElements) + } + } + } + + /// Replaces the specified subrange of elements by copying the elements of + /// the given buffer pointer, which must be fully initialized. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @inlinable + public mutating func replaceSubrange( + _ subrange: Range, + copying newElements: UnsafeMutableBufferPointer + ) { + unsafe self.replaceSubrange( + subrange, + copying: UnsafeBufferPointer(newElements)) + } + + /// Replaces the specified subrange of elements by copying the elements of + /// the given span. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length span as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @inlinable + public mutating func replaceSubrange( + _ subrange: Range, + copying newElements: Span + ) { + unsafe newElements.withUnsafeBufferPointer { buffer in + unsafe self.replaceSubrange(subrange, copying: buffer) + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @inlinable + internal mutating func _replaceSubrange< + C: Container & ~Copyable & ~Escapable + >( + _ subrange: Range, + copyingContainer newElements: borrowing C, + newCount: Int + ) { + self.replaceSubrange(subrange, newCount: newCount) { target in + target.withUnsafeMutableBufferPointer { buffer, count in + count = newElements._copyContents(intoPrefixOf: buffer) + precondition( + count == newCount, + "Broken Container: count doesn't match contents") + } + } + } +#endif + + @inlinable + internal mutating func _replaceSubrange( + _ subrange: Range, + copyingCollection newElements: __owned some Collection, + newCount: Int + ) { + self.replaceSubrange(subrange, newCount: newCount) { target in + target.withUnsafeMutableBufferPointer { dst, dstCount in + let done: Void? = newElements.withContiguousStorageIfAvailable { src in + let i = unsafe dst._initializePrefix(copying: src) + precondition( + i == newCount, + "Broken Collection: count doesn't match contents") + dstCount = i + } + if done != nil { return } + + var (it, copied) = unsafe newElements._copyContents(initializing: dst) + dstCount = copied + precondition( + it.next() == nil && copied == newCount, + "Broken Collection: count doesn't match contents") + } + } + + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Replaces the specified subrange of elements by copying the elements of + /// the given container. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length container as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @inlinable + @inline(__always) + public mutating func replaceSubrange< + C: Container & ~Copyable & ~Escapable + >( + _ subrange: Range, + copying newElements: borrowing C + ) { + _replaceSubrange( + subrange, copyingContainer: newElements, newCount: newElements.count) + } +#endif + + /// Replaces the specified subrange of elements by copying the elements of + /// the given collection. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length collection as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @inlinable + @inline(__always) + public mutating func replaceSubrange( + _ subrange: Range, + copying newElements: __owned some Collection + ) { + _replaceSubrange( + subrange, copyingCollection: newElements, newCount: newElements.count) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Replaces the specified subrange of elements by copying the elements of + /// the given container. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length container as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: The new elements to copy into the collection. + /// + /// - Complexity: O(*n* + *m*), where *n* is count of this array and + /// *m* is the count of `newElements`. + @inlinable + @inline(__always) + public mutating func replaceSubrange< + C: Container & Collection + >( + _ subrange: Range, + copying newElements: C + ) { + _replaceSubrange( + subrange, copyingContainer: newElements, newCount: newElements.count) + } +#endif +} + +#endif diff --git a/Sources/BasicContainers/RigidArray.swift b/Sources/BasicContainers/RigidArray.swift index b084474a..c3c1b749 100644 --- a/Sources/BasicContainers/RigidArray.swift +++ b/Sources/BasicContainers/RigidArray.swift @@ -11,6 +11,7 @@ #if !COLLECTIONS_SINGLE_MODULE import InternalCollectionsUtilities +import ContainersPreview #endif #if compiler(<6.2) @@ -41,7 +42,7 @@ public struct RigidArray: ~Copyable { /// A fixed capacity, heap allocated, noncopyable array of potentially /// noncopyable elements. /// -/// `RigidArray` instances are created with a certain maximum capacity. Elements +/// `RigidArray` instances are created with a specific maximum capacity. Elements /// can be added to the array up to that capacity, but no more: trying to add an /// item to a full array results in a runtime trap. /// @@ -73,7 +74,9 @@ public struct RigidArray: ~Copyable { /// spikes due to a reallocation getting triggered at an inopportune moment. /// /// For use cases outside of these narrow domains, we generally recommmend -/// the use of ``UniqueArray`` rather than `RigidArray`. +/// the use of ``UniqueArray`` rather than `RigidArray`. (For copyable elements, +/// the standard `Array` is an even more convenient choice.) +@available(SwiftStdlib 5.0, *) @safe @frozen public struct RigidArray: ~Copyable { @@ -107,63 +110,14 @@ public struct RigidArray: ~Copyable { _count = 0 } } + +@available(SwiftStdlib 5.0, *) extension RigidArray: @unchecked Sendable where Element: Sendable & ~Copyable {} -//MARK: - Initializers - -extension RigidArray where Element: ~Copyable { - @available(SwiftStdlib 5.0, *) - @inlinable - public init( - capacity: Int, - initializedWith body: (inout OutputSpan) throws(E) -> Void - ) throws(E) { - self.init(capacity: capacity) - try edit(body) - } -} - -extension RigidArray /*where Element: Copyable*/ { - /// Creates a new array containing the specified number of a single, - /// repeated value. - /// - /// - Parameters: - /// - repeatedValue: The element to repeat. - /// - count: The number of times to repeat the value passed in the - /// `repeating` parameter. `count` must be zero or greater. - public init(repeating repeatedValue: Element, count: Int) { - self.init(capacity: count) - unsafe _freeSpace.initialize(repeating: repeatedValue) - _count = count - } -} - -extension RigidArray /*where Element: Copyable*/ { - @_alwaysEmitIntoClient - @inline(__always) - public init( - capacity: Int, - copying contents: some Sequence - ) { - self.init(capacity: capacity) - self.append(copying: contents) - } - - @_alwaysEmitIntoClient - @inline(__always) - public init( - capacity: Int? = nil, - copying contents: some Collection - ) { - self.init(capacity: capacity ?? contents.count) - self.append(copying: contents) - } -} - -// FIXME: init(moving:), init(consuming:) //MARK: - Basics +@available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { @inlinable @_transparent @@ -180,6 +134,7 @@ extension RigidArray where Element: ~Copyable { public var isFull: Bool { freeCapacity == 0 } } +@available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { @inlinable internal var _items: UnsafeMutableBufferPointer { @@ -194,8 +149,8 @@ extension RigidArray where Element: ~Copyable { //MARK: - Span creation +@available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { - @available(SwiftStdlib 5.0, *) public var span: Span { @_lifetime(borrow self) @inlinable @@ -205,7 +160,6 @@ extension RigidArray where Element: ~Copyable { } } - @available(SwiftStdlib 5.0, *) public var mutableSpan: MutableSpan { @_lifetime(&self) @inlinable @@ -215,14 +169,12 @@ extension RigidArray where Element: ~Copyable { } } - @available(SwiftStdlib 5.0, *) @inlinable @_lifetime(borrow self) internal func _span(in range: Range) -> Span { span.extracting(range) } - @available(SwiftStdlib 5.0, *) @inlinable @_lifetime(&self) internal mutating func _mutableSpan( @@ -233,6 +185,7 @@ extension RigidArray where Element: ~Copyable { } } +@available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { /// Arbitrarily edit the storage underlying this array by invoking a /// user-supplied closure with a mutable `OutputSpan` view over it. @@ -251,7 +204,6 @@ extension RigidArray where Element: ~Copyable { /// - Returns: This method returns the result of its function argument. /// - Complexity: Adds O(1) overhead to the complexity of the function /// argument. - @available(SwiftStdlib 5.0, *) @inlinable public mutating func edit( _ body: (inout OutputSpan) throws(E) -> R @@ -275,6 +227,7 @@ extension RigidArray where Element: ~Copyable { } } +@available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { @inlinable internal func _contiguousSubrange(following index: inout Int) -> Range { @@ -291,11 +244,10 @@ extension RigidArray where Element: ~Copyable { } } -//MARK: - Random-access & mutable container primitives +//MARK: - Container primitives +@available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { - public typealias Index = Int - @inlinable @inline(__always) public var isEmpty: Bool { count == 0 } @@ -303,6 +255,24 @@ extension RigidArray where Element: ~Copyable { @inlinable @inline(__always) public var count: Int { _count } +} + +#if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +@available(SwiftStdlib 5.0, *) +extension RigidArray: Container where Element: ~Copyable { + public typealias BorrowIterator = Span + + @_alwaysEmitIntoClient + @inline(__always) + public func startBorrowIteration() -> Span { + self.span + } +} +#endif + +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + public typealias Index = Int @inlinable @inline(__always) @@ -317,6 +287,7 @@ extension RigidArray where Element: ~Copyable { public var indices: Range { unsafe Range(uncheckedBounds: (0, count)) } } +@available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { @inlinable @inline(__always) internal func _ptr(to index: Int) -> UnsafePointer { @@ -344,6 +315,7 @@ extension RigidArray where Element: ~Copyable { } } +@available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { @inlinable public mutating func swapAt(_ i: Int, _ j: Int) { @@ -354,15 +326,14 @@ extension RigidArray where Element: ~Copyable { } } +@available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { - @available(SwiftStdlib 5.0, *) @inlinable @_lifetime(borrow self) public func span(after index: inout Int) -> Span { _span(in: _contiguousSubrange(following: &index)) } - @available(SwiftStdlib 5.0, *) @inlinable @_lifetime(borrow self) public func span(before index: inout Int) -> Span { @@ -370,8 +341,8 @@ extension RigidArray where Element: ~Copyable { } } +@available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { - @available(SwiftStdlib 5.0, *) @_lifetime(&self) public mutating func mutableSpan( after index: inout Int @@ -379,7 +350,6 @@ extension RigidArray where Element: ~Copyable { _mutableSpan(in: _contiguousSubrange(following: &index)) } - @available(SwiftStdlib 5.0, *) @_lifetime(&self) public mutating func mutableSpan( before index: inout Int @@ -390,6 +360,7 @@ extension RigidArray where Element: ~Copyable { //MARK: - Resizing +@available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { @inlinable public mutating func reallocate(capacity newCapacity: Int) { @@ -412,6 +383,7 @@ extension RigidArray where Element: ~Copyable { //MARK: - Copying helpers +@available(SwiftStdlib 5.0, *) extension RigidArray { @inlinable public func copy() -> Self { @@ -432,6 +404,7 @@ extension RigidArray { //MARK: - Opening and closing gaps +@available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { @inlinable internal mutating func _closeGap( @@ -463,583 +436,7 @@ extension RigidArray where Element: ~Copyable { return unsafe _storage.extracting( Range(uncheckedBounds: (index, index + count))) } -} - -//MARK: - Removal operations - -extension RigidArray where Element: ~Copyable { - /// Removes all elements from the array, preserving its allocated capacity. - /// - /// - Complexity: O(*n*), where *n* is the original count of the array. - @inlinable - public mutating func removeAll() { - unsafe _items.deinitialize() - _count = 0 - } - - /// Removes and returns the last element of the array. - /// - /// The array must not be empty. - /// - /// - Returns: The last element of the original array. - /// - /// - Complexity: O(1) - @inlinable - @discardableResult - public mutating func removeLast() -> Element { - precondition(!isEmpty, "Cannot remove last element from an empty array") - let old = unsafe _storage.moveElement(from: _count - 1) - _count -= 1 - return old - } - - /// Removes and discards the specified number of elements from the end of the - /// array. - /// - /// Attempting to remove more elements than exist in the array - /// triggers a runtime error. - /// - /// - Parameter k: The number of elements to remove from the array. - /// `k` must be greater than or equal to zero and must not exceed - /// the count of the array. - /// - /// - Complexity: O(`k`) - @inlinable - public mutating func removeLast(_ k: Int) { - if k == 0 { return } - precondition( - k >= 0 && k <= _count, - "Count of elements to remove is out of bounds") - unsafe _storage.extracting( - Range(uncheckedBounds: (_count - k, _count)) - ).deinitialize() - _count &-= k - } - - /// Removes and returns the element at the specified position. - /// - /// All the elements following the specified position are moved to close the - /// gap. - /// - /// - Parameter i: The position of the element to remove. `index` must be - /// a valid index of the array that is not equal to the end index. - /// - Returns: The removed element. - /// - /// - Complexity: O(`count`) - @inlinable - @discardableResult - public mutating func remove(at index: Int) -> Element { - precondition(index >= 0 && index < _count, "Index out of bounds") - let old = unsafe _storage.moveElement(from: index) - _closeGap(at: index, count: 1) - _count -= 1 - return old - } - - /// Removes the specified subrange of elements from the array. - /// - /// All the elements following the specified subrange are moved to close the - /// resulting gap. - /// - /// - Parameter bounds: The subrange of the array to remove. The bounds - /// of the range must be valid indices of the array. - /// - /// - Complexity: O(`count`) - @inlinable - public mutating func removeSubrange(_ bounds: Range) { - precondition( - bounds.lowerBound >= 0 && bounds.upperBound <= _count, - "Subrange out of bounds") - guard !bounds.isEmpty else { return } - unsafe _storage.extracting(bounds).deinitialize() - _closeGap(at: bounds.lowerBound, count: bounds.count) - _count -= bounds.count - } - - /// Removes the specified subrange of elements from the array. - /// - /// - Parameter bounds: The subrange of the array to remove. The bounds of the - /// range must be valid indices of the array. - /// - /// - Complexity: O(`count`) - @_alwaysEmitIntoClient - public mutating func removeSubrange(_ bounds: some RangeExpression) { - // FIXME: Remove this in favor of a standard algorithm. - removeSubrange(bounds.relative(to: indices)) - } -} - -extension RigidArray where Element: ~Copyable { - /// 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; - /// otherwise, `nil`. - /// - /// - Complexity: O(1) - @_alwaysEmitIntoClient - public mutating func popLast() -> Element? { - // FIXME: Remove this in favor of a standard algorithm. - if isEmpty { return nil } - return removeLast() - } -} - -//MARK: - Append operations - -extension RigidArray where Element: ~Copyable { - /// Adds an element to the end of the array. - /// - /// If the array does not have sufficient capacity to hold any more elements, - /// then this triggers a runtime error. - /// - /// - Parameter item: The element to append to the collection. - /// - /// - Complexity: O(1) - @inlinable - public mutating func append(_ item: consuming Element) { - precondition(!isFull, "RigidArray capacity overflow") - unsafe _storage.initializeElement(at: _count, to: item) - _count &+= 1 - } - - /// Adds an element to the end of the array, if possible. - /// - /// If the array does not have sufficient capacity to hold any more elements, - /// then this returns the given item without appending it; otherwise it - /// returns nil. - /// - /// - Parameter item: The element to append to the collection. - /// - Returns: `item` if the array is full; otherwise nil. - /// - /// - Complexity: O(1) - @inlinable - public mutating func pushLast(_ item: consuming Element) -> Element? { - // FIXME: Remove this in favor of a standard algorithm. - if isFull { return item } - append(item) - return nil - } -} - -extension RigidArray where Element: ~Copyable { - /// Moves the elements of a buffer to the end of this array, leaving the - /// buffer uninitialized. - /// - /// If the array does not have sufficient capacity to hold all items in the - /// buffer, then this triggers a runtime error. - /// - /// - Parameters - /// - items: A fully initialized buffer whose contents to move into - /// the array. - /// - /// - Complexity: O(`items.count`) - @_alwaysEmitIntoClient - public mutating func append( - moving items: UnsafeMutableBufferPointer - ) { - precondition(items.count <= freeCapacity, "RigidArray capacity overflow") - guard items.count > 0 else { return } - let c = unsafe _freeSpace._moveInitializePrefix(from: items) - assert(c == items.count) - _count &+= items.count - } - - /// 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. - /// - /// 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: An array whose items to move to the end of this array. - /// - /// - Complexity: O(`items.count`) - @_alwaysEmitIntoClient - public mutating func append( - moving items: inout RigidArray - ) { - // FIXME: Remove this in favor of a generic algorithm over range-replaceable containers - unsafe items._unsafeEdit { buffer, count in - let source = buffer._extracting(first: count) - unsafe self.append(moving: source) - count = 0 - } - } -} - -extension RigidArray where Element: ~Copyable { - /// 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 fully initialized buffer whose contents to move into - /// the 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) - } -} - -extension RigidArray { - /// Copies the elements of a buffer to the end of this array. - /// - /// If the array does not have sufficient capacity to hold all items in the - /// buffer, then this triggers a runtime error. - /// - /// - Parameters - /// - newElements: A fully initialized buffer whose contents to copy into - /// the array. - /// - /// - Complexity: O(`newElements.count`) - @_alwaysEmitIntoClient - public mutating func append( - copying newElements: UnsafeBufferPointer - ) { - precondition( - newElements.count <= freeCapacity, - "RigidArray capacity overflow") - guard newElements.count > 0 else { return } - unsafe _freeSpace.baseAddress.unsafelyUnwrapped.initialize( - from: newElements.baseAddress.unsafelyUnwrapped, count: newElements.count) - _count &+= newElements.count - } - - /// Copies the elements of a buffer to the end of this array. - /// - /// If the array does not have sufficient capacity to hold all items in the - /// buffer, then this triggers a runtime error. - /// - /// - Parameters - /// - newElements: A fully initialized buffer whose contents to copy into - /// the array. - /// - /// - Complexity: O(`newElements.count`) - @_alwaysEmitIntoClient - public mutating func append( - copying items: UnsafeMutableBufferPointer - ) { - unsafe self.append(copying: UnsafeBufferPointer(items)) - } - - /// Copies the elements of a span to the end of this array. - /// - /// If the array does not have sufficient capacity to hold all items in the - /// span, then this triggers a runtime error. - /// - /// - Parameters - /// - newElements: A span whose contents to copy into the array. - /// - /// - Complexity: O(`newElements.count`) - @available(SwiftStdlib 5.0, *) - @_alwaysEmitIntoClient - public mutating func append(copying items: Span) { - unsafe items.withUnsafeBufferPointer { source in - unsafe self.append(copying: source) - } - } - - @_alwaysEmitIntoClient - @inline(__always) - internal mutating func _append>( - prefixOf items: S - ) -> S.Iterator { - let (it, c) = unsafe items._copyContents(initializing: _freeSpace) - _count += c - return it - } - - /// Copies the elements of a sequence to the end of this array. - /// - /// If the array does not have sufficient capacity to hold all items in the - /// sequence, then this triggers a runtime error. - /// - /// - Parameters - /// - newElements: The new elements to copy into the array. - /// - /// - Complexity: O(*m*), where *m* is the length of `newElements`. - @_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 } - - var it = self._append(prefixOf: newElements) - precondition(it.next() == nil, "RigidArray capacity overflow") - } -} - -//MARK: - Insert operations - - -extension RigidArray where Element: ~Copyable { - /// Inserts a new element into the array at the specified position. - /// - /// If the array does not have sufficient capacity to hold any more elements, - /// then this triggers a runtime error. - /// - /// The new element is inserted before the element currently at the specified - /// index. If you pass the array's `endIndex` as the `index` parameter, then - /// the new element is appended to the container. - /// - /// All existing elements at or following the specified position are moved to - /// make room for the new item. - /// - /// - Parameter item: The new element to insert into the array. - /// - Parameter i: The position at which to insert the new element. - /// `index` must be a valid index in the array. - /// - /// - Complexity: O(`count`) - @inlinable - public mutating func insert(_ item: consuming Element, at index: Int) { - precondition(index >= 0 && index <= count, "Index out of bounds") - precondition(!isFull, "RigidArray capacity overflow") - if index < count { - let source = unsafe _storage.extracting(index ..< count) - let target = unsafe _storage.extracting(index + 1 ..< count + 1) - let last = unsafe target.moveInitialize(fromContentsOf: source) - assert(last == target.endIndex) - } - unsafe _storage.initializeElement(at: index, to: item) - _count += 1 - } -} - -extension RigidArray where Element: ~Copyable { - /// Moves the elements of a fully initialized buffer into this array, - /// starting at the specified position, and leaving the buffer - /// uninitialized. - /// - /// If the array does not have sufficient capacity to hold all items in the - /// buffer, then this triggers a runtime error. - /// - /// - Parameters - /// - items: A fully initialized buffer whose contents to move into - /// the array. - /// - /// - Complexity: O(`count` + `items.count`) - @_alwaysEmitIntoClient - public mutating func insert( - moving items: UnsafeMutableBufferPointer, - at index: Int - ) { - precondition(items.count <= freeCapacity, "RigidArray capacity overflow") - guard items.count > 0 else { return } - let target = unsafe _openGap(at: index, count: items.count) - let c = unsafe target._moveInitializePrefix(from: items) - assert(c == items.count) - _count &+= items.count - } - - /// 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 - /// storage capacity. - /// - /// 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: An array whose contents to move into `self`. - /// - /// - Complexity: O(`count` + `items.count`) - @_alwaysEmitIntoClient - public mutating func insert( - moving items: inout RigidArray, - at index: Int - ) { - precondition(items.count <= freeCapacity, "RigidArray capacity overflow") - guard items.count > 0 else { return } - unsafe items._unsafeEdit { buffer, count in - let source = buffer._extracting(first: count) - unsafe self.insert(moving: source, at: index) - count = 0 - } - } -} - -extension RigidArray where Element: ~Copyable { - /// Inserts the elements of a given array into the given position in 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 fully initialized buffer whose contents to move into - /// the array. - /// - /// - Complexity: O(`count` + `items.count`) - @_alwaysEmitIntoClient - public mutating func insert( - consuming items: consuming RigidArray, - at index: Int - ) { - var items = items - self.insert(moving: &items, at: index) - } -} - -extension RigidArray { - /// Copies the elements of a fully initialized buffer pointer 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. The buffer - /// must be fully initialized. - /// - index: The position at which to insert the new elements. It must be - /// a valid index of the array. - /// - /// - Complexity: O(`count` + `newElements.count`) - @inlinable - public mutating func insert( - copying newElements: UnsafeBufferPointer, at index: Int - ) { - guard newElements.count > 0 else { return } - precondition( - newElements.count <= freeCapacity, - "RigidArray capacity overflow") - let gap = unsafe _openGap(at: index, count: newElements.count) - unsafe gap.baseAddress.unsafelyUnwrapped.initialize( - from: newElements.baseAddress.unsafelyUnwrapped, count: newElements.count) - _count += newElements.count - } - - /// Copies the elements of a fully initialized buffer pointer 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. The buffer - /// must be fully initialized. - /// - index: The position at which to insert the new elements. It must be - /// a valid index of the array. - /// - /// - Complexity: O(`count` + `newElements.count`) - @inlinable - public mutating func insert( - copying newElements: UnsafeMutableBufferPointer, - at index: Int - ) { - unsafe self.insert(copying: UnsafeBufferPointer(newElements), at: index) - } - - /// Copies the elements of a span 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(`count` + `newElements.count`) - @available(SwiftStdlib 5.0, *) - @inlinable - public mutating func insert( - copying newElements: Span, at index: Int - ) { - unsafe newElements.withUnsafeBufferPointer { - unsafe self.insert(copying: $0, at: index) - } - } - - @inlinable - internal mutating func _insertCollection( - at index: Int, - copying items: some Collection, - newCount: Int - ) { - precondition(index >= 0 && index <= _count, "Index out of bounds") - 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 - } - - /// Copies the elements of a collection 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(`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) - } -} - -//MARK: - Range replacement - -extension RigidArray where Element: ~Copyable { + /// Perform a range replacement up to populating the newly opened gap. This /// deinitializes existing elements in the specified subrange, rearranges /// following elements to be at their final location, and sets the container's @@ -1052,7 +449,6 @@ extension RigidArray where Element: ~Copyable { internal mutating func _gapForReplacement( of subrange: Range, withNewCount newCount: Int ) -> UnsafeMutableBufferPointer { - // FIXME: Replace this with a public variant based on OutputSpan. precondition( subrange.lowerBound >= 0 && subrange.upperBound <= _count, "Index range out of bounds") @@ -1074,290 +470,4 @@ extension RigidArray where Element: ~Copyable { } } -extension RigidArray where Element: ~Copyable { - /// Replaces the specified range of elements by moving the elements of a - /// fully initialized buffer into their place. On return, the buffer is left - /// in an uninitialized state. - /// - /// This method has the effect of removing the specified range of elements - /// from the array and inserting the new elements starting at the same - /// location. The number of new elements need not match the number of elements - /// being removed. - /// - /// If the capacity of the array isn't sufficient to accommodate the new - /// elements, then this method triggers a runtime error. - /// - /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. - /// - /// Likewise, if you pass a zero-length buffer as the `newElements` - /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. - /// - /// - Parameters - /// - subrange: The subrange of the array to replace. The bounds of - /// the range must be valid indices in the array. - /// - newElements: A fully initialized buffer whose contents to move into - /// the array. - /// - /// - Complexity: O(`self.count` + `newElements.count`) - @_alwaysEmitIntoClient - public mutating func replaceSubrange( - _ subrange: Range, - moving newElements: UnsafeMutableBufferPointer, - ) { - let gap = unsafe _gapForReplacement( - of: subrange, withNewCount: newElements.count) - let c = unsafe gap._moveInitializePrefix(from: newElements) - assert(c == newElements.count) - } - - /// Replaces the specified range of elements by moving the elements of a - /// another array into their place. On return, the source array - /// becomes empty, but it is not destroyed, and it preserves its original - /// storage capacity. - /// - /// This method has the effect of removing the specified range of elements - /// from the array and inserting the new elements starting at the same - /// location. The number of new elements need not match the number of elements - /// being removed. - /// - /// If the capacity of the array isn't sufficient to accommodate the new - /// elements, then this method triggers a runtime error. - /// - /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. - /// - /// Likewise, if you pass a zero-length buffer as the `newElements` - /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. - /// - /// - Parameters - /// - subrange: The subrange of the array to replace. The bounds of - /// the range must be valid indices in the array. - /// - newElements: An array whose contents to move into `self`. - /// - /// - Complexity: O(`self.count` + `newElements.count`) - @_alwaysEmitIntoClient - public mutating func replaceSubrange( - _ subrange: Range, - moving newElements: inout RigidArray, - ) { - unsafe newElements._unsafeEdit { buffer, count in - let source = buffer._extracting(first: count) - unsafe self.replaceSubrange(subrange, moving: source) - count = 0 - } - } -} - -extension RigidArray where Element: ~Copyable { - /// Replaces the specified range of elements by moving the elements of a - /// given array into their place, consuming it in the process. - /// - /// This method has the effect of removing the specified range of elements - /// from the array and inserting the new elements starting at the same - /// location. The number of new elements need not match the number of elements - /// being removed. - /// - /// If the capacity of the array isn't sufficient to accommodate the new - /// elements, then this method triggers a runtime error. - /// - /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. - /// - /// Likewise, if you pass a zero-length buffer as the `newElements` - /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. - /// - /// - Parameters - /// - subrange: The subrange of the array to replace. The bounds of - /// the range must be valid indices in the array. - /// - newElements: An array whose contents to move into `self`. - /// - /// - Complexity: O(`self.count` + `newElements.count`) - @_alwaysEmitIntoClient - public mutating func replaceSubrange( - _ subrange: Range, - consuming newElements: consuming RigidArray, - ) { - replaceSubrange(subrange, moving: &newElements) - } -} - -extension RigidArray { - /// Replaces the specified subrange of elements by copying the elements of - /// the given buffer pointer, which must be fully initialized. - /// - /// This method has the effect of removing the specified range of elements - /// from the array and inserting the new elements starting at the same - /// location. The number of new elements need not match the number of elements - /// being removed. - /// - /// If the capacity of the array isn't sufficient to accommodate the new - /// elements, then this method triggers a runtime error. - /// - /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. - /// - /// Likewise, if you pass a zero-length buffer as the `newElements` - /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. - /// - /// - Parameters: - /// - subrange: The subrange of the array to replace. The bounds of - /// the range must be valid indices in the array. - /// - newElements: The new elements to copy into the collection. - /// - /// - Complexity: O(`self.count` + `newElements.count`) - @inlinable - public mutating func replaceSubrange( - _ subrange: Range, - copying newElements: UnsafeBufferPointer - ) { - let gap = unsafe _gapForReplacement( - of: subrange, withNewCount: newElements.count) - let i = unsafe gap._initializePrefix(copying: newElements) - assert(i == gap.count) - } - - /// Replaces the specified subrange of elements by copying the elements of - /// the given buffer pointer, which must be fully initialized. - /// - /// This method has the effect of removing the specified range of elements - /// from the array and inserting the new elements starting at the same - /// location. The number of new elements need not match the number of elements - /// being removed. - /// - /// If the capacity of the array isn't sufficient to accommodate the new - /// elements, then this method triggers a runtime error. - /// - /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. - /// - /// Likewise, if you pass a zero-length buffer as the `newElements` - /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. - /// - /// - Parameters: - /// - subrange: The subrange of the array to replace. The bounds of - /// the range must be valid indices in the array. - /// - newElements: The new elements to copy into the collection. - /// - /// - Complexity: O(`self.count` + `newElements.count`) - @inlinable - public mutating func replaceSubrange( - _ subrange: Range, - copying newElements: UnsafeMutableBufferPointer - ) { - unsafe self.replaceSubrange( - subrange, - copying: UnsafeBufferPointer(newElements)) - } - - /// Replaces the specified subrange of elements by copying the elements of - /// the given span. - /// - /// This method has the effect of removing the specified range of elements - /// from the array and inserting the new elements starting at the same - /// location. The number of new elements need not match the number of elements - /// being removed. - /// - /// If the capacity of the array isn't sufficient to accommodate the new - /// elements, then this method triggers a runtime error. - /// - /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. - /// - /// Likewise, if you pass a zero-length span as the `newElements` - /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. - /// - /// - Parameters: - /// - subrange: The subrange of the array to replace. The bounds of - /// the range must be valid indices in the array. - /// - newElements: The new elements to copy into the collection. - /// - /// - Complexity: O(`self.count` + `newElements.count`) - @available(SwiftStdlib 5.0, *) - @inlinable - public mutating func replaceSubrange( - _ subrange: Range, - copying newElements: Span - ) { - unsafe newElements.withUnsafeBufferPointer { buffer in - unsafe self.replaceSubrange(subrange, copying: buffer) - } - } - - @inlinable - internal mutating func _replaceSubrange( - _ subrange: Range, - copyingCollection newElements: __owned some Collection, - newCount: Int - ) { - let gap = unsafe _gapForReplacement(of: subrange, withNewCount: newCount) - - let done: Void? = newElements.withContiguousStorageIfAvailable { buffer in - let i = unsafe gap._initializePrefix(copying: buffer) - precondition( - i == newCount, - "Broken Collection: count doesn't match contents") - } - if done != nil { return } - - var (it, copied) = unsafe newElements._copyContents(initializing: gap) - precondition( - it.next() == nil && copied == newCount, - "Broken Collection: count doesn't match contents") - } - - /// Replaces the specified subrange of elements by copying the elements of - /// the given collection. - /// - /// This method has the effect of removing the specified range of elements - /// from the array and inserting the new elements starting at the same - /// location. The number of new elements need not match the number of elements - /// being removed. - /// - /// If the capacity of the array isn't sufficient to accommodate the new - /// elements, then this method triggers a runtime error. - /// - /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. - /// - /// Likewise, if you pass a zero-length collection as the `newElements` - /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. - /// - /// - Parameters: - /// - subrange: The subrange of the array to replace. The bounds of - /// the range must be valid indices in the array. - /// - newElements: The new elements to copy into the collection. - /// - /// - Complexity: O(`self.count` + `newElements.count`) - @inlinable - @inline(__always) - public mutating func replaceSubrange( - _ subrange: Range, - copying newElements: __owned some Collection - ) { - _replaceSubrange( - subrange, copyingCollection: newElements, newCount: newElements.count) - } -} #endif diff --git a/Sources/BasicContainers/UniqueArray+Append.swift b/Sources/BasicContainers/UniqueArray+Append.swift new file mode 100644 index 00000000..36d96574 --- /dev/null +++ b/Sources/BasicContainers/UniqueArray+Append.swift @@ -0,0 +1,265 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + /// Adds an element to the end of the array. + /// + /// If the array does not have sufficient capacity to hold any more elements, + /// then this reallocates the array's storage to grow its capacity. + /// + /// - Parameter item: The element to append to the collection. + /// + /// - Complexity: O(1) when amortized over many invocations on the same array + @inlinable + public mutating func append(_ item: consuming Element) { + _ensureFreeCapacity(1) + _storage.append(item) + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + @_alwaysEmitIntoClient + public mutating func append( + count: Int, + initializingWith body: (inout OutputSpan) throws(E) -> Result + ) throws(E) -> Result { + _ensureFreeCapacity(count) + return try _storage.append(count: count, initializingWith: body) + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + /// Moves the elements of a buffer to the end of this array, leaving the + /// buffer uninitialized. + /// + /// If the array does not have sufficient capacity to hold all items in the + /// buffer, then this reallocates the array's storage to grow its capacity. + /// + /// - Parameters + /// - items: A fully initialized buffer whose contents to move into + /// the array. + /// + /// - Complexity: O(`items.count`) when amortized over many invocations on + /// the same array + @_alwaysEmitIntoClient + public mutating func append( + moving items: UnsafeMutableBufferPointer + ) { + _ensureFreeCapacity(items.count) + _storage.append(moving: items) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @_alwaysEmitIntoClient + public mutating func append( + moving items: inout InputSpan + ) { + _ensureFreeCapacity(items.count) + _storage.append(moving: &items) + } +#endif + + @_alwaysEmitIntoClient + public mutating func append( + moving items: inout OutputSpan + ) { + _ensureFreeCapacity(items.count) + _storage.append(moving: &items) + } + + /// 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. + /// + /// 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. + /// + /// - Parameters + /// - items: An array whose items to move to the end of this array. + /// + /// - Complexity: O(`items.count`) when amortized over many invocations on + /// the same array + @_alwaysEmitIntoClient + 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) + } +} + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + /// 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: 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 + +@available(SwiftStdlib 5.0, *) +extension UniqueArray { + /// Copies the elements of a buffer to the end of this array. + /// + /// If the array does not have sufficient capacity to hold enough elements, + /// then this reallocates the array's storage to extend its capacity. + /// + /// - Parameters + /// - newElements: A fully initialized buffer whose contents to copy into + /// the array. + /// + /// - Complexity: O(`newElements.count`) when amortized over many + /// invocations on the same array. + @_alwaysEmitIntoClient + public mutating func append( + copying newElements: UnsafeBufferPointer + ) { + _ensureFreeCapacity(newElements.count) + unsafe _storage.append(copying: newElements) + } + + /// Copies the elements of a buffer to the end of this array. + /// + /// If the array does not have sufficient capacity to hold enough elements, + /// then this reallocates the array's storage to extend its capacity. + /// + /// - Parameters + /// - newElements: A fully initialized buffer whose contents to copy into + /// the array. + /// + /// - Complexity: O(`newElements.count`) when amortized over many + /// invocations on the same array. + @_alwaysEmitIntoClient + public mutating func append( + copying newElements: UnsafeMutableBufferPointer + ) { + unsafe self.append(copying: UnsafeBufferPointer(newElements)) + } + + /// Copies the elements of a span to the end of this array. + /// + /// If the array does not have sufficient capacity to hold enough elements, + /// then this reallocates the array's storage to extend its capacity. + /// + /// - Parameters + /// - newElements: A span whose contents to copy into the array. + /// + /// - Complexity: O(`newElements.count`) when amortized over many + /// invocations on the same array. + @_alwaysEmitIntoClient + public mutating func append(copying newElements: Span) { + _ensureFreeCapacity(newElements.count) + _storage.append(copying: newElements) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Copies the elements of a container to the end of this array. + /// + /// If the array does not have sufficient capacity to hold enough elements, + /// then this reallocates the array's storage to extend its capacity. + /// + /// - Parameters + /// - newElements: A container whose contents to copy into the array. + /// + /// - Complexity: O(`newElements.count`), when amortized over many invocations + /// over the same array. + @_alwaysEmitIntoClient + @inline(__always) + public mutating func append< + Source: Container & ~Copyable & ~Escapable + >( + copying newElements: borrowing Source + ) { + _ensureFreeCapacity(newElements.count) + _storage._append(copyingContainer: newElements) + } + +#endif + + /// Copies the elements of a sequence to the end of this array. + /// + /// If the array does not have sufficient capacity to hold enough elements, + /// then this reallocates the array's storage to extend its capacity. This + /// reallocation can happen multiple times. + /// + /// - Parameters + /// - newElements: The new elements to copy into the array. + /// + /// - Complexity: O(*m*), where *m* is the length of `newElements`, when + /// amortized over many invocations over the same array. + @_alwaysEmitIntoClient + public mutating func append(copying newElements: some Sequence) { + let done: Void? = newElements.withContiguousStorageIfAvailable { buffer in + _ensureFreeCapacity(buffer.count) + unsafe _storage.append(copying: buffer) + return + } + if done != nil { return } + + _ensureFreeCapacity(newElements.underestimatedCount) + var it = _storage._append(prefixOf: newElements) + while let item = it.next() { + _ensureFreeCapacity(1) + _storage.append(item) + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Copies the elements of a container to the end of this array. + /// + /// If the array does not have sufficient capacity to hold enough elements, + /// then this reallocates the array's storage to extend its capacity. + /// + /// - Parameters + /// - newElements: A container whose contents to copy into the array. + /// + /// - Complexity: O(`newElements.count`), when amortized over many invocations + /// over the same array. + @_alwaysEmitIntoClient + @inline(__always) + public mutating func append< + Source: Container & Sequence + >(copying newElements: Source) { + _ensureFreeCapacity(newElements.count) + _storage._append(copyingContainer: newElements) + } +#endif + +} + +#endif diff --git a/Sources/BasicContainers/UniqueArray+Experimental.swift b/Sources/BasicContainers/UniqueArray+Experimental.swift index 5c55b284..1b807602 100644 --- a/Sources/BasicContainers/UniqueArray+Experimental.swift +++ b/Sources/BasicContainers/UniqueArray+Experimental.swift @@ -15,12 +15,10 @@ import InternalCollectionsUtilities import ContainersPreview #endif -#if compiler(>=6.2) -#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +#if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW -#if FIXME +#if false // TODO extension UniqueArray /*where Element: Copyable*/ { - @available(SwiftStdlib 6.2, *) @_alwaysEmitIntoClient @inline(__always) public init & ~Copyable & ~Escapable>( @@ -30,7 +28,6 @@ extension UniqueArray /*where Element: Copyable*/ { self.init(consuming: RigidArray(capacity: capacity, copying: contents)) } - @available(SwiftStdlib 6.2, *) @_alwaysEmitIntoClient @inline(__always) public init & Sequence>( @@ -42,7 +39,7 @@ extension UniqueArray /*where Element: Copyable*/ { } #endif -#if FIXME +#if false // TODO extension UniqueArray where Element: ~Copyable { @inlinable @inline(__always) @@ -53,22 +50,19 @@ extension UniqueArray where Element: ~Copyable { } #endif -#if FIXME -extension UniqueArray: RandomAccessContainer where Element: ~Copyable {} -#endif - -#if FIXME +#if false // TODO extension UniqueArray where Element: ~Copyable { @inlinable @_lifetime(&self) - public mutating func mutateElement(at index: Int) -> Inout { + public mutating func mutateElement(at index: Int) -> Mut { _storage.mutateElement(at: index) } } #endif +#if false // TODO +@available(SwiftStdlib 5.0, *) extension UniqueArray where Element: ~Copyable { - @available(SwiftStdlib 5.0, *) @_alwaysEmitIntoClient @_transparent internal mutating func _edit( @@ -83,8 +77,10 @@ extension UniqueArray where Element: ~Copyable { return _storage.reallocate(capacity: newCapacity, with: reallocatingMutation) } } +#endif -#if FIXME +#if false // TODO +@available(SwiftStdlib 5.0, *) extension UniqueArray where Element: ~Copyable { /// Removes all the elements that satisfy the given predicate. /// @@ -96,7 +92,6 @@ extension UniqueArray where Element: ~Copyable { /// whether the element should be removed from the array. /// /// - Complexity: O(`count`) - @available(SwiftStdlib 6.2, *) @_alwaysEmitIntoClient public mutating func removeAll( where shouldBeRemoved: (borrowing Element) throws(E) -> Bool @@ -108,258 +103,4 @@ extension UniqueArray where Element: ~Copyable { } #endif -extension UniqueArray where Element: ~Copyable { - @available(SwiftStdlib 5.0, *) - @_alwaysEmitIntoClient - public mutating func append( - moving items: inout InputSpan - ) { - _ensureFreeCapacity(items.count) - _storage.append(moving: &items) - } - - @available(SwiftStdlib 5.0, *) - @_alwaysEmitIntoClient - public mutating func append( - moving items: inout OutputSpan - ) { - _ensureFreeCapacity(items.count) - _storage.append(moving: &items) - } -} - -extension UniqueArray { -#if FIXME - public mutating func _appendContainer< - C: Container & ~Copyable & ~Escapable - >( - copying newElements: borrowing C - ) { - var i = newElements.startIndex - while true { - let span = newElements.span(after: &i) - if span.isEmpty { break } - self.append(copying: span) - } - } -#endif - -#if FIXME - /// Copies the elements of a container to the end of this array. - /// - /// If the array does not have sufficient capacity to hold enough elements, - /// then this reallocates the array's storage to extend its capacity. - /// - /// - Parameters - /// - newElements: A container whose contents to copy into the array. - /// - /// - Complexity: O(`newElements.count`), when amortized over many invocations - /// over the same array. - @available(SwiftStdlib 6.2, *) - @_alwaysEmitIntoClient - public mutating func append< - C: Container & ~Copyable & ~Escapable - >( - copying newElements: borrowing C - ) { - _appendContainer(copying: newElements) - } -#endif - -#if FIXME - /// Copies the elements of a container to the end of this array. - /// - /// If the array does not have sufficient capacity to hold enough elements, - /// then this reallocates the array's storage to extend its capacity. - /// - /// - Parameters - /// - newElements: A container whose contents to copy into the array. - /// - /// - Complexity: O(`newElements.count`), when amortized over many invocations - /// over the same array. - @available(SwiftStdlib 6.2, *) - @_alwaysEmitIntoClient - public mutating func append< - C: Container & Sequence - >( - copying newElements: borrowing C - ) { - _appendContainer(copying: newElements) - } -#endif -} - -#if FIXME -extension UniqueArray { - @available(SwiftStdlib 6.2, *) - @inlinable - internal mutating func _insertContainer< - C: Container & ~Copyable & ~Escapable - >( - copying newElements: borrowing C, at index: Int - ) { - // FIXME: Avoiding moving the subsequent elements twice. - let newCount = newElements.count - _ensureFreeCapacity(newCount) - _storage._insertContainer( - at: index, copying: newElements, newCount: newCount) - } - - /// 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. - /// - /// - 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`. - @available(SwiftStdlib 6.2, *) - @_alwaysEmitIntoClient - @inline(__always) - public mutating func insert< - C: Container & ~Copyable & ~Escapable - >( - copying newElements: borrowing C, at index: Int - ) { - _insertContainer(copying: newElements, at: index) - } - - /// 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. - /// - /// - 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`. - @available(SwiftStdlib 6.2, *) - @_alwaysEmitIntoClient - @inline(__always) - public mutating func insert< - C: Container & Collection - >( - copying newElements: borrowing C, at index: Int - ) { - _insertContainer(copying: newElements, at: index) - } - -} -#endif - -#if FIXME -extension UniqueArray { - @available(SwiftStdlib 6.2, *) - @inlinable - public mutating func _replaceSubrange< - C: Container & ~Copyable & ~Escapable - >( - _ subrange: Range, - copyingContainer newElements: borrowing C - ) { - // FIXME: Avoiding moving the subsequent elements twice. - let c = newElements.count - _ensureFreeCapacity(c) - _storage._replaceSubrange( - subrange, copyingContainer: newElements, newCount: c) - } - - /// Replaces the specified subrange of elements by copying the elements of - /// the given container. - /// - /// This method has the effect of removing the specified range of elements - /// from the array and inserting the new elements starting at the same location. - /// The number of new elements need not match the number of elements being - /// removed. - /// - /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. - /// - /// Likewise, if you pass a zero-length container as the `newElements` - /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. - /// - /// - Parameters: - /// - subrange: The subrange of the array to replace. The bounds of - /// the range must be valid indices in the array. - /// - newElements: The new elements to copy into the collection. - /// - /// - Complexity: O(*n* + *m*), where *n* is count of this array and - /// *m* is the count of `newElements`. - @available(SwiftStdlib 6.2, *) - @inlinable - @inline(__always) - public mutating func replaceSubrange< - C: Container & ~Copyable & ~Escapable - >( - _ subrange: Range, - copying newElements: borrowing C - ) { - _replaceSubrange(subrange, copyingContainer: newElements) - } - - /// Replaces the specified subrange of elements by copying the elements of - /// the given container. - /// - /// This method has the effect of removing the specified range of elements - /// from the array and inserting the new elements starting at the same location. - /// The number of new elements need not match the number of elements being - /// removed. - /// - /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. - /// - /// Likewise, if you pass a zero-length container as the `newElements` - /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. - /// - /// - Parameters: - /// - subrange: The subrange of the array to replace. The bounds of - /// the range must be valid indices in the array. - /// - newElements: The new elements to copy into the collection. - /// - /// - Complexity: O(*n* + *m*), where *n* is count of this array and - /// *m* is the count of `newElements`. - @available(SwiftStdlib 6.2, *) - @inlinable - @inline(__always) - public mutating func replaceSubrange< - C: Container & Collection - >( - _ subrange: Range, - copying newElements: borrowing C - ) { - _replaceSubrange(subrange, copyingContainer: newElements) - } -} -#endif - -#endif #endif diff --git a/Sources/BasicContainers/UniqueArray+Initializers.swift b/Sources/BasicContainers/UniqueArray+Initializers.swift new file mode 100644 index 00000000..5a2dfe3f --- /dev/null +++ b/Sources/BasicContainers/UniqueArray+Initializers.swift @@ -0,0 +1,91 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + @inlinable + public init( + capacity: Int, + initializingWith body: (inout OutputSpan) throws(E) -> Void + ) throws(E) { + self.init(capacity: capacity) + try edit(body) + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueArray /*where Element: Copyable*/ { + /// Creates a new array containing the specified number of a single, + /// repeated value. + /// + /// - Parameters: + /// - repeatedValue: The element to repeat. + /// - count: The number of times to repeat the value passed in the + /// `repeating` parameter. `count` must be zero or greater. + public init(repeating repeatedValue: Element, count: Int) { + self.init(consuming: RigidArray(repeating: repeatedValue, count: count)) + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + @inlinable + public init(consuming storage: consuming RigidArray) { + self._storage = storage + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueArray /*where Element: Copyable*/ { +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @_alwaysEmitIntoClient + @inline(__always) + public init & ~Copyable & ~Escapable>( + capacity: Int? = nil, + copying contents: borrowing Source + ) { + self.init(capacity: capacity ?? 0) + self.append(copying: contents) + } +#endif + + @_alwaysEmitIntoClient + @inline(__always) + public init( + capacity: Int? = nil, + copying contents: some Sequence + ) { + self.init(capacity: capacity ?? 0) + self.append(copying: contents) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @_alwaysEmitIntoClient + @inline(__always) + public init & Sequence>( + capacity: Int? = nil, + copying contents: Source + ) { + self.init(capacity: capacity ?? 0) + self.append(copying: contents) + } +#endif + +} + +#endif diff --git a/Sources/BasicContainers/UniqueArray+Insertions.swift b/Sources/BasicContainers/UniqueArray+Insertions.swift new file mode 100644 index 00000000..62d4f20e --- /dev/null +++ b/Sources/BasicContainers/UniqueArray+Insertions.swift @@ -0,0 +1,339 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + /// Inserts a new element into the array at the specified position. + /// + /// If the array does not have sufficient capacity to hold any more elements, + /// then this reallocates storage to extend its capacity. + /// + /// The new element is inserted before the element currently at the specified + /// index. If you pass the array's `endIndex` as the `index` parameter, then + /// the new element is appended to the container. + /// + /// All existing elements at or following the specified position are moved to + /// make room for the new item. + /// + /// - Parameter item: The new element to insert into the array. + /// - Parameter i: The position at which to insert the new element. + /// `index` must be a valid index in the array. + /// + /// - Complexity: O(`self.count`) + @inlinable + public mutating func insert(_ item: consuming Element, at index: Int) { + precondition(index >= 0 && index <= count) + // FIXME: Avoid moving the subsequent elements twice. + _ensureFreeCapacity(1) + _storage.insert(item, at: index) + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + @inlinable + public mutating func insert( + count: Int, + at index: Int, + initializingWith body: (inout OutputSpan) -> Result + ) -> Result { + // FIXME: This does not allow `body` to throw, to prevent having to move the tail twice. Is that okay? + _ensureFreeCapacity(count) + return _storage.insert(count: count, at: index, initializingWith: body) + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + /// Moves the elements of a fully initialized buffer into this array, + /// starting at the specified position, and leaving the buffer + /// uninitialized. + /// + /// If the array does not have sufficient capacity to hold all elements, + /// then this reallocates storage to extend its capacity. + /// + /// - Parameters + /// - items: A fully initialized buffer whose contents to move into + /// the array. + /// + /// - Complexity: O(`self.count` + `items.count`) + @_alwaysEmitIntoClient + public mutating func insert( + moving items: UnsafeMutableBufferPointer, + at index: Int + ) { + // FIXME: Avoid moving the subsequent elements twice. + _ensureFreeCapacity(items.count) + _storage.insert(moving: items, at: index) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @_alwaysEmitIntoClient + public mutating func insert( + moving items: inout InputSpan, + at index: Int + ) { + _ensureFreeCapacity(items.count) + _storage.insert(moving: &items, at: index) + } +#endif + + @_alwaysEmitIntoClient + public mutating func insert( + moving items: inout OutputSpan, + at index: Int + ) { + _ensureFreeCapacity(items.count) + _storage.insert(moving: &items, at: index) + } + + /// 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 + /// storage capacity. + /// + /// If the array does not have sufficient capacity to hold all elements, + /// then this reallocates storage to extend its capacity. + /// + /// - Parameters + /// - items: An array whose contents to move into `self`. + /// + /// - Complexity: O(`self.count` + `items.count`) + @_alwaysEmitIntoClient + public mutating func insert( + moving items: inout RigidArray, + at index: Int + ) { + // FIXME: Avoid moving the subsequent elements twice. + _ensureFreeCapacity(items.count) + _storage.insert(moving: &items, at: index) + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + /// 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. + /// + /// - 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: Avoid moving the subsequent elements twice. + _ensureFreeCapacity(items.count) + _storage.insert(consuming: items, at: index) + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueArray { + /// Copyies the elements of a fully initialized buffer pointer 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. + /// + /// - Parameters + /// - newElements: The new elements to insert into the array. The buffer + /// must be fully initialized. + /// - 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`) + @inlinable + public mutating func insert( + copying newElements: UnsafeBufferPointer, at index: Int + ) { + // FIXME: Avoid moving the subsequent elements twice. + _ensureFreeCapacity(newElements.count) + unsafe _storage.insert(copying: newElements, at: index) + } + + /// Copyies the elements of a fully initialized buffer pointer 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. + /// + /// - Parameters + /// - newElements: The new elements to insert into the array. The buffer + /// must be fully initialized. + /// - 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`) + @inlinable + public mutating func insert( + copying newElements: UnsafeMutableBufferPointer, + at index: Int + ) { + unsafe self.insert(copying: UnsafeBufferPointer(newElements), at: index) + } + + /// Copies the elements of a span 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. + /// + /// - 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`) + @inlinable + public mutating func insert( + copying newElements: Span, at index: Int + ) { + // FIXME: Avoid moving the subsequent elements twice. + _ensureFreeCapacity(newElements.count) + _storage.insert(copying: newElements, at: index) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// 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. + /// + /// - 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. + /// + /// 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. + /// + /// - 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`) + @inlinable + public mutating func insert( + copying newElements: some Collection, at index: Int + ) { + // FIXME: Avoid moving the subsequent elements twice. + let newCount = newElements.count + _ensureFreeCapacity(newCount) + _storage._insertCollection( + at: index, copying: newElements, newCount: newCount) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// 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. + /// + /// - 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+Removals.swift b/Sources/BasicContainers/UniqueArray+Removals.swift new file mode 100644 index 00000000..e84e9a8f --- /dev/null +++ b/Sources/BasicContainers/UniqueArray+Removals.swift @@ -0,0 +1,149 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + /// Removes all elements from the array, optionally preserving its + /// allocated capacity. + /// + /// - Complexity: O(*n*), where *n* is the original count of the array. + @inlinable + @inline(__always) + public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { + if keepCapacity { + _storage.removeAll() + } else { + _storage = RigidArray(capacity: 0) + } + } + + /// Removes and returns the last element of the array. + /// + /// The array must not be empty. + /// + /// - Returns: The last element of the original array. + /// + /// - Complexity: O(1) + @inlinable + @inline(__always) + @discardableResult + public mutating func removeLast() -> Element { + _storage.removeLast() + } + + /// Removes and discards the specified number of elements from the end of the + /// array. + /// + /// Attempting to remove more elements than exist in the array triggers a + /// runtime error. + /// + /// - Parameter k: The number of elements to remove from the array. + /// `k` must be greater than or equal to zero and must not exceed + /// the count of the array. + /// + /// - Complexity: O(`k`) + @inlinable + public mutating func removeLast(_ k: Int) { + _storage.removeLast(k) + } + + /// Removes and returns the element at the specified position. + /// + /// All the elements following the specified position are moved to close the + /// gap. + /// + /// - Parameter i: The position of the element to remove. `index` must be + /// a valid index of the array that is not equal to the end index. + /// - Returns: The removed element. + /// + /// - Complexity: O(`self.count`) + @inlinable + @inline(__always) + @discardableResult + public mutating func remove(at index: Int) -> Element { + _storage.remove(at: index) + } + + /// Removes the specified subrange of elements from the array. + /// + /// All the elements following the specified subrange are moved to close the + /// resulting gap. + /// + /// - Parameter bounds: The subrange of the array to remove. The bounds + /// of the range must be valid indices of the array. + /// + /// - Complexity: O(`self.count`) + @inlinable + public mutating func removeSubrange(_ bounds: Range) { + _storage.removeSubrange(bounds) + } + + /// Removes the specified subrange of elements from the array. + /// + /// - Parameter bounds: The subrange of the array to remove. The bounds + /// of the range must be valid indices of the array. + /// + /// - Complexity: O(`self.count`) + @_alwaysEmitIntoClient + public mutating func removeSubrange(_ bounds: some RangeExpression) { + // FIXME: Remove this in favor of a standard algorithm. + removeSubrange(bounds.relative(to: indices)) + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + /// 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; + /// otherwise, `nil`. + /// + /// - Complexity: O(1) + @_alwaysEmitIntoClient + public mutating func popLast() -> Element? { + if isEmpty { return nil } + return removeLast() + } +} + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + @_lifetime(&self) + @_alwaysEmitIntoClient + public mutating func consumeAll() -> InputSpan { + _storage.consumeAll() + } + + @_lifetime(&self) + @_alwaysEmitIntoClient + public mutating func consumeLast(_ count: Int) -> InputSpan { + _storage.consumeLast(count) + } + + @_alwaysEmitIntoClient + public mutating func consumeSubrange( + _ bounds: Range, + consumingWith body: (inout InputSpan) throws(E) -> Result + ) throws(E) -> Result { + try _storage.consumeSubrange(bounds, consumingWith: body) + } +} +#endif + +#endif diff --git a/Sources/BasicContainers/UniqueArray+Replacements.swift b/Sources/BasicContainers/UniqueArray+Replacements.swift new file mode 100644 index 00000000..e4f72815 --- /dev/null +++ b/Sources/BasicContainers/UniqueArray+Replacements.swift @@ -0,0 +1,399 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + @inlinable + public mutating func replaceSubrange( + _ subrange: Range, + newCount: Int, + initializingWith body: (inout OutputSpan) -> Result + ) -> Result { + // FIXME: Should we allow throwing (and a partially filled output span)? + // FIXME: Should we have a version of this with two closures, to allow custom-consuming the old items? + // replaceSubrange(5..<10, newCount: 3, consumingWith: {...}, initializingWith: {...}) + // FIXME: Avoid moving the subsequent elements twice. + _ensureFreeCapacity(newCount - subrange.count) + return _storage.replaceSubrange( + subrange, newCount: newCount, initializingWith: body) + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + /// Replaces the specified range of elements by moving the elements of a + /// fully initialized buffer into their place. On return, the buffer is left + /// in an uninitialized state. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the array does not have sufficient capacity to hold enough elements, + /// then this reallocates the array's storage to extend its capacity. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: A fully initialized buffer whose contents to move into + /// the array. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + moving newElements: UnsafeMutableBufferPointer, + ) { + // FIXME: Avoid moving the subsequent elements twice. + _ensureFreeCapacity(newElements.count - subrange.count) + _storage.replaceSubrange(subrange, moving: newElements) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + moving items: inout InputSpan + ) { + // FIXME: Avoid moving the subsequent elements twice. + _ensureFreeCapacity(items.count - subrange.count) + _storage.replaceSubrange(subrange, moving: &items) + } +#endif + + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + moving items: inout OutputSpan + ) { + // FIXME: Avoid moving the subsequent elements twice. + _ensureFreeCapacity(items.count - subrange.count) + _storage.replaceSubrange(subrange, moving: &items) + } + + /// Replaces the specified range of elements by moving the elements of a + /// another array into their place. On return, the source array + /// becomes empty, but it is not destroyed, and it preserves its original + /// storage capacity. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the array does not have sufficient capacity to hold enough elements, + /// then this reallocates the array's storage to extend its capacity. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: An array whose contents to move into `self`. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + moving newElements: inout RigidArray, + ) { + // FIXME: Avoid moving the subsequent elements twice. + _ensureFreeCapacity(newElements.count - subrange.count) + _storage.replaceSubrange(subrange, moving: &newElements) + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + /// Replaces the specified range of elements by moving the elements of a + /// given array into their place, consuming it in the process. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the array does not have sufficient capacity to hold enough elements, + /// then this reallocates the array's storage to extend its capacity. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: An array whose contents to move into `self`. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + consuming newElements: consuming RigidArray, + ) { + replaceSubrange(subrange, moving: &newElements) + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueArray { + /// Replaces the specified subrange of elements by copying the elements of + /// the given buffer pointer, which must be fully initialized. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same location. + /// The number of new elements need not match the number of elements being + /// removed. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: The new elements to copy into the collection. + /// + /// - Complexity: O(*n* + *m*), where *n* is count of this array and + /// *m* is the count of `newElements`. + @inlinable + @inline(__always) + public mutating func replaceSubrange( + _ subrange: Range, + copying newElements: UnsafeBufferPointer + ) { + // FIXME: Avoid moving the subsequent elements twice. + _ensureFreeCapacity(newElements.count) + unsafe _storage.replaceSubrange(subrange, copying: newElements) + } + + /// Replaces the specified subrange of elements by copying the elements of + /// the given buffer pointer, which must be fully initialized. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same location. + /// The number of new elements need not match the number of elements being + /// removed. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: The new elements to copy into the collection. + /// + /// - Complexity: O(*n* + *m*), where *n* is count of this array and + /// *m* is the count of `newElements`. + @inlinable + @inline(__always) + public mutating func replaceSubrange( + _ subrange: Range, + copying newElements: UnsafeMutableBufferPointer + ) { + unsafe self.replaceSubrange( + subrange, copying: UnsafeBufferPointer(newElements)) + } + + /// Replaces the specified subrange of elements by copying the elements of + /// the given span. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same location. + /// The number of new elements need not match the number of elements being + /// removed. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length span as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: The new elements to copy into the collection. + /// + /// - Complexity: O(*n* + *m*), where *n* is count of this array and + /// *m* is the count of `newElements`. + @inlinable + public mutating func replaceSubrange( + _ subrange: Range, + copying newElements: Span + ) { + // FIXME: Avoid moving the subsequent elements twice. + _ensureFreeCapacity(newElements.count) + _storage.replaceSubrange(subrange, copying: newElements) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Replaces the specified subrange of elements by copying the elements of + /// the given container. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same location. + /// The number of new elements need not match the number of elements being + /// removed. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length container as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: The new elements to copy into the collection. + /// + /// - Complexity: O(*n* + *m*), where *n* is count of this array and + /// *m* is the count of `newElements`. + @inlinable + @inline(__always) + public mutating func replaceSubrange< + C: Container & ~Copyable & ~Escapable + >( + _ subrange: Range, + copying newElements: borrowing C + ) { + // FIXME: Avoid moving the subsequent elements twice. + let c = newElements.count + _ensureFreeCapacity(c - subrange.count) + _storage._replaceSubrange( + subrange, copyingContainer: newElements, newCount: c) + } +#endif + + /// Replaces the specified subrange of elements by copying the elements of + /// the given collection. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same location. + /// The number of new elements need not match the number of elements being + /// removed. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length collection as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: The new elements to copy into the collection. + /// + /// - Complexity: O(*n* + *m*), where *n* is count of this array and + /// *m* is the count of `newElements`. + @inlinable + @inline(__always) + public mutating func replaceSubrange( + _ subrange: Range, + copying newElements: __owned some Collection + ) { + // FIXME: Avoid moving the subsequent elements twice. + let c = newElements.count + _ensureFreeCapacity(c) + _storage._replaceSubrange( + subrange, copyingCollection: newElements, newCount: c) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Replaces the specified subrange of elements by copying the elements of + /// the given container. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same location. + /// The number of new elements need not match the number of elements being + /// removed. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length container as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: The new elements to copy into the collection. + /// + /// - Complexity: O(*n* + *m*), where *n* is count of this array and + /// *m* is the count of `newElements`. + @inlinable + @inline(__always) + public mutating func replaceSubrange< + C: Container & Collection + >( + _ subrange: Range, + copying newElements: borrowing C + ) { + // FIXME: Avoid moving the subsequent elements twice. + let c = newElements.count + _ensureFreeCapacity(c - subrange.count) + _storage._replaceSubrange( + subrange, copyingContainer: newElements, newCount: c) + } +#endif +} +#endif diff --git a/Sources/BasicContainers/UniqueArray.swift b/Sources/BasicContainers/UniqueArray.swift index 891c9a13..7711122c 100644 --- a/Sources/BasicContainers/UniqueArray.swift +++ b/Sources/BasicContainers/UniqueArray.swift @@ -11,6 +11,7 @@ #if !COLLECTIONS_SINGLE_MODULE import InternalCollectionsUtilities +import ContainersPreview #endif #if compiler(<6.2) @@ -56,70 +57,29 @@ public struct UniqueArray: ~Copyable { /// resizing array types as a matter of policy. The type `RigidArray` provides /// a fixed-capacity array variant that caters specifically for these use cases, /// trading ease-of-use for more consistent/predictable execution. +@available(SwiftStdlib 5.0, *) @frozen public struct UniqueArray: ~Copyable { @usableFromInline internal var _storage: RigidArray + @inlinable + public init(capacity: Int) { + _storage = .init(capacity: capacity) + } + @inlinable public init() { _storage = .init(capacity: 0) } } + +@available(SwiftStdlib 5.0, *) extension UniqueArray: Sendable where Element: Sendable & ~Copyable {} -//MARK: - Initializers - -extension UniqueArray where Element: ~Copyable { - @inlinable - public init(capacity: Int) { - _storage = .init(capacity: capacity) - } -} - -extension UniqueArray where Element: ~Copyable { - @available(SwiftStdlib 5.0, *) - @inlinable - public init( - capacity: Int, - initializedWith body: (inout OutputSpan) throws(E) -> Void - ) throws(E) { - self.init(capacity: capacity) - try edit(body) - } -} - -extension UniqueArray where Element: ~Copyable { - @inlinable - public init(consuming storage: consuming RigidArray) { - self._storage = storage - } -} - -extension UniqueArray /*where Element: Copyable*/ { - /// Creates a new array containing the specified number of a single, - /// repeated value. - /// - /// - Parameters: - /// - repeatedValue: The element to repeat. - /// - count: The number of times to repeat the value passed in the - /// `repeating` parameter. `count` must be zero or greater. - public init(repeating repeatedValue: Element, count: Int) { - self.init(consuming: RigidArray(repeating: repeatedValue, count: count)) - } -} - -extension UniqueArray /*where Element: Copyable*/ { - @_alwaysEmitIntoClient - @inline(__always) - public init(capacity: Int? = nil, copying contents: some Sequence) { - self.init(capacity: capacity ?? 0) - self.append(copying: contents) - } -} - //MARK: - Basics +@available(SwiftStdlib 5.0, *) extension UniqueArray where Element: ~Copyable { @inlinable @inline(__always) @@ -134,8 +94,8 @@ extension UniqueArray where Element: ~Copyable { //MARK: - Span creation +@available(SwiftStdlib 5.0, *) extension UniqueArray where Element: ~Copyable { - @available(SwiftStdlib 5.0, *) public var span: Span { @_lifetime(borrow self) @inlinable @@ -154,6 +114,7 @@ extension UniqueArray where Element: ~Copyable { } } +@available(SwiftStdlib 5.0, *) extension UniqueArray where Element: ~Copyable { /// Arbitrarily edit the storage underlying this array by invoking a /// user-supplied closure with a mutable `OutputSpan` view over it. @@ -172,7 +133,6 @@ extension UniqueArray where Element: ~Copyable { /// - Returns: This method returns the result of its function argument. /// - Complexity: Adds O(1) overhead to the complexity of the function /// argument. - @available(SwiftStdlib 5.0, *) @inlinable @inline(__always) public mutating func edit( _ body: (inout OutputSpan) throws(E) -> R @@ -181,11 +141,10 @@ extension UniqueArray where Element: ~Copyable { } } -//MARK: - Random-access & mutable container primitives +//MARK: - Container primitives +@available(SwiftStdlib 5.0, *) extension UniqueArray where Element: ~Copyable { - public typealias Index = Int - @inlinable @inline(__always) public var isEmpty: Bool { _storage.isEmpty } @@ -193,6 +152,24 @@ extension UniqueArray where Element: ~Copyable { @inlinable @inline(__always) public var count: Int { _storage.count } +} + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +@available(SwiftStdlib 5.0, *) +extension UniqueArray: Container where Element: ~Copyable { + public typealias BorrowIterator = RigidArray.BorrowIterator + + @_alwaysEmitIntoClient + @inline(__always) + public func startBorrowIteration() -> Span { + self._storage.startBorrowIteration() + } +} +#endif + +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + public typealias Index = Int @inlinable @inline(__always) @@ -217,6 +194,7 @@ extension UniqueArray where Element: ~Copyable { } } +@available(SwiftStdlib 5.0, *) extension UniqueArray where Element: ~Copyable { @inlinable public mutating func swapAt(_ i: Int, _ j: Int) { @@ -224,15 +202,14 @@ extension UniqueArray where Element: ~Copyable { } } +@available(SwiftStdlib 5.0, *) extension UniqueArray where Element: ~Copyable { - @available(SwiftStdlib 5.0, *) @inlinable @_lifetime(borrow self) public func span(after index: inout Int) -> Span { _storage.span(after: &index) } - @available(SwiftStdlib 5.0, *) @inlinable @_lifetime(borrow self) public func span(before index: inout Int) -> Span { @@ -240,8 +217,8 @@ extension UniqueArray where Element: ~Copyable { } } +@available(SwiftStdlib 5.0, *) extension UniqueArray where Element: ~Copyable { - @available(SwiftStdlib 5.0, *) @_lifetime(&self) public mutating func mutableSpan( after index: inout Int @@ -249,7 +226,6 @@ extension UniqueArray where Element: ~Copyable { _storage.mutableSpan(after: &index) } - @available(SwiftStdlib 5.0, *) @_lifetime(&self) public mutating func mutableSpan( before index: inout Int @@ -269,6 +245,7 @@ internal func _growDynamicArrayCapacity(_ capacity: Int) -> Int { return Int(bitPattern: c) } +@available(SwiftStdlib 5.0, *) extension UniqueArray where Element: ~Copyable { @inlinable @inline(never) public mutating func reallocate(capacity: Int) { @@ -302,749 +279,4 @@ extension UniqueArray where Element: ~Copyable { } } -//MARK: - Removal operations - -extension UniqueArray where Element: ~Copyable { - /// Removes all elements from the array, optionally preserving its - /// allocated capacity. - /// - /// - Complexity: O(*n*), where *n* is the original count of the array. - @inlinable - @inline(__always) - public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { - if keepCapacity { - _storage.removeAll() - } else { - _storage = RigidArray(capacity: 0) - } - } - - /// Removes and returns the last element of the array. - /// - /// The array must not be empty. - /// - /// - Returns: The last element of the original array. - /// - /// - Complexity: O(1) - @inlinable - @inline(__always) - @discardableResult - public mutating func removeLast() -> Element { - _storage.removeLast() - } - - /// Removes and discards the specified number of elements from the end of the - /// array. - /// - /// Attempting to remove more elements than exist in the array triggers a - /// runtime error. - /// - /// - Parameter k: The number of elements to remove from the array. - /// `k` must be greater than or equal to zero and must not exceed - /// the count of the array. - /// - /// - Complexity: O(`k`) - @inlinable - public mutating func removeLast(_ k: Int) { - _storage.removeLast(k) - } - - /// Removes and returns the element at the specified position. - /// - /// All the elements following the specified position are moved to close the - /// gap. - /// - /// - Parameter i: The position of the element to remove. `index` must be - /// a valid index of the array that is not equal to the end index. - /// - Returns: The removed element. - /// - /// - Complexity: O(`self.count`) - @inlinable - @inline(__always) - @discardableResult - public mutating func remove(at index: Int) -> Element { - _storage.remove(at: index) - } - - /// Removes the specified subrange of elements from the array. - /// - /// All the elements following the specified subrange are moved to close the - /// resulting gap. - /// - /// - Parameter bounds: The subrange of the array to remove. The bounds - /// of the range must be valid indices of the array. - /// - /// - Complexity: O(`self.count`) - @inlinable - public mutating func removeSubrange(_ bounds: Range) { - _storage.removeSubrange(bounds) - } - - /// Removes the specified subrange of elements from the array. - /// - /// - Parameter bounds: The subrange of the array to remove. The bounds - /// of the range must be valid indices of the array. - /// - /// - Complexity: O(`self.count`) - @_alwaysEmitIntoClient - public mutating func removeSubrange(_ bounds: some RangeExpression) { - // FIXME: Remove this in favor of a standard algorithm. - removeSubrange(bounds.relative(to: indices)) - } -} - -extension UniqueArray where Element: ~Copyable { - /// 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; - /// otherwise, `nil`. - /// - /// - Complexity: O(1) - @_alwaysEmitIntoClient - public mutating func popLast() -> Element? { - if isEmpty { return nil } - return removeLast() - } -} - -//MARK: - Append operations - -extension UniqueArray where Element: ~Copyable { - /// Adds an element to the end of the array. - /// - /// If the array does not have sufficient capacity to hold any more elements, - /// then this reallocates the array's storage to grow its capacity. - /// - /// - Parameter item: The element to append to the collection. - /// - /// - Complexity: O(1) when amortized over many invocations on the same array - @inlinable - public mutating func append(_ item: consuming Element) { - _ensureFreeCapacity(1) - _storage.append(item) - } -} - -extension UniqueArray where Element: ~Copyable { - /// Moves the elements of a buffer to the end of this array, leaving the - /// buffer uninitialized. - /// - /// If the array does not have sufficient capacity to hold all items in the - /// buffer, then this reallocates the array's storage to grow its capacity. - /// - /// - Parameters - /// - items: A fully initialized buffer whose contents to move into - /// the array. - /// - /// - Complexity: O(`items.count`) when amortized over many invocations on - /// the same array - @_alwaysEmitIntoClient - public mutating func append( - moving items: UnsafeMutableBufferPointer - ) { - _ensureFreeCapacity(items.count) - _storage.append(moving: items) - } - - /// 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. - /// - /// 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. - /// - /// - Parameters - /// - items: An array whose items to move to the end of this array. - /// - /// - Complexity: O(`items.count`) when amortized over many invocations on - /// the same array - @_alwaysEmitIntoClient - 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) - } -} - -extension UniqueArray where Element: ~Copyable { - /// 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: 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) - } -} - -extension UniqueArray { - /// Copies the elements of a buffer to the end of this array. - /// - /// If the array does not have sufficient capacity to hold enough elements, - /// then this reallocates the array's storage to extend its capacity. - /// - /// - Parameters - /// - newElements: A fully initialized buffer whose contents to copy into - /// the array. - /// - /// - Complexity: O(`newElements.count`) when amortized over many - /// invocations on the same array. - @_alwaysEmitIntoClient - public mutating func append( - copying newElements: UnsafeBufferPointer - ) { - _ensureFreeCapacity(newElements.count) - unsafe _storage.append(copying: newElements) - } - - /// Copies the elements of a buffer to the end of this array. - /// - /// If the array does not have sufficient capacity to hold enough elements, - /// then this reallocates the array's storage to extend its capacity. - /// - /// - Parameters - /// - newElements: A fully initialized buffer whose contents to copy into - /// the array. - /// - /// - Complexity: O(`newElements.count`) when amortized over many - /// invocations on the same array. - @_alwaysEmitIntoClient - public mutating func append( - copying newElements: UnsafeMutableBufferPointer - ) { - unsafe self.append(copying: UnsafeBufferPointer(newElements)) - } - - /// Copies the elements of a span to the end of this array. - /// - /// If the array does not have sufficient capacity to hold enough elements, - /// then this reallocates the array's storage to extend its capacity. - /// - /// - Parameters - /// - newElements: A span whose contents to copy into the array. - /// - /// - Complexity: O(`newElements.count`) when amortized over many - /// invocations on the same array. - @available(SwiftStdlib 6.2, *) - @_alwaysEmitIntoClient - public mutating func append(copying newElements: Span) { - _ensureFreeCapacity(newElements.count) - _storage.append(copying: newElements) - } - - /// Copies the elements of a sequence to the end of this array. - /// - /// If the array does not have sufficient capacity to hold enough elements, - /// then this reallocates the array's storage to extend its capacity. This - /// reallocation can happen multiple times. - /// - /// - Parameters - /// - newElements: The new elements to copy into the array. - /// - /// - Complexity: O(*m*), where *m* is the length of `newElements`, when - /// amortized over many invocations over the same array. - @_alwaysEmitIntoClient - public mutating func append(copying newElements: some Sequence) { - let done: Void? = newElements.withContiguousStorageIfAvailable { buffer in - _ensureFreeCapacity(buffer.count) - unsafe _storage.append(copying: buffer) - return - } - if done != nil { return } - - _ensureFreeCapacity(newElements.underestimatedCount) - var it = _storage._append(prefixOf: newElements) - while let item = it.next() { - _ensureFreeCapacity(1) - _storage.append(item) - } - } -} - -//MARK: - Insert operations - -extension UniqueArray where Element: ~Copyable { - /// Inserts a new element into the array at the specified position. - /// - /// If the array does not have sufficient capacity to hold any more elements, - /// then this reallocates storage to extend its capacity. - /// - /// The new element is inserted before the element currently at the specified - /// index. If you pass the array's `endIndex` as the `index` parameter, then - /// the new element is appended to the container. - /// - /// All existing elements at or following the specified position are moved to - /// make room for the new item. - /// - /// - Parameter item: The new element to insert into the array. - /// - Parameter i: The position at which to insert the new element. - /// `index` must be a valid index in the array. - /// - /// - Complexity: O(`self.count`) - @inlinable - public mutating func insert(_ item: consuming Element, at index: Int) { - precondition(index >= 0 && index <= count) - // FIXME: Avoiding moving the subsequent elements twice. - _ensureFreeCapacity(1) - _storage.insert(item, at: index) - } -} - -extension UniqueArray where Element: ~Copyable { - /// Moves the elements of a fully initialized buffer into this array, - /// starting at the specified position, and leaving the buffer - /// uninitialized. - /// - /// If the array does not have sufficient capacity to hold all elements, - /// then this reallocates storage to extend its capacity. - /// - /// - Parameters - /// - items: A fully initialized buffer whose contents to move into - /// the array. - /// - /// - Complexity: O(`self.count` + `items.count`) - @_alwaysEmitIntoClient - public mutating func insert( - moving items: UnsafeMutableBufferPointer, - at index: Int - ) { - // FIXME: Avoiding moving the subsequent elements twice. - _ensureFreeCapacity(items.count) - _storage.insert(moving: items, at: index) - } - - /// 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 - /// storage capacity. - /// - /// If the array does not have sufficient capacity to hold all elements, - /// then this reallocates storage to extend its capacity. - /// - /// - Parameters - /// - items: An array whose contents to move into `self`. - /// - /// - Complexity: O(`self.count` + `items.count`) - @_alwaysEmitIntoClient - public mutating func insert( - moving items: inout RigidArray, - at index: Int - ) { - // FIXME: Avoiding moving the subsequent elements twice. - _ensureFreeCapacity(items.count) - _storage.insert(moving: &items, at: index) - } -} - -extension UniqueArray where Element: ~Copyable { - /// 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. - /// - /// - 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: Avoiding moving the subsequent elements twice. - _ensureFreeCapacity(items.count) - _storage.insert(consuming: items, at: index) - } -} - -extension UniqueArray { - /// Copyies the elements of a fully initialized buffer pointer 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. - /// - /// - Parameters - /// - newElements: The new elements to insert into the array. The buffer - /// must be fully initialized. - /// - 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`) - @inlinable - public mutating func insert( - copying newElements: UnsafeBufferPointer, at index: Int - ) { - // FIXME: Avoiding moving the subsequent elements twice. - _ensureFreeCapacity(newElements.count) - unsafe _storage.insert(copying: newElements, at: index) - } - - /// Copyies the elements of a fully initialized buffer pointer 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. - /// - /// - Parameters - /// - newElements: The new elements to insert into the array. The buffer - /// must be fully initialized. - /// - 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`) - @inlinable - public mutating func insert( - copying newElements: UnsafeMutableBufferPointer, - at index: Int - ) { - unsafe self.insert(copying: UnsafeBufferPointer(newElements), at: index) - } - - /// Copies the elements of a span 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. - /// - /// - 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`) - @available(SwiftStdlib 6.2, *) - @inlinable - public mutating func insert( - copying newElements: Span, at index: Int - ) { - // FIXME: Avoiding moving the subsequent elements twice. - _ensureFreeCapacity(newElements.count) - _storage.insert(copying: newElements, at: index) - } - - /// Copies the elements of a collection 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. - /// - /// - 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`) - @inlinable - public mutating func insert( - copying newElements: some Collection, at index: Int - ) { - // FIXME: Avoiding moving the subsequent elements twice. - let newCount = newElements.count - _ensureFreeCapacity(newCount) - _storage._insertCollection( - at: index, copying: newElements, newCount: newCount) - } -} - -//MARK: - Range replacement - -extension UniqueArray where Element: ~Copyable { - /// Replaces the specified range of elements by moving the elements of a - /// fully initialized buffer into their place. On return, the buffer is left - /// in an uninitialized state. - /// - /// This method has the effect of removing the specified range of elements - /// from the array and inserting the new elements starting at the same - /// location. The number of new elements need not match the number of elements - /// being removed. - /// - /// If the array does not have sufficient capacity to hold enough elements, - /// then this reallocates the array's storage to extend its capacity. - /// - /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. - /// - /// Likewise, if you pass a zero-length buffer as the `newElements` - /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. - /// - /// - Parameters - /// - subrange: The subrange of the array to replace. The bounds of - /// the range must be valid indices in the array. - /// - newElements: A fully initialized buffer whose contents to move into - /// the array. - /// - /// - Complexity: O(`self.count` + `newElements.count`) - @_alwaysEmitIntoClient - public mutating func replaceSubrange( - _ subrange: Range, - moving newElements: UnsafeMutableBufferPointer, - ) { - // FIXME: Avoiding moving the subsequent elements twice. - _ensureFreeCapacity(newElements.count - subrange.count) - _storage.replaceSubrange(subrange, moving: newElements) - } - - /// Replaces the specified range of elements by moving the elements of a - /// another array into their place. On return, the source array - /// becomes empty, but it is not destroyed, and it preserves its original - /// storage capacity. - /// - /// This method has the effect of removing the specified range of elements - /// from the array and inserting the new elements starting at the same - /// location. The number of new elements need not match the number of elements - /// being removed. - /// - /// If the array does not have sufficient capacity to hold enough elements, - /// then this reallocates the array's storage to extend its capacity. - /// - /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. - /// - /// Likewise, if you pass a zero-length buffer as the `newElements` - /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. - /// - /// - Parameters - /// - subrange: The subrange of the array to replace. The bounds of - /// the range must be valid indices in the array. - /// - newElements: An array whose contents to move into `self`. - /// - /// - Complexity: O(`self.count` + `newElements.count`) - @_alwaysEmitIntoClient - public mutating func replaceSubrange( - _ subrange: Range, - moving newElements: inout RigidArray, - ) { - // FIXME: Avoiding moving the subsequent elements twice. - _ensureFreeCapacity(newElements.count - subrange.count) - _storage.replaceSubrange(subrange, moving: &newElements) - } -} - -extension UniqueArray where Element: ~Copyable { - /// Replaces the specified range of elements by moving the elements of a - /// given array into their place, consuming it in the process. - /// - /// This method has the effect of removing the specified range of elements - /// from the array and inserting the new elements starting at the same - /// location. The number of new elements need not match the number of elements - /// being removed. - /// - /// If the array does not have sufficient capacity to hold enough elements, - /// then this reallocates the array's storage to extend its capacity. - /// - /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. - /// - /// Likewise, if you pass a zero-length buffer as the `newElements` - /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. - /// - /// - Parameters - /// - subrange: The subrange of the array to replace. The bounds of - /// the range must be valid indices in the array. - /// - newElements: An array whose contents to move into `self`. - /// - /// - Complexity: O(`self.count` + `newElements.count`) - @_alwaysEmitIntoClient - public mutating func replaceSubrange( - _ subrange: Range, - consuming newElements: consuming RigidArray, - ) { - replaceSubrange(subrange, moving: &newElements) - } -} - -extension UniqueArray { - /// Replaces the specified subrange of elements by copying the elements of - /// the given buffer pointer, which must be fully initialized. - /// - /// This method has the effect of removing the specified range of elements - /// from the array and inserting the new elements starting at the same location. - /// The number of new elements need not match the number of elements being - /// removed. - /// - /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. - /// - /// Likewise, if you pass a zero-length buffer as the `newElements` - /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. - /// - /// - Parameters: - /// - subrange: The subrange of the array to replace. The bounds of - /// the range must be valid indices in the array. - /// - newElements: The new elements to copy into the collection. - /// - /// - Complexity: O(*n* + *m*), where *n* is count of this array and - /// *m* is the count of `newElements`. - @inlinable - @inline(__always) - public mutating func replaceSubrange( - _ subrange: Range, - copying newElements: UnsafeBufferPointer - ) { - // FIXME: Avoiding moving the subsequent elements twice. - _ensureFreeCapacity(newElements.count) - unsafe _storage.replaceSubrange(subrange, copying: newElements) - } - - /// Replaces the specified subrange of elements by copying the elements of - /// the given buffer pointer, which must be fully initialized. - /// - /// This method has the effect of removing the specified range of elements - /// from the array and inserting the new elements starting at the same location. - /// The number of new elements need not match the number of elements being - /// removed. - /// - /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. - /// - /// Likewise, if you pass a zero-length buffer as the `newElements` - /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. - /// - /// - Parameters: - /// - subrange: The subrange of the array to replace. The bounds of - /// the range must be valid indices in the array. - /// - newElements: The new elements to copy into the collection. - /// - /// - Complexity: O(*n* + *m*), where *n* is count of this array and - /// *m* is the count of `newElements`. - @inlinable - @inline(__always) - public mutating func replaceSubrange( - _ subrange: Range, - copying newElements: UnsafeMutableBufferPointer - ) { - unsafe self.replaceSubrange( - subrange, copying: UnsafeBufferPointer(newElements)) - } - - /// Replaces the specified subrange of elements by copying the elements of - /// the given span. - /// - /// This method has the effect of removing the specified range of elements - /// from the array and inserting the new elements starting at the same location. - /// The number of new elements need not match the number of elements being - /// removed. - /// - /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. - /// - /// Likewise, if you pass a zero-length span as the `newElements` - /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. - /// - /// - Parameters: - /// - subrange: The subrange of the array to replace. The bounds of - /// the range must be valid indices in the array. - /// - newElements: The new elements to copy into the collection. - /// - /// - Complexity: O(*n* + *m*), where *n* is count of this array and - /// *m* is the count of `newElements`. - @available(SwiftStdlib 6.2, *) - @inlinable - public mutating func replaceSubrange( - _ subrange: Range, - copying newElements: Span - ) { - // FIXME: Avoiding moving the subsequent elements twice. - _ensureFreeCapacity(newElements.count) - _storage.replaceSubrange(subrange, copying: newElements) - } - - /// Replaces the specified subrange of elements by copying the elements of - /// the given collection. - /// - /// This method has the effect of removing the specified range of elements - /// from the array and inserting the new elements starting at the same location. - /// The number of new elements need not match the number of elements being - /// removed. - /// - /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. - /// - /// Likewise, if you pass a zero-length collection as the `newElements` - /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. - /// - /// - Parameters: - /// - subrange: The subrange of the array to replace. The bounds of - /// the range must be valid indices in the array. - /// - newElements: The new elements to copy into the collection. - /// - /// - Complexity: O(*n* + *m*), where *n* is count of this array and - /// *m* is the count of `newElements`. - @inlinable - @inline(__always) - public mutating func replaceSubrange( - _ subrange: Range, - copying newElements: __owned some Collection - ) { - // FIXME: Avoiding moving the subsequent elements twice. - let c = newElements.count - _ensureFreeCapacity(c) - _storage._replaceSubrange( - subrange, copyingCollection: newElements, newCount: c) - } -} #endif diff --git a/Sources/InternalCollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift.gyb b/Sources/InternalCollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift.gyb index 29553931..2bed0319 100644 --- a/Sources/InternalCollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift.gyb +++ b/Sources/InternalCollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift.gyb @@ -123,48 +123,13 @@ extension UnsafeMutableBufferPointer { /// The `source` span must fit entirely in `self`. /// /// - Returns: The index after the last item that was initialized in this buffer. - @available(SwiftStdlib 6.2, *) + @available(SwiftStdlib 5.0, *) @inlinable ${modifier} func _initializePrefix(copying source: Span) -> Int { source.withUnsafeBufferPointer { self._initializePrefix(copying: $0) } } #endif -#if compiler(>=6.2) && FIXME - /// Initialize all slots in this buffer by copying data from `items`, which must fit entirely - /// in this buffer. - /// - /// If `items` contains more elements than can fit into this buffer, then this function - /// will return an index other than `items.endIndex`. In that case, `self` may not be fully - /// populated. - /// - /// If `Element` is not bitwise copyable, then this function must be called on an - /// entirely uninitialized buffer. - /// - /// - Returns: A pair of values `(count, end)`, where `count` is the number of items that were - /// successfully initialized, and `end` is the index into `items` after the last copied item. - @available(SwiftStdlib 6.2, *) - @inlinable - ${modifier} func _initializePrefix< - C: Container & ~Copyable & ~Escapable - >( - copying items: borrowing C - ) -> (copied: Int, end: C.Index) { - var target = self - var i = items.startIndex - while true { - let start = i - let span = items.span(after: &i) - if span.isEmpty { break } - guard span.count <= target.count else { - return (self.count - target.count, start) - } - target._initializeAndDropPrefix(copying: span) - } - return (self.count - target.count, i) - } -#endif - /// Initialize slots at the start of this buffer by copying data from `buffer`, then /// shrink `self` to drop all initialized items from its front, leaving it addressing the /// uninitialized remainder. @@ -269,13 +234,17 @@ extension UnsafeMutableBufferPointer { let i = self.initialize(fromContentsOf: source) assert(i == self.endIndex) } +} +extension UnsafeMutableBufferPointer where Element: ~Copyable { @inlinable @inline(__always) ${modifier} func moveInitializeAll(fromContentsOf source: Self) { let i = self.moveInitialize(fromContentsOf: source) assert(i == self.endIndex) } +} +extension UnsafeMutableBufferPointer { @inlinable @inline(__always) ${modifier} func moveInitializeAll(fromContentsOf source: Slice) { let i = self.moveInitialize(fromContentsOf: source) diff --git a/Sources/InternalCollectionsUtilities/autogenerated/UnsafeMutableBufferPointer+Extras.swift b/Sources/InternalCollectionsUtilities/autogenerated/UnsafeMutableBufferPointer+Extras.swift index 568b9fed..7abcc67e 100644 --- a/Sources/InternalCollectionsUtilities/autogenerated/UnsafeMutableBufferPointer+Extras.swift +++ b/Sources/InternalCollectionsUtilities/autogenerated/UnsafeMutableBufferPointer+Extras.swift @@ -129,48 +129,13 @@ extension UnsafeMutableBufferPointer { /// The `source` span must fit entirely in `self`. /// /// - Returns: The index after the last item that was initialized in this buffer. - @available(SwiftStdlib 6.2, *) + @available(SwiftStdlib 5.0, *) @inlinable internal func _initializePrefix(copying source: Span) -> Int { source.withUnsafeBufferPointer { self._initializePrefix(copying: $0) } } #endif -#if compiler(>=6.2) && FIXME - /// Initialize all slots in this buffer by copying data from `items`, which must fit entirely - /// in this buffer. - /// - /// If `items` contains more elements than can fit into this buffer, then this function - /// will return an index other than `items.endIndex`. In that case, `self` may not be fully - /// populated. - /// - /// If `Element` is not bitwise copyable, then this function must be called on an - /// entirely uninitialized buffer. - /// - /// - Returns: A pair of values `(count, end)`, where `count` is the number of items that were - /// successfully initialized, and `end` is the index into `items` after the last copied item. - @available(SwiftStdlib 6.2, *) - @inlinable - internal func _initializePrefix< - C: Container & ~Copyable & ~Escapable - >( - copying items: borrowing C - ) -> (copied: Int, end: C.Index) { - var target = self - var i = items.startIndex - while true { - let start = i - let span = items.span(after: &i) - if span.isEmpty { break } - guard span.count <= target.count else { - return (self.count - target.count, start) - } - target._initializeAndDropPrefix(copying: span) - } - return (self.count - target.count, i) - } -#endif - /// Initialize slots at the start of this buffer by copying data from `buffer`, then /// shrink `self` to drop all initialized items from its front, leaving it addressing the /// uninitialized remainder. @@ -275,13 +240,17 @@ extension UnsafeMutableBufferPointer { let i = self.initialize(fromContentsOf: source) assert(i == self.endIndex) } +} +extension UnsafeMutableBufferPointer where Element: ~Copyable { @inlinable @inline(__always) internal func moveInitializeAll(fromContentsOf source: Self) { let i = self.moveInitialize(fromContentsOf: source) assert(i == self.endIndex) } +} +extension UnsafeMutableBufferPointer { @inlinable @inline(__always) internal func moveInitializeAll(fromContentsOf source: Slice) { let i = self.moveInitialize(fromContentsOf: source) @@ -438,48 +407,13 @@ extension UnsafeMutableBufferPointer { /// The `source` span must fit entirely in `self`. /// /// - Returns: The index after the last item that was initialized in this buffer. - @available(SwiftStdlib 6.2, *) + @available(SwiftStdlib 5.0, *) @inlinable public func _initializePrefix(copying source: Span) -> Int { source.withUnsafeBufferPointer { self._initializePrefix(copying: $0) } } #endif -#if compiler(>=6.2) && FIXME - /// Initialize all slots in this buffer by copying data from `items`, which must fit entirely - /// in this buffer. - /// - /// If `items` contains more elements than can fit into this buffer, then this function - /// will return an index other than `items.endIndex`. In that case, `self` may not be fully - /// populated. - /// - /// If `Element` is not bitwise copyable, then this function must be called on an - /// entirely uninitialized buffer. - /// - /// - Returns: A pair of values `(count, end)`, where `count` is the number of items that were - /// successfully initialized, and `end` is the index into `items` after the last copied item. - @available(SwiftStdlib 6.2, *) - @inlinable - public func _initializePrefix< - C: Container & ~Copyable & ~Escapable - >( - copying items: borrowing C - ) -> (copied: Int, end: C.Index) { - var target = self - var i = items.startIndex - while true { - let start = i - let span = items.span(after: &i) - if span.isEmpty { break } - guard span.count <= target.count else { - return (self.count - target.count, start) - } - target._initializeAndDropPrefix(copying: span) - } - return (self.count - target.count, i) - } -#endif - /// Initialize slots at the start of this buffer by copying data from `buffer`, then /// shrink `self` to drop all initialized items from its front, leaving it addressing the /// uninitialized remainder. @@ -584,13 +518,17 @@ extension UnsafeMutableBufferPointer { let i = self.initialize(fromContentsOf: source) assert(i == self.endIndex) } +} +extension UnsafeMutableBufferPointer where Element: ~Copyable { @inlinable @inline(__always) public func moveInitializeAll(fromContentsOf source: Self) { let i = self.moveInitialize(fromContentsOf: source) assert(i == self.endIndex) } +} +extension UnsafeMutableBufferPointer { @inlinable @inline(__always) public func moveInitializeAll(fromContentsOf source: Slice) { let i = self.moveInitialize(fromContentsOf: source) diff --git a/Tests/BasicContainersTests/RigidArrayTests.swift b/Tests/BasicContainersTests/RigidArrayTests.swift index 9b86c1ad..935de351 100644 --- a/Tests/BasicContainersTests/RigidArrayTests.swift +++ b/Tests/BasicContainersTests/RigidArrayTests.swift @@ -303,7 +303,7 @@ class RigidArrayTests: CollectionTestCase { } } -#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +#if false // TODO func test_borrowElement() { withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in withLifetimeTracking { tracker in @@ -334,8 +334,8 @@ class RigidArrayTests: CollectionTestCase { } } -#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW - func test_mutateElement() { +#if false // TODO + func test_mutateElement2() { withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in withLifetimeTracking { tracker in var a = tracker.rigidArray(layout: layout) @@ -555,7 +555,7 @@ class RigidArrayTests: CollectionTestCase { } } -#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +#if false // TODO func test_removeAll_where() { withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in withLifetimeTracking { tracker in @@ -735,8 +735,10 @@ class RigidArrayTests: CollectionTestCase { var a = tracker.rigidArray(layout: layout) let rigidAddition = StaccatoContainer( - contents: RigidArray(count: addition.count) { - tracker.instance(for: addition[$0]) + contents: RigidArray(capacity: addition.count) { + for item in addition { + $0.append(tracker.instance(for: item)) + } }, spanCounts: [Swift.max(spanCount, 1)]) a.insert(copying: rigidAddition, at: i) diff --git a/Tests/BasicContainersTests/UniqueArrayTests.swift b/Tests/BasicContainersTests/UniqueArrayTests.swift index 4096997b..3eaf7488 100644 --- a/Tests/BasicContainersTests/UniqueArrayTests.swift +++ b/Tests/BasicContainersTests/UniqueArrayTests.swift @@ -323,7 +323,7 @@ class UniqueArrayTests: CollectionTestCase { } } -#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +#if false // TODO func test_borrowElement() { withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in withLifetimeTracking { tracker in @@ -337,7 +337,7 @@ class UniqueArrayTests: CollectionTestCase { } #endif -#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +#if false // TODO func test_mutateElement() { withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in withLifetimeTracking { tracker in @@ -538,7 +538,7 @@ class UniqueArrayTests: CollectionTestCase { } } -#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +#if false // TODO func test_removeAll_where() { withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in withLifetimeTracking { tracker in @@ -785,8 +785,10 @@ class UniqueArrayTests: CollectionTestCase { var a = tracker.uniqueArray(layout: layout) let rigidAddition = StaccatoContainer( - contents: RigidArray(count: addition.count) { - tracker.instance(for: addition[$0]) + contents: RigidArray(capacity: addition.count) { + for item in addition { + $0.append(tracker.instance(for: item)) + } }, spanCounts: [spanCount]) a.insert(copying: rigidAddition, at: i) From c0943d7658856fad951c2840fe6c143b0747afa9 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 26 Sep 2025 17:19:30 -0700 Subject: [PATCH 03/16] =?UTF-8?q?struct=20Borrow=20=E2=86=92=20struct=20Re?= =?UTF-8?q?f?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Sources/ContainersPreview/Box.swift | 4 ++-- Sources/ContainersPreview/{Borrow.swift => Ref.swift} | 2 +- Tests/ContainersTests/{BorrowTests.swift => RefTests.swift} | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) rename Sources/ContainersPreview/{Borrow.swift => Ref.swift} (96%) rename Tests/ContainersTests/{BorrowTests.swift => RefTests.swift} (90%) diff --git a/Sources/ContainersPreview/Box.swift b/Sources/ContainersPreview/Box.swift index bb049d77..7567e0ac 100644 --- a/Sources/ContainersPreview/Box.swift +++ b/Sources/ContainersPreview/Box.swift @@ -90,8 +90,8 @@ extension Box where T: ~Copyable { @_alwaysEmitIntoClient @_transparent @_lifetime(borrow self) - public func borrow() -> Borrow { - unsafe Borrow(unsafeAddress: UnsafePointer(_pointer), borrowing: self) + public func borrow() -> Ref { + unsafe Ref(unsafeAddress: UnsafePointer(_pointer), borrowing: self) } #endif diff --git a/Sources/ContainersPreview/Borrow.swift b/Sources/ContainersPreview/Ref.swift similarity index 96% rename from Sources/ContainersPreview/Borrow.swift rename to Sources/ContainersPreview/Ref.swift index 7d42bbf2..ab7edecc 100644 --- a/Sources/ContainersPreview/Borrow.swift +++ b/Sources/ContainersPreview/Ref.swift @@ -14,7 +14,7 @@ import Builtin @frozen @safe -public struct Borrow: Copyable, ~Escapable { +public struct Ref: Copyable, ~Escapable { @usableFromInline package let _pointer: UnsafePointer diff --git a/Tests/ContainersTests/BorrowTests.swift b/Tests/ContainersTests/RefTests.swift similarity index 90% rename from Tests/ContainersTests/BorrowTests.swift rename to Tests/ContainersTests/RefTests.swift index f6c0ed6d..c23ed74d 100644 --- a/Tests/ContainersTests/BorrowTests.swift +++ b/Tests/ContainersTests/RefTests.swift @@ -14,8 +14,8 @@ import XCTest import ContainersPreview import Synchronization -final class BorrowTests: XCTestCase { - @available(SwiftStdlib 6.2, *) +final class RefTests: XCTestCase { + @available(SwiftStdlib 5.0, *) func test_basic() { let x: Atomic? = Atomic(0) From 89c7e027ecbb6e586ee24ce3e116ebe6fed7f7a6 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 26 Sep 2025 17:20:40 -0700 Subject: [PATCH 04/16] =?UTF-8?q?struct=20Inout=20=E2=86=92=20struct=20Mut?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Sources/ContainersPreview/Box.swift | 8 ++++---- .../ContainersPreview/{Inout.swift => Mut.swift} | 16 ++++++++-------- Sources/ContainersPreview/Shared.swift | 4 ++-- .../{InoutTests.swift => MutTests.swift} | 4 ++-- 4 files changed, 16 insertions(+), 16 deletions(-) rename Sources/ContainersPreview/{Inout.swift => Mut.swift} (82%) rename Tests/ContainersTests/{InoutTests.swift => MutTests.swift} (93%) diff --git a/Sources/ContainersPreview/Box.swift b/Sources/ContainersPreview/Box.swift index 7567e0ac..3ff38888 100644 --- a/Sources/ContainersPreview/Box.swift +++ b/Sources/ContainersPreview/Box.swift @@ -79,8 +79,8 @@ extension Box where T: ~Copyable { @_alwaysEmitIntoClient @_transparent @_lifetime(immortal) - public consuming func leak() -> Inout { - let result = unsafe Inout(unsafeImmortalAddress: _pointer) + public consuming func leak() -> Mut { + let result = unsafe Mut(unsafeImmortalAddress: _pointer) discard self return result } @@ -99,8 +99,8 @@ extension Box where T: ~Copyable { @_alwaysEmitIntoClient @_transparent @_lifetime(&self) - public mutating func mutate() -> Inout { - unsafe Inout(unsafeAddress: _pointer, mutating: &self) + public mutating func mutate() -> Mut { + unsafe Mut(unsafeAddress: _pointer, mutating: &self) } #endif } diff --git a/Sources/ContainersPreview/Inout.swift b/Sources/ContainersPreview/Mut.swift similarity index 82% rename from Sources/ContainersPreview/Inout.swift rename to Sources/ContainersPreview/Mut.swift index bf759e6d..983b6314 100644 --- a/Sources/ContainersPreview/Inout.swift +++ b/Sources/ContainersPreview/Mut.swift @@ -16,15 +16,15 @@ import Builtin /// A safe mutable reference allowing in-place mutation to an exclusive value. /// -/// In order to get an instance of an `Inout`, one must have exclusive access +/// In order to get an instance of a `Mut`, one must have exclusive access /// to the instance of `T`. This is achieved through the 'inout' operator, '&'. @frozen @safe -public struct Inout: ~Copyable, ~Escapable { +public struct Mut: ~Copyable, ~Escapable { @usableFromInline package let _pointer: UnsafeMutablePointer - /// Initializes an instance of 'Inout' extending the exclusive access of the + /// Initializes an instance of 'Mut' extending the exclusive access of the /// passed instance. /// /// - Parameter instance: The desired instance to get a mutable reference to. @@ -34,13 +34,13 @@ public struct Inout: ~Copyable, ~Escapable { unsafe _pointer = UnsafeMutablePointer(Builtin.unprotectedAddressOf(&instance)) } - /// Unsafely initializes an instance of 'Inout' using the given 'unsafeAddress' + /// Unsafely initializes an instance of 'Mut' using the given 'unsafeAddress' /// as the mutable reference based on the lifetime of the given 'owner' /// argument. /// /// - Parameter unsafeAddress: The address to use to mutably reference an /// instance of type 'T'. - /// - Parameter owner: The owning instance that this 'Inout' instance's + /// - Parameter owner: The owning instance that this 'Mut' instance's /// lifetime is based on. @unsafe @_alwaysEmitIntoClient @@ -53,7 +53,7 @@ public struct Inout: ~Copyable, ~Escapable { unsafe _pointer = unsafeAddress } - /// Unsafely initializes an instance of 'Inout' using the given + /// Unsafely initializes an instance of 'Mut' using the given /// 'unsafeImmortalAddress' as the mutable reference acting as though its /// lifetime is immortal. /// @@ -70,7 +70,7 @@ public struct Inout: ~Copyable, ~Escapable { } } -extension Inout where T: ~Copyable { +extension Mut where T: ~Copyable { /// Dereferences the mutable reference allowing for in-place reads and writes /// to the underlying instance. @_alwaysEmitIntoClient @@ -80,8 +80,8 @@ extension Inout where T: ~Copyable { unsafe UnsafePointer(_pointer) } - @_lifetime(copy self) @_transparent + @_lifetime(self: copy self) unsafeMutableAddress { unsafe _pointer } diff --git a/Sources/ContainersPreview/Shared.swift b/Sources/ContainersPreview/Shared.swift index 67b4e1fa..423d978b 100644 --- a/Sources/ContainersPreview/Shared.swift +++ b/Sources/ContainersPreview/Shared.swift @@ -139,11 +139,11 @@ extension Shared where Storage: ~Copyable { @inlinable @_lifetime(&self) - public mutating func mutate() -> Inout { + public mutating func mutate() -> Mut { // This is gloriously (and very explicitly) unsafe, as it should be. // `Shared` is carefully constructed to guarantee that // lifetime(self) == lifetime(_box.storage). - unsafe Inout(unsafeAddress: _mutableAddress, mutating: &self) + unsafe Mut(unsafeAddress: _mutableAddress, mutating: &self) } } diff --git a/Tests/ContainersTests/InoutTests.swift b/Tests/ContainersTests/MutTests.swift similarity index 93% rename from Tests/ContainersTests/InoutTests.swift rename to Tests/ContainersTests/MutTests.swift index 6bd2f0b7..a31b204d 100644 --- a/Tests/ContainersTests/InoutTests.swift +++ b/Tests/ContainersTests/MutTests.swift @@ -18,10 +18,10 @@ import ContainersPreview #endif #if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW -final class InoutTests: XCTestCase { +final class MutTests: XCTestCase { func test_basic() { var x = 0 - var y = Inout(&x) + var y = Mut(&x) var v = y[] XCTAssertEqual(v, 0) From 62ba5cf1eef3664c41b68864022421d2e35af718 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 26 Sep 2025 17:20:57 -0700 Subject: [PATCH 05/16] Disable struct Shared for now --- Sources/ContainersPreview/Shared.swift | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Sources/ContainersPreview/Shared.swift b/Sources/ContainersPreview/Shared.swift index 423d978b..38204e3c 100644 --- a/Sources/ContainersPreview/Shared.swift +++ b/Sources/ContainersPreview/Shared.swift @@ -11,6 +11,7 @@ #if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +#if false // TODO import Builtin // For Shared.isIdentical /// A utility adapter that wraps a noncopyable storage type in a copy-on-write @@ -114,11 +115,9 @@ extension Shared where Storage: ~Copyable { @inlinable @inline(__always) public var value: Storage { - @_lifetime(borrow self) unsafeAddress { unsafe _address } - @_lifetime(&self) unsafeMutableAddress { precondition(isUnique()) return unsafe _mutableAddress @@ -129,11 +128,11 @@ extension Shared where Storage: ~Copyable { extension Shared where Storage: ~Copyable { @inlinable @_lifetime(borrow self) - public borrowing func borrow() -> Borrow { + public borrowing func borrow() -> Ref { // This is gloriously (and very explicitly) unsafe, as it should be. // `Shared` is carefully constructed to guarantee that // lifetime(self) == lifetime(_box.storage). - unsafe Borrow(unsafeAddress: _address, borrowing: self) + unsafe Ref(unsafeAddress: _address, borrowing: self) } @@ -162,3 +161,4 @@ extension Shared where Storage: ~Copyable { } } #endif +#endif From 155a8a010ea5922cd86c312bdb33e7fe3b3eb117 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 26 Sep 2025 17:21:30 -0700 Subject: [PATCH 06/16] InputSpan: Set availability to be consistent with other Span types --- Sources/ContainersPreview/InputSpan.swift | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/Sources/ContainersPreview/InputSpan.swift b/Sources/ContainersPreview/InputSpan.swift index 0a945304..63e7dbc8 100644 --- a/Sources/ContainersPreview/InputSpan.swift +++ b/Sources/ContainersPreview/InputSpan.swift @@ -16,6 +16,7 @@ import InternalCollectionsUtilities #endif import Builtin +@available(SwiftStdlib 5.0, *) @safe @frozen public struct InputSpan: ~Copyable, ~Escapable { @@ -46,8 +47,10 @@ public struct InputSpan: ~Copyable, ~Escapable { } } +@available(SwiftStdlib 5.0, *) extension InputSpan: @unchecked Sendable where Element: Sendable & ~Copyable {} +@available(SwiftStdlib 5.0, *) extension InputSpan where Element: ~Copyable { @_alwaysEmitIntoClient @_transparent @@ -86,6 +89,7 @@ extension InputSpan where Element: ~Copyable { } } +@available(SwiftStdlib 5.0, *) extension InputSpan where Element: ~Copyable { /// Consume the input span and return the number of initialized elements /// remaining at the end of the underlying memory region. @@ -118,6 +122,7 @@ extension InputSpan where Element: ~Copyable { } } +@available(SwiftStdlib 5.0, *) extension InputSpan { /// Consume the input span and return the number of initialized elements /// remaining at the end of the underlying memory region. @@ -144,6 +149,7 @@ extension InputSpan { } } +@available(SwiftStdlib 5.0, *) extension InputSpan where Element: ~Copyable { /// The number of initialized elements in this span. @_alwaysEmitIntoClient @@ -162,6 +168,7 @@ extension InputSpan where Element: ~Copyable { public var isFull: Bool { _count == capacity } } +@available(SwiftStdlib 5.0, *) extension InputSpan where Element: ~Copyable { @unsafe @_alwaysEmitIntoClient @@ -195,6 +202,7 @@ extension InputSpan where Element: ~Copyable { } } +@available(SwiftStdlib 5.0, *) extension InputSpan { /// Unsafely create an input span over partially initialized memory. /// @@ -222,6 +230,7 @@ extension InputSpan { } } +@available(SwiftStdlib 5.0, *) extension InputSpan where Element: ~Copyable { /// The type that represents an initialized position in an `InputSpan`. public typealias Index = Int @@ -301,6 +310,7 @@ extension InputSpan where Element: ~Copyable { } } +@available(SwiftStdlib 5.0, *) extension InputSpan where Element: ~Copyable { /// Prepend a single element to this span. @_alwaysEmitIntoClient @@ -355,6 +365,7 @@ extension InputSpan where Element: ~Copyable { //MARK: Bulk append functions +@available(SwiftStdlib 5.0, *) extension InputSpan { /// Repeatedly append an element to this span. @_alwaysEmitIntoClient @@ -368,6 +379,7 @@ extension InputSpan { } } +@available(SwiftStdlib 5.0, *) extension InputSpan where Element: ~Copyable { /// Borrow the underlying initialized memory for read-only access. @available(SwiftStdlib 5.0, *) @@ -401,6 +413,7 @@ extension InputSpan where Element: ~Copyable { } } +@available(SwiftStdlib 5.0, *) extension InputSpan where Element: ~Copyable { /// Call the given closure with the unsafe buffer pointer addressed by this /// InputSpan and a mutable reference to its count of initialized elements. From 2ae7f11ecf59f366dfed86f17922068194feedc4 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 26 Sep 2025 17:26:50 -0700 Subject: [PATCH 07/16] Add draft version of borrowable Container protocol --- Package.swift | 8 +- Package@swift-6.0.swift | 6 +- .../BorrowIteratorProtocol.swift | 105 ++++++++++ .../Container+Utilities.swift | 133 ++++++++++++ Sources/ContainersPreview/Container.swift | 87 ++++++++ .../Assertions+Containers.swift | 85 ++++---- .../ConformanceCheckers/CheckContainer.swift | 196 +++++------------- .../MinimalTypes/StaccatoContainer.swift | 86 +++----- 8 files changed, 461 insertions(+), 245 deletions(-) create mode 100644 Sources/ContainersPreview/BorrowIteratorProtocol.swift create mode 100644 Sources/ContainersPreview/Container+Utilities.swift create mode 100644 Sources/ContainersPreview/Container.swift diff --git a/Package.swift b/Package.swift index 7d8b8319..a571a2c4 100644 --- a/Package.swift +++ b/Package.swift @@ -89,7 +89,7 @@ let extraSettings: [SwiftSetting] = [ .enableExperimentalFeature("BuiltinModule"), .enableExperimentalFeature("Lifetimes"), .enableExperimentalFeature("InoutLifetimeDependence"), -// .enableExperimentalFeature("SuppressedAssociatedTypes"), + .enableExperimentalFeature("SuppressedAssociatedTypes"), // .enableExperimentalFeature("AddressableParameters"), // .enableExperimentalFeature("AddressableTypes"), @@ -193,7 +193,11 @@ let targets: [CustomTarget] = [ .target( kind: .testSupport, name: "_CollectionsTestSupport", - dependencies: ["InternalCollectionsUtilities", "ContainersPreview"]), + dependencies: [ + "InternalCollectionsUtilities", + "ContainersPreview", + "BasicContainers", + ]), .target( kind: .test, name: "CollectionsTestSupportTests", diff --git a/Package@swift-6.0.swift b/Package@swift-6.0.swift index be65b230..44eb7ae6 100644 --- a/Package@swift-6.0.swift +++ b/Package@swift-6.0.swift @@ -214,7 +214,11 @@ let targets: [CustomTarget] = [ .target( kind: .testSupport, name: "_CollectionsTestSupport", - dependencies: ["InternalCollectionsUtilities", "ContainersPreview"]), + dependencies: [ + "InternalCollectionsUtilities", + "ContainersPreview", + "BasicContainers", + ]), .target( kind: .test, name: "CollectionsTestSupportTests", diff --git a/Sources/ContainersPreview/BorrowIteratorProtocol.swift b/Sources/ContainersPreview/BorrowIteratorProtocol.swift new file mode 100644 index 00000000..f3452512 --- /dev/null +++ b/Sources/ContainersPreview/BorrowIteratorProtocol.swift @@ -0,0 +1,105 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2024 - 2025 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 compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +@available(SwiftStdlib 5.0, *) +public protocol BorrowIteratorProtocol: ~Copyable, ~Escapable { + associatedtype Element: ~Copyable /*& ~Escapable*/ + + /// Advance the iterator to the next storage chunk, returning a span over it. + /// + /// If the iterator has not yet reached the end of the underlying container, + /// then this method returns a non-empty span over the container's storage + /// that begins with the element at the iterator's current position and + /// extends to the end of the contiguous storage chunk that contains that + /// item, but at most `maximumCount` items. On return, the iterator's current + /// position is updated to the slot following the last item in the returned + /// span. + /// + /// If the iterator's current position is at the end of the container, then + /// this method returns an empty span without updating the position. + /// + /// 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 it = items.startBorrowIteration() + /// while true { + /// let span = it.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, for example to repeat their contents. + /// + /// Note: Repeatedly iterating over the same container is expected to return + /// the same items (collected in similarly sized span instances), but the + /// returned spans are not guaranteed to be identical. (For example, this is + /// the case with containers that can store contents within their direct + /// representation. Such containers may not always have a unique address in + /// memory, and so the locations of the spans exposed by this method may vary + /// between different borrows of the same container.) + /// + /// - Parameter maximumCount: The maximum count of items the caller is ready + /// to process, or nil if the caller is prepared to accept an arbitrarily + /// large span. If non-nil, the maximum must be greater than zero. + /// - Returns: A span over a piece of contiguous storage in the underlying + /// container. It the iterator is at the end of the container, then + /// this returns an empty span. Otherwise the result will contain at least + /// one element. + @_lifetime(copy self) + @_lifetime(self: copy self) + mutating func nextSpan(maximumCount: Int?) -> Span + + @_lifetime(self: copy self) + mutating func skip(by offset: Int) -> Int +} + +@available(SwiftStdlib 5.0, *) +extension BorrowIteratorProtocol where Self: ~Copyable & ~Escapable { + @_lifetime(self: copy self) + @inlinable + public mutating func skip(by offset: Int) -> Int { + var remainder = offset + while remainder > 0 { + let span = nextSpan(maximumCount: remainder) + if span.isEmpty { break } + remainder &-= span.count + } + return offset &- remainder + } +} + +@available(SwiftStdlib 5.0, *) +extension BorrowIteratorProtocol where Self: ~Copyable & ~Escapable { + @_lifetime(copy self) + @_lifetime(self: copy self) + @_transparent + public mutating func nextSpan() -> Span { + nextSpan(maximumCount: nil) + } +} + +@available(SwiftStdlib 5.0, *) +extension Span: BorrowIteratorProtocol where Element: ~Copyable { + @_lifetime(copy self) + @_lifetime(self: copy self) + public mutating func nextSpan(maximumCount: Int?) -> Span { + let c = maximumCount ?? self.count + let result = self.extracting(first: c) + self = self.extracting(droppingFirst: c) + return result + } +} + +#endif diff --git a/Sources/ContainersPreview/Container+Utilities.swift b/Sources/ContainersPreview/Container+Utilities.swift new file mode 100644 index 00000000..7696b264 --- /dev/null +++ b/Sources/ContainersPreview/Container+Utilities.swift @@ -0,0 +1,133 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2024 - 2025 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 +// +//===----------------------------------------------------------------------===// + +import InternalCollectionsUtilities + +#if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + +@available(SwiftStdlib 5.0, *) +extension Container where Self: ~Copyable & ~Escapable, Element: Copyable { + @inlinable + package func _copyContents( + intoPrefixOf buffer: UnsafeMutableBufferPointer + ) -> Int { + var target = buffer + var it = self.startBorrowIteration() + while target.count != 0 { + let span = it.nextSpan(maximumCount: target.count) + if span.isEmpty { + return buffer.count - target.count + } + target._initializeAndDropPrefix(copying: span) + } + let test = it.nextSpan() + precondition(test.isEmpty, "Contents do not fit in target buffer") + return buffer.count + } +} + +@available(SwiftStdlib 5.0, *) +extension Container where Self: ~Copyable & ~Escapable { + @inlinable + @discardableResult + internal func _spanwiseZip< + Other: Container & ~Copyable & ~Escapable, + State: ~Copyable, E: Error + >( + state: inout State, + with other: borrowing Other, + by process: (inout State, Span, Span) throws(E) -> Bool + ) throws(E) -> Int { + var it1 = self.startBorrowIteration() + var it2 = other.startBorrowIteration() + var a = it1.nextSpan() + var b = it2.nextSpan() + var offset = 0 // Offset of the start of the current spans + loop: + while true { + if a.isEmpty { + a = it1.nextSpan() + } + if b.isEmpty { + b = it2.nextSpan() + } + if a.isEmpty || b.isEmpty { + return offset + } + + let c = Swift.min(a.count, b.count) + guard try process(&state, a.extracting(first: c), b.extracting(first: c)) else { + return offset + } + a = a.extracting(droppingFirst: c) + b = b.extracting(droppingFirst: c) + offset += c + } + } + + /// Returns a Boolean value indicating whether this container and another + /// container contain equivalent elements in the same order, using the given + /// predicate as the equivalence test. + /// + /// The predicate must form an *equivalence relation* over the elements. That + /// is, for any elements `a`, `b`, and `c`, the following conditions must + /// hold: + /// + /// - `areEquivalent(a, a)` is always `true`. (Reflexivity) + /// - `areEquivalent(a, b)` implies `areEquivalent(b, a)`. (Symmetry) + /// - If `areEquivalent(a, b)` and `areEquivalent(b, c)` are both `true`, then + /// `areEquivalent(a, c)` is also `true`. (Transitivity) + /// + /// - Parameters: + /// - other: A container to compare to this container. + /// - areEquivalent: A predicate that returns `true` if its two arguments + /// are equivalent; otherwise, `false`. + /// - Returns: `true` if this container and `other` contain equivalent items, + /// using `areEquivalent` as the equivalence test; otherwise, `false.` + /// + /// - Complexity: O(*m*), where *m* is the count of the longer of the input containers. + @inlinable + public func borrowingElementsEqual< + E: Error, + Other: Container & ~Copyable & ~Escapable + >( + _ other: borrowing Other, + by areEquivalent: (borrowing Element, borrowing Other.Element) throws(E) -> Bool + ) throws(E) -> Bool { + guard self.count == other.count else { return false } + var result = true + try _spanwiseZip(state: &result, with: other) { state, a, b throws(E) in + assert(a.count == b.count) + for i in a.indices { + guard try areEquivalent(a[i], b[i]) else { + state = false + return false + } + } + return true + } + return result + } +} + +@available(SwiftStdlib 5.0, *) +extension Container where Self: ~Copyable & ~Escapable, Element: Equatable { + @inlinable + public func borrowingElementsEqual< + Other: Container & ~Copyable & ~Escapable + >( + _ other: borrowing Other, + ) -> Bool { + self.borrowingElementsEqual(other, by: ==) + } +} + +#endif diff --git a/Sources/ContainersPreview/Container.swift b/Sources/ContainersPreview/Container.swift new file mode 100644 index 00000000..a804e5aa --- /dev/null +++ b/Sources/ContainersPreview/Container.swift @@ -0,0 +1,87 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2024 - 2025 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 compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + +@available(SwiftStdlib 5.0, *) +public protocol Container: ~Copyable, ~Escapable { + associatedtype Element: ~Copyable /*& ~Escapable*/ + associatedtype BorrowIterator: BorrowIteratorProtocol & ~Copyable & ~Escapable + + var isEmpty: Bool { get } + var count: Int { get } + + @_lifetime(borrow self) + borrowing func startBorrowIteration() -> BorrowIterator +} + +@available(SwiftStdlib 5.0, *) +extension Container where Self: ~Copyable & ~Escapable { + /// Implementation demo of what borrowing for-in loops would need to expand into. + @inlinable + public func _borrowingForEach( + _ body: (borrowing Element) throws(E) -> Void + ) throws(E) -> Void { + var it = startBorrowIteration() + while true { + let span = it.nextSpan() + if span.isEmpty { break } + var i = 0 + while i < span.count { + try body(span[unchecked: i]) + i &+= 1 + } + } + } +} + +@available(SwiftStdlib 5.0, *) +extension Container where Self: ~Copyable & ~Escapable { + @inlinable + public func borrowingReduce( + into initial: consuming Result, + _ update: (inout Result, borrowing Self.Element) throws(E) -> () + ) throws(E) -> Result { + var result = initial + try self._borrowingForEach { item throws(E) in + try update(&result, item) + } + return result + } + + @inlinable + public func borrowingReduce( + _ initial: consuming Result, + _ next: (consuming Result, borrowing Self.Element) throws(E) -> Result + ) throws(E) -> Result { + var result = initial +#if false // FIXME: missing reinitialization of closure capture 'result' after consume + try self._borrowingForEach { item throws(E) in + result = try next(result, item) + } +#else + var it = startBorrowIteration() + while true { + let span = it.nextSpan() + if span.isEmpty { break } + var i = 0 + while i < span.count { + result = try next(result, span[unchecked: i]) + i &+= 1 + } + } +#endif + return result + } + +} + +#endif diff --git a/Tests/_CollectionsTestSupport/AssertionContexts/Assertions+Containers.swift b/Tests/_CollectionsTestSupport/AssertionContexts/Assertions+Containers.swift index b88327d7..e153de16 100644 --- a/Tests/_CollectionsTestSupport/AssertionContexts/Assertions+Containers.swift +++ b/Tests/_CollectionsTestSupport/AssertionContexts/Assertions+Containers.swift @@ -96,7 +96,7 @@ public func expectContainerContents< } #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW -@available(SwiftStdlib 6.2, *) +@available(SwiftStdlib 5.0, *) public func expectContainersWithEquivalentElements< C1: Container & ~Copyable & ~Escapable, C2: Container & ~Copyable & ~Escapable @@ -109,14 +109,14 @@ public func expectContainersWithEquivalentElements< file: StaticString = #file, line: UInt = #line ) { - if left.elementsEqual(right, by: areEquivalent) { return } + if left.borrowingElementsEqual(right, by: areEquivalent) { return } _expectFailure( "Containers do not have equivalent elements", message, trapping: trapping, file: file, line: line) } /// Check if `left` and `right` contain equal elements in the same order. -@available(SwiftStdlib 6.2, *) +@available(SwiftStdlib 5.0, *) public func expectContainersWithEqualElements< Element: Equatable, C1: Container & ~Copyable & ~Escapable, @@ -129,14 +129,14 @@ public func expectContainersWithEqualElements< file: StaticString = #file, line: UInt = #line ) { - if left.elementsEqual(right) { return } + if left.borrowingElementsEqual(right) { return } _expectFailure( "Containers do not have equal elements", message, trapping: trapping, file: file, line: line) } /// Check if `left` and `right` contain equal elements in the same order. -@available(SwiftStdlib 6.2, *) +@available(SwiftStdlib 5.0, *) public func expectContainerContents< Element: Equatable, C1: Container & ~Copyable & ~Escapable, @@ -149,25 +149,27 @@ public func expectContainerContents< file: StaticString = #file, line: UInt = #line ) { - var i = left.startIndex - var it = right.makeIterator() - while i < left.endIndex { - let a = left[i] - guard let b = it.next() else { - _expectFailure( - "Container is longer than expected", - message, trapping: trapping, file: file, line: line) - return + var it1 = left.startBorrowIteration() + var it2 = right.makeIterator() + while true { + let span = it1.nextSpan() + if span.isEmpty { break } + for i in 0 ..< span.count { + guard let b = it2.next() else { + _expectFailure( + "Container is longer than expected", + message, trapping: trapping, file: file, line: line) + return + } + guard span[i] == b else { + _expectFailure( + "'\(span[i])' is not equal to '\(b)'", + message, trapping: trapping, file: file, line: line) + return + } } - guard a == b else { - _expectFailure( - "'\(a)' at index \(i) is not equal to '\(b)'", - message, trapping: trapping, file: file, line: line) - return - } - left.formIndex(after: &i) } - guard it.next() == nil else { + guard it2.next() == nil else { _expectFailure( "Container is shorter than expected", message, trapping: trapping, file: file, line: line) @@ -176,7 +178,7 @@ public func expectContainerContents< } /// Check if `left` and `right` contain equal elements in the same order. -@available(SwiftStdlib 6.2, *) +@available(SwiftStdlib 5.0, *) public func expectContainerContents< C1: Container & ~Copyable & ~Escapable, C2: Collection, @@ -189,24 +191,29 @@ public func expectContainerContents< file: StaticString = #file, line: UInt = #line ) { - var i = left.startIndex - var it = right.makeIterator() - while i < left.endIndex { - guard let b = it.next() else { - _expectFailure( - "Container is longer than expected", - message, trapping: trapping, file: file, line: line) - return + var it1 = left.startBorrowIteration() + var it2 = right.makeIterator() + var offset = 0 + while true { + let span = it1.nextSpan() + if span.isEmpty { break } + for i in 0 ..< span.count { + guard let b = it2.next() else { + _expectFailure( + "Container is longer than expected", + message, trapping: trapping, file: file, line: line) + return + } + guard areEquivalent(span[i], b) else { + _expectFailure( + "Element at offset \(offset + i) is not equivalent to '\(b)'", + message, trapping: trapping, file: file, line: line) + return + } } - guard areEquivalent(left[i], b) else { - _expectFailure( - "Element at index \(i) is not equal to '\(b)'", - message, trapping: trapping, file: file, line: line) - return - } - left.formIndex(after: &i) + offset += span.count } - guard it.next() == nil else { + guard it2.next() == nil else { _expectFailure( "Container is shorter than expected", message, trapping: trapping, file: file, line: line) diff --git a/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift b/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift index 66efc525..032ec094 100644 --- a/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift +++ b/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift @@ -13,32 +13,7 @@ import XCTest import ContainersPreview -@available(SwiftStdlib 6.2, *) -extension Container where Self: ~Copyable & ~Escapable { - @inlinable - internal func _indicesByIndexAfter() -> [Index] { - var result: [Index] = [] - var i = startIndex - while i != endIndex { - result.append(i) - i = index(after: i) - } - return result - } - - @inlinable - internal func _indicesByFormIndexAfter() -> [Index] { - var result: [Index] = [] - var i = startIndex - while i != endIndex { - result.append(i) - formIndex(after: &i) - } - return result - } -} - -@available(SwiftStdlib 6.2, *) +@available(SwiftStdlib 5.0, *) @inlinable public func checkContainer< C: Container & ~Copyable & ~Escapable, @@ -46,7 +21,7 @@ public func checkContainer< >( _ container: borrowing C, expectedContents: Expected, - file: StaticString = #file, + file: StaticString = #filePath, line: UInt = #line ) where C.Element: Equatable { checkContainer( @@ -56,7 +31,7 @@ public func checkContainer< file: file, line: line) } -@available(SwiftStdlib 6.2, *) +@available(SwiftStdlib 5.0, *) @inlinable public func checkContainer< C: Container & ~Copyable & ~Escapable, @@ -65,7 +40,7 @@ public func checkContainer< _ container: borrowing C, expectedContents: Expected, by areEquivalent: (C.Element, C.Element) -> Bool, - file: StaticString = #file, + file: StaticString = #filePath, line: UInt = #line ) where C.Element: Equatable { let entry = TestContext.current.push("checkContainer", file: file, line: line) @@ -76,131 +51,74 @@ public func checkContainer< let actualCount = container.count expectEqual(actualCount, expectedContents.count) - let validIndices = container._indicesByIndexAfter() - - expectEqual( - container._indicesByIndexAfter(), validIndices, - "Container does not have stable indices") - - // Check that `index(after:)` produces the same results as `formIndex(after:)` - do { - let indicesByFormIndexAfter = container._indicesByFormIndexAfter() - expectEqual(indicesByFormIndexAfter, validIndices) - } - - expectEqual(container.index(container.startIndex, offsetBy: container.count), container.endIndex) - - // Check contents using indexing. - let actualContents = validIndices.map { container[$0] } - expectEquivalentElements(actualContents, expectedContents, by: areEquivalent) - - let allIndices = validIndices + [container.endIndex] - do { - var last: C.Index? = nil - for index in allIndices { - if let last { - // The indices must be monotonically increasing. - expectGreaterThan( - index, last, - "Index \(index) is not greater than immediately preceding index \(last)") - - // Aligning a valid index must not change it. - let nearestDown = container.index(alignedDown: index) - expectEqual(nearestDown, index, "Aligning a valid index down must not change its position") - let nearestUp = container.index(alignedUp: index) - expectEqual(nearestUp, index, "Aligning a valid index up must not change its position") - } - last = index - } - } - - // Check the `Comparable` conformance of the Index type. - if C.Index.self != Int.self { - checkComparable(allIndices, oracle: { .comparing($0, $1) }) - } - - withEveryRange("range", in: 0 ..< expectedContents.count) { range in - let i = range.lowerBound - let j = range.upperBound - - // Check `index(_,offsetBy:)` - let e = container.index(allIndices[i], offsetBy: j - i) - expectEqual(e, allIndices[j]) - if j < expectedContents.count { - expectEquivalent(container[e], expectedContents[j], by: areEquivalent) - } - - // Check `distance(from:to:)` - let d = container.distance(from: allIndices[i], to: allIndices[j]) - expectEqual(d, j - i) - } - - // Check `formIndex(_,offsetBy:limitedBy:)` - let limits = Set([0, allIndices.count - 1, allIndices.count / 2]).sorted() - withEvery("limit", in: limits) { limit in - withEvery("i", in: 0 ..< allIndices.count) { i in - let max = allIndices.count - i + (limit >= i ? 2 : 0) - withEvery("delta", in: 0 ..< max) { delta in - let target = i + delta - var index = allIndices[i] - var d = delta - container.formIndex(&index, offsetBy: &d, limitedBy: allIndices[limit]) - if i > limit { - expectEqual(d, 0, "Nonzero remainder after jump opposite limit") - expectEqual(index, allIndices[target], "Jump opposite limit landed in wrong position") - } else if target <= limit { - expectEqual(d, 0, "Nonzero remainder after jump within limit") - expectEqual(index, allIndices[target], "Jump within limit landed in wrong position") - } else { - expectEqual(d, target - limit, "Unexpected remainder after jump beyond limit") - expectEqual(index, allIndices[limit], "Jump beyond limit landed in unexpected position") - } - } - } - } - // Check that the spans seem plausibly sized and that the indices are monotonic. - let spanShapes: [(offsetRange: Range, indexRange: Range)] = { - var r: [(offsetRange: Range, indexRange: Range)] = [] + let spanShapes: [Range] = { + var r: [Range] = [] var pos = 0 - var index = container.startIndex + var it = container.startBorrowIteration() while true { - let origIndex = index let origPos = pos - let span = container.span(after: &index) + let span = it.nextSpan(maximumCount: nil) pos += span.count if span.isEmpty { - expectEqual(origIndex, container.endIndex) - expectEqual(index, origIndex, "span(after:) is not expected to move the end index") break } - expectGreaterThan( - index, origIndex, "span(after:) does not monotonically increase the index") - expectEqual( - index, allIndices[pos], "span(after:) does not advance the index by the size of the returned span") - r.append((origPos ..< pos, origIndex ..< index)) + r.append(origPos ..< pos) } return r }() expectEqual( - spanShapes.reduce(into: 0, { $0 += $1.offsetRange.count }), actualCount, + spanShapes.reduce(into: 0, { $0 += $1.count }), actualCount, "Container's count does not match the sum of its spans") - // Check that the spans have stable sizes and the expected contents. do { var pos = 0 - var index = container.startIndex + var it = container.startBorrowIteration() var spanIndex = 0 while true { - let span = container.span(after: &index) + let span = it.nextSpan(maximumCount: nil) if span.isEmpty { break } expectEqual( - span.count, spanShapes[spanIndex].offsetRange.count, + span.count, spanShapes[spanIndex].count, "Container has nondeterministic span sizes") + for i in 0 ..< span.count { + expectEqual(span[i], expectedContents[pos]) + pos += 1 + } + spanIndex += 1 + } + expectEqual(spanIndex, spanShapes.endIndex) + expectEqual(pos, expectedContents.count) + } + + // Check that we can iterate one by one. + do { + var pos = 0 + var it = container.startBorrowIteration() + while true { + let span = it.nextSpan(maximumCount: 1) + if span.isEmpty { break } + expectEqual(span.count, 1) + for i in 0 ..< span.count { + expectEqual(span[i], expectedContents[pos]) + pos += 1 + } + } + expectEqual(pos, expectedContents.count) + } + + // Check that we can iterate with huge maximum counts + do { + var pos = 0 + var it = container.startBorrowIteration() + var spanIndex = 0 + while true { + let span = it.nextSpan(maximumCount: Int.max) + if span.isEmpty { break } expectEqual( - index, spanShapes[spanIndex].indexRange.upperBound, - "Container has nondeterministic span boundaries") + span.count, spanShapes[spanIndex].count, + "Container has inconsistent/nondeterministic span sizes") for i in 0 ..< span.count { expectEqual(span[i], expectedContents[pos]) pos += 1 @@ -211,21 +129,5 @@ public func checkContainer< expectEqual(pos, expectedContents.count) } - // Check that we can get a span beginning at every index, and that it extends as much as possible. - do { - for spanIndex in spanShapes.indices { - let (offsetRange, indexRange) = spanShapes[spanIndex] - for pos in offsetRange { - let start = validIndices[pos] - var i = start - let span = container.span(after: &i) - - expectEqual(span.count, offsetRange.upperBound - pos, - "Unexpected span size at offset \(pos), index \(start)") - expectEqual(i, indexRange.upperBound, - "Unexpected span upper bound at offset \(pos), index \(start)") - } - } - } } #endif diff --git a/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift b/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift index 703990e2..b61709f8 100644 --- a/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift +++ b/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift @@ -12,12 +12,14 @@ #if COLLECTIONS_SINGLE_MODULE import Collections #else +import BasicContainers import ContainersPreview #endif #if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW /// A container type with user-defined contents and storage chunks. /// Useful for testing. +@available(SwiftStdlib 5.0, *) public struct StaccatoContainer: ~Copyable { internal let _contents: RigidArray internal let _spanCounts: [Int] @@ -32,20 +34,21 @@ public struct StaccatoContainer: ~Copyable { } } -public struct _StaccatoContainerIndex: Comparable { +@available(SwiftStdlib 5.0, *) +public struct _StaccatoBorrowIterator: BorrowIteratorProtocol, ~Escapable { + internal let _contents: Span + internal let _spanCounts: [Int] + internal let _modulus: Int internal var _offset: Int - internal init(_offset: Int) { - self._offset = _offset + @_lifetime(copy contents) + internal init(contents: Span, spanCounts: [Int]) { + self._contents = contents + self._spanCounts = spanCounts + self._modulus = spanCounts.reduce(into: 0, { $0 += $1 }) + self._offset = 0 } - public static func == (left: Self, right: Self) -> Bool { left._offset == right._offset } - public static func < (left: Self, right: Self) -> Bool { left._offset < right._offset } -} - -extension StaccatoContainer where Element: ~Copyable { - public typealias Index = _StaccatoContainerIndex // rdar://150240032 - func _spanCoordinates(atOffset offset: Int) -> (spanIndex: Int, spanOffset: Int) { precondition(offset >= 0 && offset <= _contents.count) var remainder = offset % _modulus @@ -58,57 +61,28 @@ extension StaccatoContainer where Element: ~Copyable { } return (i, remainder) } + + @_lifetime(copy self) + public mutating func nextSpan(maximumCount: Int?) -> Span { + let (spanIndex, spanOffset) = _spanCoordinates(atOffset: _offset) + let c = _spanCounts[spanIndex] - spanOffset + let startOffset = _offset + let endOffset = Swift.min(startOffset + c, _contents.count) + _offset = endOffset + return _contents.extracting(startOffset ..< endOffset) + + } } -extension StaccatoContainer where Element: ~Copyable { + +@available(SwiftStdlib 5.0, *) +extension StaccatoContainer: Container where Element: ~Copyable { + public typealias BorrowIterator = _StaccatoBorrowIterator // FIXME rdar://150240032 public var isEmpty: Bool { _contents.isEmpty } public var count: Int { _contents.count } - public var startIndex: Index { Index(_offset: 0) } - public var endIndex: Index { Index(_offset: _contents.count) } - public func index(after index: Index) -> Index { - precondition(index >= startIndex && index < endIndex) - return Index(_offset: index._offset + 1) - } - public func formIndex(after i: inout Index) { - i = index(after: i) - } - public func index(_ index: Index, offsetBy n: Int) -> Index { - precondition(index._offset >= 0 && index._offset <= _contents.count) - let offset = index._offset + n - precondition(offset >= 0 && offset <= _contents.count) - return Index(_offset: offset) - } - public func distance(from start: Index, to end: Index) -> Int { - precondition(start >= startIndex && start <= endIndex) - precondition(end >= startIndex && end <= endIndex) - return end._offset - start._offset - } -} - -@available(SwiftStdlib 6.2, *) -extension StaccatoContainer: Container where Element: ~Copyable { - public func formIndex(_ i: inout Index, offsetBy distance: inout Int, limitedBy limit: Index) { - precondition(i >= startIndex && i <= endIndex) - _contents.formIndex(&i._offset, offsetBy: &distance, limitedBy: limit._offset) - } - - @lifetime(borrow self) - public func borrowElement(at index: Index) -> Future.Borrow { - precondition(index >= startIndex && index < endIndex, "Index out of bounds") - return _contents.borrowElement(at: index._offset) - } - - @lifetime(borrow self) - public func nextSpan(after index: inout Index) -> Span { - precondition(index >= startIndex && index <= endIndex) - let span = _contents.span - let (spanIndex, spanOffset) = _spanCoordinates(atOffset: index._offset) - let c = _spanCounts[spanIndex] - spanOffset - let startOffset = index._offset - let endOffset = Swift.min(startOffset + c, span.count) - index._offset = endOffset - return span._extracting(startOffset ..< endOffset) + public func startBorrowIteration() -> BorrowIterator { + BorrowIterator(contents: _contents.span, spanCounts: _spanCounts) } } #endif From db092b7de90109da74a0833df1727ffa94418dd9 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 26 Sep 2025 17:28:33 -0700 Subject: [PATCH 08/16] =?UTF-8?q?Disable=20container=20preview=20trait=20w?= =?UTF-8?q?hile=20we=E2=80=99re=20debugging=20a=20runtime=20crash?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Package.swift | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/Package.swift b/Package.swift index a571a2c4..d95fcbf9 100644 --- a/Package.swift +++ b/Package.swift @@ -12,6 +12,7 @@ import PackageDescription +#if false // FIXME: Disabled while we're debugging a runtime crash (rdar://150240032) let _traits: Set = [ .default( enabledTraits: [ @@ -25,6 +26,7 @@ let _traits: Set = [ protocols and associated algorithms. """), ] +#endif // This package recognizes the conditional compilation flags listed below. // To use enable them, uncomment the corresponding lines or define them @@ -32,9 +34,9 @@ let _traits: Set = [ // // swift build -Xswiftc -DCOLLECTIONS_INTERNAL_CHECKS var defines: [SwiftSetting] = [ - .define( - "COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW", - .when(traits: ["UnstableContainersPreview"])), +// .define( +// "COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW", +// .when(traits: ["UnstableContainersPreview"])), // Enables internal consistency checks at the end of initializers and // mutating operations. This can have very significant overhead, so enabling @@ -362,6 +364,6 @@ let _targets: [Target] = targets.map { $0.toTarget() } let package = Package( name: "swift-collections", products: _products, - traits: _traits, + traits: [], //_traits, targets: _targets ) From 346934794aa14409711fef00762c3bae091b19a0 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 26 Sep 2025 17:32:19 -0700 Subject: [PATCH 09/16] Add package-wide source file header to TrailingElementsModule components --- Sources/TrailingElementsModule/CMakeLists.txt | 2 +- Sources/TrailingElementsModule/TrailingArray.swift | 11 +++++++++++ Sources/TrailingElementsModule/TrailingElements.swift | 11 +++++++++++ Sources/TrailingElementsModule/TrailingPadding.swift | 11 +++++++++++ .../TrailingElementsTests/TrailingElementsTests.swift | 10 ++++++++++ 5 files changed, 44 insertions(+), 1 deletion(-) diff --git a/Sources/TrailingElementsModule/CMakeLists.txt b/Sources/TrailingElementsModule/CMakeLists.txt index 90395398..4eb70d57 100644 --- a/Sources/TrailingElementsModule/CMakeLists.txt +++ b/Sources/TrailingElementsModule/CMakeLists.txt @@ -1,7 +1,7 @@ #[[ This source file is part of the Swift Collections Open Source Project -Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors +Copyright (c) 2025 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 diff --git a/Sources/TrailingElementsModule/TrailingArray.swift b/Sources/TrailingElementsModule/TrailingArray.swift index 65727d19..896ca78a 100644 --- a/Sources/TrailingElementsModule/TrailingArray.swift +++ b/Sources/TrailingElementsModule/TrailingArray.swift @@ -1,3 +1,14 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2025 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 +// +//===----------------------------------------------------------------------===// + /// A value that manages a contiguous block of memory starting with a header /// value and then followed by a contiguous array of elements. Values of this /// type own the underlying memory, and are non-copyable to ensure that diff --git a/Sources/TrailingElementsModule/TrailingElements.swift b/Sources/TrailingElementsModule/TrailingElements.swift index 6f04daa1..4ae0d30e 100644 --- a/Sources/TrailingElementsModule/TrailingElements.swift +++ b/Sources/TrailingElementsModule/TrailingElements.swift @@ -1,3 +1,14 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2025 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 +// +//===----------------------------------------------------------------------===// + /// Describes a type that has some number of elements following it directly /// in memory. Such types are generally used with the `TrailingArray` /// type, which manages storage for the header and its trailing elements. diff --git a/Sources/TrailingElementsModule/TrailingPadding.swift b/Sources/TrailingElementsModule/TrailingPadding.swift index 3af80cba..9da72085 100644 --- a/Sources/TrailingElementsModule/TrailingPadding.swift +++ b/Sources/TrailingElementsModule/TrailingPadding.swift @@ -1,3 +1,14 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2025 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 +// +//===----------------------------------------------------------------------===// + /// Represents memory containing a header value followed by some extra padding /// following it. Values of this type own the underlying memory, and are /// non-copyable to ensure that ownership of that memory is unique. Memory diff --git a/Tests/TrailingElementsTests/TrailingElementsTests.swift b/Tests/TrailingElementsTests/TrailingElementsTests.swift index 3dca17ac..d550bfda 100644 --- a/Tests/TrailingElementsTests/TrailingElementsTests.swift +++ b/Tests/TrailingElementsTests/TrailingElementsTests.swift @@ -1,3 +1,13 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2025 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 +// +//===----------------------------------------------------------------------===// import Testing import TrailingElementsModule From 31d3abcc225339b9dffb68b5d25f389d3bfefda3 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 26 Sep 2025 17:35:47 -0700 Subject: [PATCH 10/16] Reindent TrailingElementsModule --- .../TrailingArray.swift | 707 +++++++++--------- .../TrailingElements.swift | 10 +- .../TrailingPadding.swift | 206 ++--- .../TrailingElementsTests.swift | 269 +++---- 4 files changed, 609 insertions(+), 583 deletions(-) diff --git a/Sources/TrailingElementsModule/TrailingArray.swift b/Sources/TrailingElementsModule/TrailingArray.swift index 896ca78a..1098d556 100644 --- a/Sources/TrailingElementsModule/TrailingArray.swift +++ b/Sources/TrailingElementsModule/TrailingArray.swift @@ -19,377 +19,388 @@ /// it is not stored separately. @frozen public struct TrailingArray: ~Copyable - where Header: ~Copyable +where Header: ~Copyable { - /// A pointer to the raw, underlying storage. This may point before the - /// Header instance in cases where the alignment of Element exceeds that - /// of the Header and we have overallocated to compensate. - @usableFromInline - var _storage: UnsafeMutableRawPointer - - /// Pointer to the header. - @_alwaysEmitIntoClient - var _pointer: UnsafeMutablePointer
{ - Self.headerPointer(fromStorage: _storage) + /// A pointer to the raw, underlying storage. This may point before the + /// Header instance in cases where the alignment of Element exceeds that + /// of the Header and we have overallocated to compensate. + @usableFromInline + var _storage: UnsafeMutableRawPointer + + /// Pointer to the header. + @_alwaysEmitIntoClient + var _pointer: UnsafeMutablePointer
{ + Self.headerPointer(fromStorage: _storage) + } + + /// The element type stored within the buffer. + public typealias Element = Header.Element + + /// Allocate storage and initialize only the header, leaving the trailing + /// elements uninitialized. This is private because it can compromise + /// memory safety. + @_alwaysEmitIntoClient + private init(_headerOnly header: consuming Header) { + let (bytes, alignment) = Self.allocationSize(header: header) + _storage = UnsafeMutableRawPointer.allocate( + byteCount: bytes, + alignment: alignment + ) + + _pointer.initialize(to: header) + } + + @available(SwiftStdlib 5.1, *) + @_alwaysEmitIntoClient + mutating func _initializeTrailingElements( + initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) { + var output = unsafe OutputSpan(buffer: rawElements, initializedCount: 0) + try initializer(&output) + let initialized = unsafe output.finalize(for: rawElements) + precondition(count == initialized, "TrailingArray initialization underflow") + } + + /// Allocate an intrusive managed buffer with the given header and calling + /// the initializer to fill in the trailing elements. + @available(SwiftStdlib 5.1, *) + @_alwaysEmitIntoClient + public init( + header: consuming Header, + initializingTrailingElementsWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) { + self.init(_headerOnly: header) + try _initializeTrailingElements(initializer: initializer) + } + + /// Allocate an intrusive managed buffer with the given header and + /// initializing each trailing element with the given `element`. + @_alwaysEmitIntoClient + public init(header: consuming Header, repeating element: Element) { + self.init(_headerOnly: header) + rawElements.initialize(repeating: element) + } + + /// Deinitialize each of the trailing elements, then the header, then + /// deallocate the underlying storage. + @_alwaysEmitIntoClient + deinit { + rawElements.deinitialize() + _pointer.deinitialize(count: 1) + _storage.deallocate() + } + + /// Take ownership over a pointer to memory containing the header followed + /// by the trailing elements. + /// + /// Once this managed buffer instance is no longer used, this memory will + /// be freed. + /// - Parameters: + /// - pointer: A pointer to the header, which should already have been + /// initialized by the caller. + /// - storage: A pointer to the storage containing the header and + /// pointers. This will usually be `UnsafeMutableRawPointer(pointer)`, + /// but may precede `pointer` if the elements have greater alignment + /// than the header. + @_alwaysEmitIntoClient + public init( + consuming pointer: UnsafeMutablePointer
, + storage: UnsafeMutableRawPointer + ) { + self._storage = storage + precondition( + self._pointer == pointer, + "header pointer does not account for the alignment of the elements" + ) + } + + /// Return the pointer to the underlying memory, including ownership over + /// that memory. The underlying storage will not be freed by this buffer; + /// it is the responsibility of the caller. The header pointer and + /// underlying storage are returned separately, to handle cases where + /// the alignment of the elements is greater than than of the header. + @_alwaysEmitIntoClient + public consuming func leakStorage() -> ( + pointer: UnsafeMutablePointer
, + storage: UnsafeMutableRawPointer + ) { + let pointer = self._pointer + let storage = _storage + discard self + return (pointer, storage) + } + + /// Access the header portion of the buffer. + @_alwaysEmitIntoClient + public var header: Header { + unsafeAddress { + UnsafePointer(_pointer) } - - /// The element type stored within the buffer. - public typealias Element = Header.Element - - /// Allocate storage and initialize only the header, leaving the trailing - /// elements uninitialized. This is private because it can compromise - /// memory safety. - @_alwaysEmitIntoClient - private init(_headerOnly header: consuming Header) { - let (bytes, alignment) = Self.allocationSize(header: header) - _storage = UnsafeMutableRawPointer.allocate( - byteCount: bytes, - alignment: alignment - ) - - _pointer.initialize(to: header) + + unsafeMutableAddress { + _pointer } - - @available(SwiftStdlib 5.1, *) - @_alwaysEmitIntoClient - mutating func _initializeTrailingElements( - initializer: (inout OutputSpan) throws(E) -> Void - ) throws(E) { - var output = unsafe OutputSpan(buffer: rawElements, initializedCount: 0) - try initializer(&output) - let initialized = unsafe output.finalize(for: rawElements) - precondition(count == initialized, "TrailingArray initialization underflow") + } + + /// The number of trailing elements in the value. + @_alwaysEmitIntoClient + public var count: Int { header.trailingCount } + + /// Starting index for accessing the trailing elements. Always 0 + @_alwaysEmitIntoClient + public var startIndex: Int { 0 } + + /// Ending index for accessing the trailing elements. Always `count`. + @_alwaysEmitIntoClient + public var endIndex: Int { count } + + /// Indices covering all of the trailing elements. Always `0.. { 0.. Element { + get { + precondition(index >= 0 && index < count) + return rawElements[index] } - - /// Allocate an intrusive managed buffer with the given header and calling - /// the initializer to fill in the trailing elements. - @available(SwiftStdlib 5.1, *) - @_alwaysEmitIntoClient - public init( - header: consuming Header, - initializingTrailingElementsWith initializer: (inout OutputSpan) throws(E) -> Void - ) throws(E) { - self.init(_headerOnly: header) - try _initializeTrailingElements(initializer: initializer) + + set { + precondition(index >= 0 && index < count) + rawElements[index] = newValue } - - /// Allocate an intrusive managed buffer with the given header and - /// initializing each trailing element with the given `element`. - @_alwaysEmitIntoClient - public init(header: consuming Header, repeating element: Element) { - self.init(_headerOnly: header) - rawElements.initialize(repeating: element) + } + + /// Access the flexible array elements. + @_alwaysEmitIntoClient + var rawElements: UnsafeMutableBufferPointer { + UnsafeMutableBufferPointer( + start: UnsafeMutableRawPointer(_pointer.advanced(by: 1)) + .assumingMemoryBound(to: Element.self), + count: header.trailingCount + ) + } + + /// Accesses the trailing elements following the header. + @available(SwiftStdlib 5.1, *) + @_alwaysEmitIntoClient + public var elements: Span { + @_lifetime(self) + get { + _overrideLifetime(rawElements.span, borrowing: self) } - - /// Deinitialize each of the trailing elements, then the header, then - /// deallocate the underlying storage. - @_alwaysEmitIntoClient - deinit { - rawElements.deinitialize() - _pointer.deinitialize(count: 1) - _storage.deallocate() + } + + /// Accesses the trailing elements following the header, allowing mutation + /// of those elements. + @available(SwiftStdlib 5.1, *) + @_alwaysEmitIntoClient + public var mutableElements: MutableSpan { + @_lifetime(self) + mutating get { + let elements = self.rawElements.mutableSpan + return _overrideLifetime(elements, mutating: &self) } - - /// Take ownership over a pointer to memory containing the header followed - /// by the trailing elements. - /// - /// Once this managed buffer instance is no longer used, this memory will - /// be freed. - /// - Parameters: - /// - pointer: A pointer to the header, which should already have been - /// initialized by the caller. - /// - storage: A pointer to the storage containing the header and - /// pointers. This will usually be `UnsafeMutableRawPointer(pointer)`, - /// but may precede `pointer` if the elements have greater alignment - /// than the header. - @_alwaysEmitIntoClient - public init( - consuming pointer: UnsafeMutablePointer
, - storage: UnsafeMutableRawPointer - ) { - self._storage = storage - precondition( - self._pointer == pointer, - "header pointer does not account for the alignment of the elements" - ) + } + + /// Execute the given closure, providing it with an unsafe buffer pointer + /// referencing the header. + @_alwaysEmitIntoClient + public mutating func withUnsafeMutablePointerToHeader( + _ body: (UnsafeMutablePointer
) throws(E) -> R + ) throws(E) -> R { + return try body(_pointer) + } + + /// Execute the given closure, providing it with an unsafe buffer pointer + /// referencing the trailing elements. + @_alwaysEmitIntoClient + public mutating func withUnsafeMutablePointerToElements( + _ body: (UnsafeMutableBufferPointer) throws(E) -> R + ) throws(E) -> R { + return try body(rawElements) + } + + /// Execute the given closure, providing it with unsafe pointers to the + /// header and trailing elements, respectively. + @_alwaysEmitIntoClient + public mutating func withUnsafeMutablePointers( + _ body: (UnsafeMutablePointer
, UnsafeMutableBufferPointer) throws(E) -> R + ) throws(E) -> R { + return try body(_pointer, rawElements) + } + + /// Determine the allocation size and alignment needed for the given header + /// value along with its trailing elements. + /// + /// In cases where the element's alignment exceeds that of the header, + /// this operation will suggest overallocation so that the elements can be + /// properly aligned following the header. + @_alwaysEmitIntoClient + static func allocationSize(header: borrowing Header) -> (size: Int, alignment: Int) { + // The number of bytes needed to contain the header and elements, + // assuming that there are no alignment issues. + let numBytes = MemoryLayout
.stride + MemoryLayout.stride * header.trailingCount + + let headerAlignment = MemoryLayout
.alignment + let elementAlignment = MemoryLayout.alignment + + // If the header provides sufficient alignment for the elements, + // we're done. + if elementAlignment <= headerAlignment { + return (numBytes, MemoryLayout
.alignment) } - - /// Return the pointer to the underlying memory, including ownership over - /// that memory. The underlying storage will not be freed by this buffer; - /// it is the responsibility of the caller. The header pointer and - /// underlying storage are returned separately, to handle cases where - /// the alignment of the elements is greater than than of the header. - @_alwaysEmitIntoClient - public consuming func leakStorage() -> ( - pointer: UnsafeMutablePointer
, - storage: UnsafeMutableRawPointer - ) { - let pointer = self._pointer - let storage = _storage - discard self - return (pointer, storage) - } - - /// Access the header portion of the buffer. - @_alwaysEmitIntoClient - public var header: Header { - unsafeAddress { - UnsafePointer(_pointer) - } - - unsafeMutableAddress { - _pointer - } - } - - /// The number of trailing elements in the value. - @_alwaysEmitIntoClient - public var count: Int { header.trailingCount } - - /// Starting index for accessing the trailing elements. Always 0 - @_alwaysEmitIntoClient - public var startIndex: Int { 0 } - - /// Ending index for accessing the trailing elements. Always `count`. - @_alwaysEmitIntoClient - public var endIndex: Int { count } - - /// Indices covering all of the trailing elements. Always `0.. { 0.. Element { - get { - precondition(index >= 0 && index < count) - return rawElements[index] - } - - set { - precondition(index >= 0 && index < count) - rawElements[index] = newValue - } - } - - /// Access the flexible array elements. - @_alwaysEmitIntoClient - var rawElements: UnsafeMutableBufferPointer { - UnsafeMutableBufferPointer( - start: UnsafeMutableRawPointer(_pointer.advanced(by: 1)) - .assumingMemoryBound(to: Element.self), - count: header.trailingCount - ) - } - - /// Accesses the trailing elements following the header. - @available(SwiftStdlib 5.1, *) - @_alwaysEmitIntoClient - public var elements: Span { - @_lifetime(self) - get { - _overrideLifetime(rawElements.span, borrowing: self) - } - } - - /// Accesses the trailing elements following the header, allowing mutation - /// of those elements. - @available(SwiftStdlib 5.1, *) - @_alwaysEmitIntoClient - public var mutableElements: MutableSpan { - @_lifetime(self) - mutating get { - let elements = self.rawElements.mutableSpan - return _overrideLifetime(elements, mutating: &self) - } - } - - /// Execute the given closure, providing it with an unsafe buffer pointer - /// referencing the header. - @_alwaysEmitIntoClient - public mutating func withUnsafeMutablePointerToHeader(_ body: (UnsafeMutablePointer
) throws(E) -> R) throws(E) -> R { - return try body(_pointer) - } - - /// Execute the given closure, providing it with an unsafe buffer pointer - /// referencing the trailing elements. - @_alwaysEmitIntoClient - public mutating func withUnsafeMutablePointerToElements(_ body: (UnsafeMutableBufferPointer) throws(E) -> R) throws(E) -> R { - return try body(rawElements) - } - - /// Execute the given closure, providing it with unsafe pointers to the - /// header and trailing elements, respectively. - @_alwaysEmitIntoClient - public mutating func withUnsafeMutablePointers( - _ body: (UnsafeMutablePointer
, UnsafeMutableBufferPointer) throws(E) -> R - ) throws(E) -> R { - return try body(_pointer, rawElements) - } - - /// Determine the allocation size and alignment needed for the given header - /// value along with its trailing elements. - /// - /// In cases where the element's alignment exceeds that of the header, - /// this operation will suggest overallocation so that the elements can be - /// properly aligned following the header. - @_alwaysEmitIntoClient - static func allocationSize(header: borrowing Header) -> (size: Int, alignment: Int) { - // The number of bytes needed to contain the header and elements, - // assuming that there are no alignment issues. - let numBytes = MemoryLayout
.stride + MemoryLayout.stride * header.trailingCount - - let headerAlignment = MemoryLayout
.alignment - let elementAlignment = MemoryLayout.alignment - - // If the header provides sufficient alignment for the elements, - // we're done. - if elementAlignment <= headerAlignment { - return (numBytes, MemoryLayout
.alignment) - } - - // We may have to slide an allocation by up to the difference between - // the element and header alignments to ensure that the elements are - // appropriately aligned. - return (numBytes + elementAlignment - headerAlignment, - MemoryLayout.alignment) - } - - /// Given storage that is large enough to accommodate padding + the header - /// + the elements, return the header pointer from the storage pointer. - @_alwaysEmitIntoClient - static func headerPointer(fromStorage storage: UnsafeMutableRawPointer) -> UnsafeMutablePointer
{ - let headerAlignment = MemoryLayout
.alignment - let elementAlignment = MemoryLayout.alignment - - // Normal case: the header has sufficient alignment to include the - // elements, so the storage refers directly to the header. - if elementAlignment <= headerAlignment { - return storage.assumingMemoryBound(to: Header.self) - } - - // The header is stored right before the elements, with padding bytes - // between the start of the allocation and up to the header. - return storage.advanced(by: MemoryLayout
.stride) - .alignedUp(for: Element.self) - .advanced(by: -MemoryLayout
.stride) - .assumingMemoryBound(to: Header.self) + + // We may have to slide an allocation by up to the difference between + // the element and header alignments to ensure that the elements are + // appropriately aligned. + return ( + numBytes + elementAlignment - headerAlignment, + MemoryLayout.alignment) + } + + /// Given storage that is large enough to accommodate padding + the header + /// + the elements, return the header pointer from the storage pointer. + @_alwaysEmitIntoClient + static func headerPointer(fromStorage storage: UnsafeMutableRawPointer) -> UnsafeMutablePointer
{ + let headerAlignment = MemoryLayout
.alignment + let elementAlignment = MemoryLayout.alignment + + // Normal case: the header has sufficient alignment to include the + // elements, so the storage refers directly to the header. + if elementAlignment <= headerAlignment { + return storage.assumingMemoryBound(to: Header.self) } + + // The header is stored right before the elements, with padding bytes + // between the start of the allocation and up to the header. + return storage.advanced(by: MemoryLayout
.stride) + .alignedUp(for: Element.self) + .advanced(by: -MemoryLayout
.stride) + .assumingMemoryBound(to: Header.self) + } } extension TrailingArray where Header: ~Copyable, Header.Element: BitwiseCopyable { - /// Allocate an intrusive managed buffer with the given header, but leaving the - /// trailing elements uninitialized. - @_alwaysEmitIntoClient - @unsafe - public init(header: consuming Header, uninitializedTrailingElements: ()) { - self.init(_headerOnly: header) - } + /// Allocate an intrusive managed buffer with the given header, but leaving the + /// trailing elements uninitialized. + @_alwaysEmitIntoClient + @unsafe + public init(header: consuming Header, uninitializedTrailingElements: ()) { + self.init(_headerOnly: header) + } } extension TrailingArray where Header: Copyable { - /// Create a temporary intrusive managed buffer for the given header, whose - /// trailing elements are initialized to copies of `element`. That instance - /// is provided to the given `body` to operate on for the duration of the - /// call. The temporary is allocated on the stack, unless it is very - /// large according to `withUnsafeTemporaryAllocation`. - @_alwaysEmitIntoClient - public static func withTemporaryValue( - header: consuming Header, - repeating element: Element, - body: (inout TrailingArray
) throws(E) -> R - ) throws(E) -> R { - return try _withTemporaryValue(header: header, uninitializedTrailingElements: ()) { (value) throws(E) in - value.rawElements.initialize(repeating: element) - return try body(&value) - } + /// Create a temporary intrusive managed buffer for the given header, whose + /// trailing elements are initialized to copies of `element`. That instance + /// is provided to the given `body` to operate on for the duration of the + /// call. The temporary is allocated on the stack, unless it is very + /// large according to `withUnsafeTemporaryAllocation`. + @_alwaysEmitIntoClient + public static func withTemporaryValue( + header: consuming Header, + repeating element: Element, + body: (inout TrailingArray
) throws(E) -> R + ) throws(E) -> R { + return try _withTemporaryValue( + header: header, uninitializedTrailingElements: () + ) { (value) throws(E) in + value.rawElements.initialize(repeating: element) + return try body(&value) } - - /// Create a temporary intrusive managed buffer for the given header, whose - /// trailing elements are initialized with the given `initializer` function. - /// That instance is provided to the given `body` to operate on for the - /// duration of the call. The temporary is allocated on the stack, unless - /// it is very large according to `withUnsafeTemporaryAllocation`. - @available(SwiftStdlib 5.1, *) - @_alwaysEmitIntoClient - public static func withTemporaryValue( - header: consuming Header, - initializingTrailingElementsWith initializer: (inout OutputSpan) throws(E) -> Void, - body: (inout TrailingArray
) throws(E) -> R - ) throws(E) -> R { - return try _withTemporaryValue(header: header, uninitializedTrailingElements: ()) { (value) throws(E) in - try value._initializeTrailingElements(initializer: initializer) - return try body(&value) - } + } + + /// Create a temporary intrusive managed buffer for the given header, whose + /// trailing elements are initialized with the given `initializer` function. + /// That instance is provided to the given `body` to operate on for the + /// duration of the call. The temporary is allocated on the stack, unless + /// it is very large according to `withUnsafeTemporaryAllocation`. + @available(SwiftStdlib 5.1, *) + @_alwaysEmitIntoClient + public static func withTemporaryValue( + header: consuming Header, + initializingTrailingElementsWith initializer: (inout OutputSpan) throws(E) -> Void, + body: (inout TrailingArray
) throws(E) -> R + ) throws(E) -> R { + return try _withTemporaryValue( + header: header, uninitializedTrailingElements: () + ) { (value) throws(E) in + try value._initializeTrailingElements(initializer: initializer) + return try body(&value) } + } } extension TrailingArray { - /// Create a temporary intrusive managed buffer for the given header, whose - /// trailing elements are left uninitialized. That instance is provided to - /// the given `body` to operate on for the duration of the - /// call. The temporary is allocated on the stack, unless it is very - /// large according to `withUnsafeTemporaryAllocation`. - @_alwaysEmitIntoClient - @unsafe - static func _withTemporaryValue( - header: Header, - uninitializedTrailingElements: (), - body: (inout TrailingArray
) throws(E) -> R - ) throws(E) -> R { - let (numBytes, alignment) = allocationSize(header: header) - - // Allocate temporary storage large enough for the value we need. - let result: Result = withUnsafeTemporaryAllocation( - byteCount: numBytes, - alignment: alignment - ) { buffer in - // Initialize the header within the temporary allocation. - let storagePointer = buffer.baseAddress! - let headerPointer = TrailingArray.headerPointer(fromStorage: storagePointer) - headerPointer.initialize(to: header) - - /// Create a trailing array over that temporary storage. - var managedBuffer = TrailingArray(consuming: headerPointer, - storage: storagePointer) - let resultOrError: Result - do throws(E) { - resultOrError = .success(try body(&managedBuffer)) - } catch { - resultOrError = .failure(error) - } - - // Deinitialize the elements and header. - managedBuffer.rawElements.deinitialize() - managedBuffer._pointer.deinitialize(count: 1) - - // Tell the trailing buffer not to free the storage. - let (finalPointer, finalStorage) = managedBuffer.leakStorage() - precondition(finalPointer == headerPointer) - precondition(finalStorage == storagePointer) - - return resultOrError - } - - return try result.get() + /// Create a temporary intrusive managed buffer for the given header, whose + /// trailing elements are left uninitialized. That instance is provided to + /// the given `body` to operate on for the duration of the + /// call. The temporary is allocated on the stack, unless it is very + /// large according to `withUnsafeTemporaryAllocation`. + @_alwaysEmitIntoClient + @unsafe + static func _withTemporaryValue( + header: Header, + uninitializedTrailingElements: (), + body: (inout TrailingArray
) throws(E) -> R + ) throws(E) -> R { + let (numBytes, alignment) = allocationSize(header: header) + + // Allocate temporary storage large enough for the value we need. + let result: Result = withUnsafeTemporaryAllocation( + byteCount: numBytes, + alignment: alignment + ) { buffer in + // Initialize the header within the temporary allocation. + let storagePointer = buffer.baseAddress! + let headerPointer = TrailingArray.headerPointer(fromStorage: storagePointer) + headerPointer.initialize(to: header) + + /// Create a trailing array over that temporary storage. + var managedBuffer = TrailingArray(consuming: headerPointer, + storage: storagePointer) + let resultOrError: Result + do throws(E) { + resultOrError = .success(try body(&managedBuffer)) + } catch { + resultOrError = .failure(error) + } + + // Deinitialize the elements and header. + managedBuffer.rawElements.deinitialize() + managedBuffer._pointer.deinitialize(count: 1) + + // Tell the trailing buffer not to free the storage. + let (finalPointer, finalStorage) = managedBuffer.leakStorage() + precondition(finalPointer == headerPointer) + precondition(finalStorage == storagePointer) + + return resultOrError } + + return try result.get() + } } extension TrailingArray where Header.Element: BitwiseCopyable { - /// Create a temporary intrusive managed buffer for the given header, whose - /// trailing elements are left uninitialized. That instance is provided to - /// the given `body` to operate on for the duration of the - /// call. The temporary is allocated on the stack, unless it is very - /// large according to `withUnsafeTemporaryAllocation`. - @_alwaysEmitIntoClient - @unsafe - public static func withTemporaryValue( - header: consuming Header, - uninitializedTrailingElements: (), - body: (inout TrailingArray
) throws(E) -> R - ) throws(E) -> R { - return try _withTemporaryValue(header: header, uninitializedTrailingElements: ()) { (value) throws(E) in - try body(&value) - } + /// Create a temporary intrusive managed buffer for the given header, whose + /// trailing elements are left uninitialized. That instance is provided to + /// the given `body` to operate on for the duration of the + /// call. The temporary is allocated on the stack, unless it is very + /// large according to `withUnsafeTemporaryAllocation`. + @_alwaysEmitIntoClient + @unsafe + public static func withTemporaryValue( + header: consuming Header, + uninitializedTrailingElements: (), + body: (inout TrailingArray
) throws(E) -> R + ) throws(E) -> R { + return try _withTemporaryValue( + header: header, uninitializedTrailingElements: () + ) { (value) throws(E) in + try body(&value) } + } } diff --git a/Sources/TrailingElementsModule/TrailingElements.swift b/Sources/TrailingElementsModule/TrailingElements.swift index 4ae0d30e..4bc218c0 100644 --- a/Sources/TrailingElementsModule/TrailingElements.swift +++ b/Sources/TrailingElementsModule/TrailingElements.swift @@ -13,9 +13,9 @@ /// in memory. Such types are generally used with the `TrailingArray` /// type, which manages storage for the header and its trailing elements. public protocol TrailingElements: ~Copyable { - /// The element type of the data that follows the header in memory. - associatedtype Element - - /// The number of elements following the header. - var trailingCount: Int { get } + /// The element type of the data that follows the header in memory. + associatedtype Element + + /// The number of elements following the header. + var trailingCount: Int { get } } diff --git a/Sources/TrailingElementsModule/TrailingPadding.swift b/Sources/TrailingElementsModule/TrailingPadding.swift index 9da72085..45f4ffae 100644 --- a/Sources/TrailingElementsModule/TrailingPadding.swift +++ b/Sources/TrailingElementsModule/TrailingPadding.swift @@ -26,112 +26,116 @@ /// `IntrusiveManagedPointer` instead. @frozen public struct TrailingPadding: ~Copyable { - /// Pointer to the header, followed by the padding. - @usableFromInline - let _pointer: UnsafeMutablePointer
- - /// Create a new instance with the given header and total size. The total - /// size includes the storage for the header itself, so it must be at least - /// as large as the header. - @_alwaysEmitIntoClient - public init(header: consuming Header, totalSize size: Int) { - precondition(size >= MemoryLayout
.size, - "must allocate enough storage for the underlying stored type") - _pointer = UnsafeMutableRawPointer.allocate(byteCount: size, alignment: MemoryLayout
.alignment) - .assumingMemoryBound(to: Header.self) - _pointer.initialize(to: header) + /// Pointer to the header, followed by the padding. + @usableFromInline + let _pointer: UnsafeMutablePointer
+ + /// Create a new instance with the given header and total size. The total + /// size includes the storage for the header itself, so it must be at least + /// as large as the header. + @_alwaysEmitIntoClient + public init(header: consuming Header, totalSize size: Int) { + precondition(size >= MemoryLayout
.size, + "must allocate enough storage for the underlying stored type") + _pointer = UnsafeMutableRawPointer + .allocate(byteCount: size, alignment: MemoryLayout
.alignment) + .assumingMemoryBound(to: Header.self) + _pointer.initialize(to: header) + } + + /// Take ownership over a pointer to memory containing the header followed + /// by the trailing elements. + /// + /// Once this padded storage is no longer used, this memory will be + /// deinitialized and freed. + @_alwaysEmitIntoClient + public init(consuming pointer: UnsafeMutablePointer
) { + self._pointer = pointer + } + + /// Deinitializes the header, then deallocates the underlying memory. + @_alwaysEmitIntoClient + deinit { + _pointer.deinitialize(count: 1) + _pointer.deallocate() + } + + /// Access the header portion of the value. + @_alwaysEmitIntoClient + public var header: Header { + unsafeAddress { + UnsafePointer(_pointer) } - - /// Take ownership over a pointer to memory containing the header followed - /// by the trailing elements. - /// - /// Once this padded storage is no longer used, this memory will be - /// deinitialized and freed. - @_alwaysEmitIntoClient - public init(consuming pointer: UnsafeMutablePointer
) { - self._pointer = pointer - } - - /// Deinitializes the header, then deallocates the underlying memory. - @_alwaysEmitIntoClient - deinit { - _pointer.deinitialize(count: 1) - _pointer.deallocate() - } - - /// Access the header portion of the value. - @_alwaysEmitIntoClient - public var header: Header { - unsafeAddress { - UnsafePointer(_pointer) - } - - unsafeMutableAddress { - _pointer - } - } - - /// Executes the given closure with the pointer to the header itself. - @_alwaysEmitIntoClient - public func withUnsafeMutablePointerToHeader(_ body: (UnsafeMutablePointer
) throws(E) -> R) throws(E) -> R { - return try body(_pointer) - } - - /// Take ownership over the stored memory, returning its pointer. The - /// underlying storage will not be freed by the `TrailingPadding` instance, - /// as it is the responsibility of the caller. - @_alwaysEmitIntoClient - public consuming func leakStorage() -> UnsafeMutablePointer
{ - let pointer = self._pointer - discard self - return pointer + + unsafeMutableAddress { + _pointer } + } + + /// Executes the given closure with the pointer to the header itself. + @_alwaysEmitIntoClient + public func withUnsafeMutablePointerToHeader( + _ body: (UnsafeMutablePointer
) throws(E) -> R + ) throws(E) -> R { + return try body(_pointer) + } + + /// Take ownership over the stored memory, returning its pointer. The + /// underlying storage will not be freed by the `TrailingPadding` instance, + /// as it is the responsibility of the caller. + @_alwaysEmitIntoClient + public consuming func leakStorage() -> UnsafeMutablePointer
{ + let pointer = self._pointer + discard self + return pointer + } } -extension TrailingPadding: @unchecked Sendable where Header: Sendable, Header: ~Copyable { } +extension TrailingPadding: @unchecked Sendable +where Header: Sendable, Header: ~Copyable { } extension TrailingPadding where Header: Copyable { - /// Create a temporary for the given header with additional storage, - /// providing that instance to the given `body` to operate on for the - /// duration. The temporary is allocated on the stack (unless it is very - /// large), eliminating the need for heap allocation of variable-size - /// values. - @_alwaysEmitIntoClient - public static func withTemporaryValue( - header: Header, - totalSize size: Int, - body: (inout TrailingPadding
) throws(E) -> R - ) throws(E) -> R { - precondition(size >= MemoryLayout
.size, - "must allocate enough storage for the underlying stored type") - - // Allocate temporary storage large enough for the value we need. - let result: Result = withUnsafeTemporaryAllocation( - byteCount: size, - alignment: MemoryLayout
.alignment - ) { buffer in - /// Create a tail-allocated storage over that temporary storage. - let pointer = buffer.baseAddress!.assumingMemoryBound(to: Header.self) - pointer.initialize(to: header) - var tailAllocated = TrailingPadding(consuming: pointer) - - do throws(E) { - let result = try body(&tailAllocated) - - // Tell the tail-allocated buffer not to free the storage. - let finalPointer = tailAllocated.leakStorage() - precondition(finalPointer == pointer) - - return .success(result) - } catch { - // Tell the tail-allocated buffer not to free the storage. - let finalPointer = tailAllocated.leakStorage() - precondition(finalPointer == pointer) - - return .failure(error) - } - } - - return try result.get() + /// Create a temporary for the given header with additional storage, + /// providing that instance to the given `body` to operate on for the + /// duration. The temporary is allocated on the stack (unless it is very + /// large), eliminating the need for heap allocation of variable-size + /// values. + @_alwaysEmitIntoClient + public static func withTemporaryValue( + header: Header, + totalSize size: Int, + body: (inout TrailingPadding
) throws(E) -> R + ) throws(E) -> R { + precondition(size >= MemoryLayout
.size, + "must allocate enough storage for the underlying stored type") + + // Allocate temporary storage large enough for the value we need. + let result: Result = withUnsafeTemporaryAllocation( + byteCount: size, + alignment: MemoryLayout
.alignment + ) { buffer in + /// Create a tail-allocated storage over that temporary storage. + let pointer = buffer.baseAddress!.assumingMemoryBound(to: Header.self) + pointer.initialize(to: header) + var tailAllocated = TrailingPadding(consuming: pointer) + + do throws(E) { + let result = try body(&tailAllocated) + + // Tell the tail-allocated buffer not to free the storage. + let finalPointer = tailAllocated.leakStorage() + precondition(finalPointer == pointer) + + return .success(result) + } catch { + // Tell the tail-allocated buffer not to free the storage. + let finalPointer = tailAllocated.leakStorage() + precondition(finalPointer == pointer) + + return .failure(error) + } } + + return try result.get() + } } diff --git a/Tests/TrailingElementsTests/TrailingElementsTests.swift b/Tests/TrailingElementsTests/TrailingElementsTests.swift index d550bfda..51d8a8a6 100644 --- a/Tests/TrailingElementsTests/TrailingElementsTests.swift +++ b/Tests/TrailingElementsTests/TrailingElementsTests.swift @@ -12,156 +12,167 @@ import Testing import TrailingElementsModule struct Point { - var x: Int - var y: Int + var x: Int + var y: Int } struct Coordinates { - var numCoordinates: Int + var numCoordinates: Int } extension Coordinates: TrailingElements { - typealias Element = Point - var trailingCount: Int { numCoordinates } + typealias Element = Point + var trailingCount: Int { numCoordinates } } struct OneByteWithPointers: TrailingElements { - var byte: UInt8 - - init(count: Int) { - self.byte = UInt8(count) - } - - typealias Element = OpaquePointer - var trailingCount: Int { Int(byte) } + var byte: UInt8 + + init(count: Int) { + self.byte = UInt8(count) + } + + typealias Element = OpaquePointer + var trailingCount: Int { Int(byte) } } struct ManyBytesWithPointers: TrailingElements { - var bytes: (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8) - - init(count: Int) { - self.bytes = (UInt8(count), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) - } - - typealias Element = OpaquePointer - var trailingCount: Int { Int(bytes.0) } + var bytes: ( + UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, + UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, + UInt8, UInt8) + + init(count: Int) { + self.bytes = ( + UInt8(count), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) + } + + typealias Element = OpaquePointer + var trailingCount: Int { Int(bytes.0) } } @Suite("Trailing elements tests") struct TrailingElementsTests { - @Test func simpleCoordinates() { - var coords = TrailingArray(header: Coordinates(numCoordinates: 3)) { outputSpan in - outputSpan.append(Point(x: 1, y: 2)) - outputSpan.append(Point(x: 2, y: 3)) - outputSpan.append(Point(x: 3, y: 4)) - } - - #expect(coords[0].x == 1) - #expect(coords[1].x == 2) - #expect(coords[2].x == 3) - - coords[1].y = 17 - #expect(coords[1].y == 17) + @Test func simpleCoordinates() { + var coords = TrailingArray( + header: Coordinates(numCoordinates: 3) + ) { outputSpan in + outputSpan.append(Point(x: 1, y: 2)) + outputSpan.append(Point(x: 2, y: 3)) + outputSpan.append(Point(x: 3, y: 4)) } - - @Test func repeatingInit() { - var coords = TrailingArray(header: Coordinates(numCoordinates: 3), repeating: Point(x: 1, y: 1)) - - #expect(coords[0].x == 1) - #expect(coords[1].x == 1) - #expect(coords[2].x == 1) - - coords[1].x = 17 - #expect(coords[0].x == 1) - #expect(coords[1].x == 17) - #expect(coords[2].x == 1) + + #expect(coords[0].x == 1) + #expect(coords[1].x == 2) + #expect(coords[2].x == 3) + + coords[1].y = 17 + #expect(coords[1].y == 17) + } + + @Test func repeatingInit() { + var coords = TrailingArray( + header: Coordinates(numCoordinates: 3), repeating: Point(x: 1, y: 1)) + + #expect(coords[0].x == 1) + #expect(coords[1].x == 1) + #expect(coords[2].x == 1) + + coords[1].x = 17 + #expect(coords[0].x == 1) + #expect(coords[1].x == 17) + #expect(coords[2].x == 1) + } + + @Test func temporaryCoordinates() { + TrailingArray.withTemporaryValue( + header: Coordinates(numCoordinates: 3) + ) { outputSpan in + outputSpan.append(Point(x: 1, y: 2)) + outputSpan.append(Point(x: 2, y: 3)) + outputSpan.append(Point(x: 3, y: 4)) + } body: { coords in + #expect(coords[0].x == 1) + #expect(coords[1].x == 2) + #expect(coords[2].x == 3) } - - @Test func temporaryCoordinates() { - TrailingArray.withTemporaryValue(header: Coordinates(numCoordinates: 3)) { outputSpan in - outputSpan.append(Point(x: 1, y: 2)) - outputSpan.append(Point(x: 2, y: 3)) - outputSpan.append(Point(x: 3, y: 4)) - } body: { coords in - #expect(coords[0].x == 1) - #expect(coords[1].x == 2) - #expect(coords[2].x == 3) - } + } + + @Test(arguments: 0 ... 10) + func underalignedByteOnHeap(count: Int) { + var pointers = TrailingArray( + header: OneByteWithPointers(count: count) + ) { outputSpan in + for i in 0...stride)) == - UnsafeMutableRawPointer(elementsPtr.baseAddress)) - } + + for i in 0...stride)) == - UnsafeMutableRawPointer(elementsPtr.baseAddress)) - } - } + + pointers.withUnsafeMutablePointers { headerPtr, elementsPtr in + let p1 = headerPtr.advanced(by: MemoryLayout.stride) + let p2 = elementsPtr.baseAddress + #expect(UnsafeMutableRawPointer(p1) == UnsafeMutableRawPointer(p2)) } - - @Test(arguments: 0 ... 10) - func underalignedBytesOnHeap(count: Int) { - var pointers = TrailingArray(header: ManyBytesWithPointers(count: count)) { outputSpan in - for i in 0...stride)) == - UnsafeMutableRawPointer(elementsPtr.baseAddress)) - } + } + + @Test(arguments: 0 ... 10) + func underalignedByteOnStack(count: Int) { + TrailingArray.withTemporaryValue(header: OneByteWithPointers(count: count)) { outputSpan in + for i in 0...stride) + let p2 = elementsPtr.baseAddress + #expect(UnsafeMutableRawPointer(p1) == UnsafeMutableRawPointer(p2)) + } } - - @Test(arguments: 0 ... 10) - func underalignedBytesOnStack(count: Int) { - TrailingArray.withTemporaryValue(header: ManyBytesWithPointers(count: count)) { outputSpan in - for i in 0...stride)) == - UnsafeMutableRawPointer(elementsPtr.baseAddress)) - } - } + } + + @Test(arguments: 0 ... 10) + func underalignedBytesOnHeap(count: Int) { + var pointers = TrailingArray(header: ManyBytesWithPointers(count: count)) { outputSpan in + for i in 0...stride) + let p2 = elementsPtr.baseAddress + #expect(UnsafeMutableRawPointer(p1) == UnsafeMutableRawPointer(p2)) + } + } + + @Test(arguments: 0 ... 10) + func underalignedBytesOnStack(count: Int) { + TrailingArray.withTemporaryValue(header: ManyBytesWithPointers(count: count)) { outputSpan in + for i in 0...stride) + let p2 = elementsPtr.baseAddress + #expect(UnsafeMutableRawPointer(p1) == UnsafeMutableRawPointer(p2)) + } + } + } } From 097ea09b6ab1c0b81e55f79a4b0e91d64dc61181 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 26 Sep 2025 18:47:02 -0700 Subject: [PATCH 11/16] Update Collections.xcodeproj --- .../Container+Utilities.swift | 2 + .../TrailingElementsTests.swift | 6 ++ Xcode/Collections.xcodeproj/project.pbxproj | 84 +++++++++++++++---- Xcode/Shared.xcconfig | 1 + 4 files changed, 77 insertions(+), 16 deletions(-) diff --git a/Sources/ContainersPreview/Container+Utilities.swift b/Sources/ContainersPreview/Container+Utilities.swift index 7696b264..407594ad 100644 --- a/Sources/ContainersPreview/Container+Utilities.swift +++ b/Sources/ContainersPreview/Container+Utilities.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import InternalCollectionsUtilities +#endif #if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW diff --git a/Tests/TrailingElementsTests/TrailingElementsTests.swift b/Tests/TrailingElementsTests/TrailingElementsTests.swift index 51d8a8a6..666f1d8e 100644 --- a/Tests/TrailingElementsTests/TrailingElementsTests.swift +++ b/Tests/TrailingElementsTests/TrailingElementsTests.swift @@ -8,8 +8,14 @@ // See https://swift.org/LICENSE.txt for license information // //===----------------------------------------------------------------------===// + import Testing + +#if COLLECTIONS_SINGLE_MODULE +import Collections +#else import TrailingElementsModule +#endif struct Point { var x: Int diff --git a/Xcode/Collections.xcodeproj/project.pbxproj b/Xcode/Collections.xcodeproj/project.pbxproj index 6c899ca2..a4afaa12 100644 --- a/Xcode/Collections.xcodeproj/project.pbxproj +++ b/Xcode/Collections.xcodeproj/project.pbxproj @@ -10,13 +10,9 @@ 7D48BCD12E51524200D7F6F7 /* InputSpan.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCCB2E51524200D7F6F7 /* InputSpan.swift */; }; 7D48BCD32E51524200D7F6F7 /* Box.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCC82E51524200D7F6F7 /* Box.swift */; }; 7D48BCD62E51524200D7F6F7 /* Shared.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCCD2E51524200D7F6F7 /* Shared.swift */; }; - 7D48BCD82E51524200D7F6F7 /* Borrow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCC72E51524200D7F6F7 /* Borrow.swift */; }; - 7D48BCD92E51524200D7F6F7 /* Inout.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCCA2E51524200D7F6F7 /* Inout.swift */; }; 7D48BCDC2E51554900D7F6F7 /* ClassBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCDB2E51554900D7F6F7 /* ClassBox.swift */; }; 7D48BCDF2E51558700D7F6F7 /* TestPrintable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCDD2E51558700D7F6F7 /* TestPrintable.swift */; }; 7D48BCE02E51558700D7F6F7 /* LifetimeTrackedStruct.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCDE2E51558700D7F6F7 /* LifetimeTrackedStruct.swift */; }; - 7D48BCEC2E5158A100D7F6F7 /* InoutTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCE72E5158A100D7F6F7 /* InoutTests.swift */; }; - 7D48BCED2E5158A100D7F6F7 /* BorrowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCE52E5158A100D7F6F7 /* BorrowTests.swift */; }; 7D48BCEE2E5158A100D7F6F7 /* BoxTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCE62E5158A100D7F6F7 /* BoxTests.swift */; }; 7D48BCF02E51597200D7F6F7 /* Assertions+Containers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCEF2E51597200D7F6F7 /* Assertions+Containers.swift */; }; 7D48BCF22E51599200D7F6F7 /* CheckContainer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCF12E51599200D7F6F7 /* CheckContainer.swift */; }; @@ -24,6 +20,23 @@ 7D48BCFE2E5182CE00D7F6F7 /* UnsafeRawBufferPointer+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCFD2E5182CE00D7F6F7 /* UnsafeRawBufferPointer+Extras.swift */; }; 7D48BCFF2E5182CE00D7F6F7 /* UnsafeMutableRawBufferPointer+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCFC2E5182CE00D7F6F7 /* UnsafeMutableRawBufferPointer+Extras.swift */; }; 7D48BD002E5182CE00D7F6F7 /* LifetimeOverride.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCFA2E5182CE00D7F6F7 /* LifetimeOverride.swift */; }; + 7D6FEE0F2E877870007C1B86 /* RefTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D6FEE0E2E877870007C1B86 /* RefTests.swift */; }; + 7D6FEE102E877870007C1B86 /* MutTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D6FEE0D2E877870007C1B86 /* MutTests.swift */; }; + 7D6FEE162E8778CF007C1B86 /* Mut.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D6FEE142E8778CF007C1B86 /* Mut.swift */; }; + 7D6FEE172E8778CF007C1B86 /* BorrowIteratorProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D6FEE112E8778CF007C1B86 /* BorrowIteratorProtocol.swift */; }; + 7D6FEE182E8778CF007C1B86 /* Container+Utilities.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D6FEE132E8778CF007C1B86 /* Container+Utilities.swift */; }; + 7D6FEE192E8778CF007C1B86 /* Ref.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D6FEE152E8778CF007C1B86 /* Ref.swift */; }; + 7D6FEE1A2E8778CF007C1B86 /* Container.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D6FEE122E8778CF007C1B86 /* Container.swift */; }; + 7D6FEE252E8778F3007C1B86 /* UniqueArray+Append.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D6FEE202E8778F3007C1B86 /* UniqueArray+Append.swift */; }; + 7D6FEE262E8778F3007C1B86 /* RigidArray+Removals.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D6FEE1E2E8778F3007C1B86 /* RigidArray+Removals.swift */; }; + 7D6FEE272E8778F3007C1B86 /* UniqueArray+Removals.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D6FEE232E8778F3007C1B86 /* UniqueArray+Removals.swift */; }; + 7D6FEE282E8778F3007C1B86 /* RigidArray+Replacements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D6FEE1F2E8778F3007C1B86 /* RigidArray+Replacements.swift */; }; + 7D6FEE292E8778F3007C1B86 /* UniqueArray+Replacements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D6FEE242E8778F3007C1B86 /* UniqueArray+Replacements.swift */; }; + 7D6FEE2A2E8778F3007C1B86 /* RigidArray+Append.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D6FEE1B2E8778F3007C1B86 /* RigidArray+Append.swift */; }; + 7D6FEE2B2E8778F3007C1B86 /* RigidArray+Initializers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D6FEE1C2E8778F3007C1B86 /* RigidArray+Initializers.swift */; }; + 7D6FEE2C2E8778F3007C1B86 /* UniqueArray+Insertions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D6FEE222E8778F3007C1B86 /* UniqueArray+Insertions.swift */; }; + 7D6FEE2D2E8778F3007C1B86 /* RigidArray+Insertions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D6FEE1D2E8778F3007C1B86 /* RigidArray+Insertions.swift */; }; + 7D6FEE2E2E8778F3007C1B86 /* UniqueArray+Initializers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D6FEE212E8778F3007C1B86 /* UniqueArray+Initializers.swift */; }; 7D9B859729E4F74400B291CD /* BitArray+Shifts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9B859129E4F74400B291CD /* BitArray+Shifts.swift */; }; 7D9B859829E4F74400B291CD /* BitArray+Descriptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9B859229E4F74400B291CD /* BitArray+Descriptions.swift */; }; 7D9B859929E4F74400B291CD /* BitArray+LosslessStringConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9B859329E4F74400B291CD /* BitArray+LosslessStringConvertible.swift */; }; @@ -453,18 +466,14 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ - 7D48BCC72E51524200D7F6F7 /* Borrow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Borrow.swift; sourceTree = ""; }; 7D48BCC82E51524200D7F6F7 /* Box.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Box.swift; sourceTree = ""; }; 7D48BCC92E51524200D7F6F7 /* CMakeLists.txt */ = {isa = PBXFileReference; lastKnownFileType = text; path = CMakeLists.txt; sourceTree = ""; }; - 7D48BCCA2E51524200D7F6F7 /* Inout.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Inout.swift; sourceTree = ""; }; 7D48BCCB2E51524200D7F6F7 /* InputSpan.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InputSpan.swift; sourceTree = ""; }; 7D48BCCD2E51524200D7F6F7 /* Shared.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Shared.swift; 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 = ""; }; - 7D48BCE52E5158A100D7F6F7 /* BorrowTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BorrowTests.swift; sourceTree = ""; }; 7D48BCE62E5158A100D7F6F7 /* BoxTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BoxTests.swift; sourceTree = ""; }; - 7D48BCE72E5158A100D7F6F7 /* InoutTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InoutTests.swift; sourceTree = ""; }; 7D48BCEF2E51597200D7F6F7 /* Assertions+Containers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Assertions+Containers.swift"; sourceTree = ""; }; 7D48BCF12E51599200D7F6F7 /* CheckContainer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CheckContainer.swift; sourceTree = ""; }; 7D48BCF32E5159A300D7F6F7 /* StaccatoContainer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StaccatoContainer.swift; sourceTree = ""; }; @@ -482,6 +491,23 @@ 7D5A64D629CCEF1500CB2595 /* gyb */ = {isa = PBXFileReference; lastKnownFileType = text; path = gyb; sourceTree = ""; }; 7D5A64D729CCEF1500CB2595 /* gyb.py */ = {isa = PBXFileReference; lastKnownFileType = text.script.python; path = gyb.py; sourceTree = ""; }; 7D5A64D829CCF0FE00CB2595 /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; + 7D6FEE0D2E877870007C1B86 /* MutTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MutTests.swift; sourceTree = ""; }; + 7D6FEE0E2E877870007C1B86 /* RefTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RefTests.swift; sourceTree = ""; }; + 7D6FEE112E8778CF007C1B86 /* BorrowIteratorProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BorrowIteratorProtocol.swift; sourceTree = ""; }; + 7D6FEE122E8778CF007C1B86 /* Container.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Container.swift; sourceTree = ""; }; + 7D6FEE132E8778CF007C1B86 /* Container+Utilities.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Container+Utilities.swift"; sourceTree = ""; }; + 7D6FEE142E8778CF007C1B86 /* Mut.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Mut.swift; sourceTree = ""; }; + 7D6FEE152E8778CF007C1B86 /* Ref.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Ref.swift; sourceTree = ""; }; + 7D6FEE1B2E8778F3007C1B86 /* RigidArray+Append.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidArray+Append.swift"; sourceTree = ""; }; + 7D6FEE1C2E8778F3007C1B86 /* RigidArray+Initializers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidArray+Initializers.swift"; sourceTree = ""; }; + 7D6FEE1D2E8778F3007C1B86 /* RigidArray+Insertions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidArray+Insertions.swift"; sourceTree = ""; }; + 7D6FEE1E2E8778F3007C1B86 /* RigidArray+Removals.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidArray+Removals.swift"; sourceTree = ""; }; + 7D6FEE1F2E8778F3007C1B86 /* RigidArray+Replacements.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidArray+Replacements.swift"; sourceTree = ""; }; + 7D6FEE202E8778F3007C1B86 /* UniqueArray+Append.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueArray+Append.swift"; sourceTree = ""; }; + 7D6FEE212E8778F3007C1B86 /* UniqueArray+Initializers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueArray+Initializers.swift"; sourceTree = ""; }; + 7D6FEE222E8778F3007C1B86 /* UniqueArray+Insertions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueArray+Insertions.swift"; sourceTree = ""; }; + 7D6FEE232E8778F3007C1B86 /* UniqueArray+Removals.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueArray+Removals.swift"; sourceTree = ""; }; + 7D6FEE242E8778F3007C1B86 /* UniqueArray+Replacements.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueArray+Replacements.swift"; sourceTree = ""; }; 7D9B859129E4F74400B291CD /* BitArray+Shifts.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+Shifts.swift"; sourceTree = ""; }; 7D9B859229E4F74400B291CD /* BitArray+Descriptions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+Descriptions.swift"; sourceTree = ""; }; 7D9B859329E4F74400B291CD /* BitArray+LosslessStringConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+LosslessStringConvertible.swift"; sourceTree = ""; }; @@ -952,11 +978,14 @@ 7D48BCCE2E51524200D7F6F7 /* ContainersPreview */ = { isa = PBXGroup; children = ( - 7D48BCC72E51524200D7F6F7 /* Borrow.swift */, + 7D6FEE112E8778CF007C1B86 /* BorrowIteratorProtocol.swift */, 7D48BCC82E51524200D7F6F7 /* Box.swift */, 7D48BCC92E51524200D7F6F7 /* CMakeLists.txt */, - 7D48BCCA2E51524200D7F6F7 /* Inout.swift */, + 7D6FEE122E8778CF007C1B86 /* Container.swift */, + 7D6FEE132E8778CF007C1B86 /* Container+Utilities.swift */, 7D48BCCB2E51524200D7F6F7 /* InputSpan.swift */, + 7D6FEE142E8778CF007C1B86 /* Mut.swift */, + 7D6FEE152E8778CF007C1B86 /* Ref.swift */, 7D48BCCD2E51524200D7F6F7 /* Shared.swift */, ); path = ContainersPreview; @@ -965,9 +994,9 @@ 7D48BCE82E5158A100D7F6F7 /* ContainersTests */ = { isa = PBXGroup; children = ( - 7D48BCE52E5158A100D7F6F7 /* BorrowTests.swift */, + 7D6FEE0D2E877870007C1B86 /* MutTests.swift */, + 7D6FEE0E2E877870007C1B86 /* RefTests.swift */, 7D48BCE62E5158A100D7F6F7 /* BoxTests.swift */, - 7D48BCE72E5158A100D7F6F7 /* InoutTests.swift */, ); path = ContainersTests; sourceTree = ""; @@ -1877,9 +1906,19 @@ children = ( A93AC20F2E7C841700A824DF /* CMakeLists.txt */, A93AC2102E7C841700A824DF /* RigidArray.swift */, + 7D6FEE1B2E8778F3007C1B86 /* RigidArray+Append.swift */, A93AC2112E7C841700A824DF /* RigidArray+Experimental.swift */, + 7D6FEE1C2E8778F3007C1B86 /* RigidArray+Initializers.swift */, + 7D6FEE1D2E8778F3007C1B86 /* RigidArray+Insertions.swift */, + 7D6FEE1E2E8778F3007C1B86 /* RigidArray+Removals.swift */, + 7D6FEE1F2E8778F3007C1B86 /* RigidArray+Replacements.swift */, A93AC2122E7C841700A824DF /* UniqueArray.swift */, + 7D6FEE202E8778F3007C1B86 /* UniqueArray+Append.swift */, A93AC2132E7C841700A824DF /* UniqueArray+Experimental.swift */, + 7D6FEE212E8778F3007C1B86 /* UniqueArray+Initializers.swift */, + 7D6FEE222E8778F3007C1B86 /* UniqueArray+Insertions.swift */, + 7D6FEE232E8778F3007C1B86 /* UniqueArray+Removals.swift */, + 7D6FEE242E8778F3007C1B86 /* UniqueArray+Replacements.swift */, ); path = BasicContainers; sourceTree = ""; @@ -2035,6 +2074,11 @@ 7DE920C029CA70F4004483EB /* BitSet+SetAlgebra conformance.swift in Sources */, 7DE9203C29CA70F3004483EB /* OrderedSet+Partial SetAlgebra formSymmetricDifference.swift in Sources */, 7DE9209029CA70F4004483EB /* Rope.swift in Sources */, + 7D6FEE162E8778CF007C1B86 /* Mut.swift in Sources */, + 7D6FEE172E8778CF007C1B86 /* BorrowIteratorProtocol.swift in Sources */, + 7D6FEE182E8778CF007C1B86 /* Container+Utilities.swift in Sources */, + 7D6FEE192E8778CF007C1B86 /* Ref.swift in Sources */, + 7D6FEE1A2E8778CF007C1B86 /* Container.swift in Sources */, 7DE9213B29CA70F4004483EB /* TreeSet+Hashable.swift in Sources */, 7DE9200D29CA70F3004483EB /* OrderedDictionary+Equatable.swift in Sources */, 7DE9207C29CA70F4004483EB /* BigSubstring.swift in Sources */, @@ -2100,8 +2144,6 @@ 7D48BCD12E51524200D7F6F7 /* InputSpan.swift in Sources */, 7D48BCD32E51524200D7F6F7 /* Box.swift in Sources */, 7D48BCD62E51524200D7F6F7 /* Shared.swift in Sources */, - 7D48BCD82E51524200D7F6F7 /* Borrow.swift in Sources */, - 7D48BCD92E51524200D7F6F7 /* Inout.swift in Sources */, 7DE9208629CA70F4004483EB /* BigString+LosslessStringConvertible.swift in Sources */, 7DE9204329CA70F3004483EB /* _HashTable+Bucket.swift in Sources */, 7DE9216A29CA70F4004483EB /* TreeDictionary.swift in Sources */, @@ -2290,6 +2332,16 @@ 7DE9207929CA70F4004483EB /* BigString+UnicodeScalarView.swift in Sources */, 7DE9205329CA70F3004483EB /* _DequeBufferHeader.swift in Sources */, 7DE9202429CA70F3004483EB /* OrderedSet+Invariants.swift in Sources */, + 7D6FEE252E8778F3007C1B86 /* UniqueArray+Append.swift in Sources */, + 7D6FEE262E8778F3007C1B86 /* RigidArray+Removals.swift in Sources */, + 7D6FEE272E8778F3007C1B86 /* UniqueArray+Removals.swift in Sources */, + 7D6FEE282E8778F3007C1B86 /* RigidArray+Replacements.swift in Sources */, + 7D6FEE292E8778F3007C1B86 /* UniqueArray+Replacements.swift in Sources */, + 7D6FEE2A2E8778F3007C1B86 /* RigidArray+Append.swift in Sources */, + 7D6FEE2B2E8778F3007C1B86 /* RigidArray+Initializers.swift in Sources */, + 7D6FEE2C2E8778F3007C1B86 /* UniqueArray+Insertions.swift in Sources */, + 7D6FEE2D2E8778F3007C1B86 /* RigidArray+Insertions.swift in Sources */, + 7D6FEE2E2E8778F3007C1B86 /* UniqueArray+Initializers.swift in Sources */, 7DE920A729CA70F4004483EB /* _CharacterRecognizer.swift in Sources */, 7DE920A429CA70F4004483EB /* Rope+Sequence.swift in Sources */, 7DE9201829CA70F3004483EB /* OrderedDictionary+Invariants.swift in Sources */, @@ -2404,6 +2456,8 @@ 7DE9221E29CA8576004483EB /* MutableCollectionTests.swift in Sources */, 7DE9221529CA8576004483EB /* RandomAccessCollection+Extras.swift in Sources */, 7DEBDB7929CCE44A00ADC226 /* LifetimeTracked.swift in Sources */, + 7D6FEE0F2E877870007C1B86 /* RefTests.swift in Sources */, + 7D6FEE102E877870007C1B86 /* MutTests.swift in Sources */, 7DE921FC29CA8576004483EB /* IndexRangeCollectionTests.swift in Sources */, 7DE9221229CA8576004483EB /* OrderedDictionary+Elements Tests.swift in Sources */, 7DEBDB7629CCE44A00ADC226 /* MinimalIndex.swift in Sources */, @@ -2434,8 +2488,6 @@ 7DEBDB8F29CCE44A00ADC226 /* CheckEquatable.swift in Sources */, 7DEBDB7729CCE44A00ADC226 /* HashableBox.swift in Sources */, 7DE9220E29CA8576004483EB /* SampleStrings.swift in Sources */, - 7D48BCEC2E5158A100D7F6F7 /* InoutTests.swift in Sources */, - 7D48BCED2E5158A100D7F6F7 /* BorrowTests.swift in Sources */, 7D48BCEE2E5158A100D7F6F7 /* BoxTests.swift in Sources */, 7DEBDB9129CCE44A00ADC226 /* CollectionTestCase.swift in Sources */, 7DEBDB1829CBF69F00ADC226 /* _UnsafeBitSet+_Word.swift in Sources */, diff --git a/Xcode/Shared.xcconfig b/Xcode/Shared.xcconfig index 24bc61ad..21cf3511 100644 --- a/Xcode/Shared.xcconfig +++ b/Xcode/Shared.xcconfig @@ -18,6 +18,7 @@ OTHER_SWIFT_FLAGS = $(inherited) \ -enable-experimental-feature BuiltinModule \ -enable-experimental-feature Lifetimes \ -enable-experimental-feature InoutLifetimeDependence \ + -enable-experimental-feature SuppressedAssociatedTypes \ -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 76c643222ff0d4f2e9a336792cfb54d685058044 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 26 Sep 2025 19:58:56 -0700 Subject: [PATCH 12/16] Update CMake config --- Sources/ContainersPreview/CMakeLists.txt | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Sources/ContainersPreview/CMakeLists.txt b/Sources/ContainersPreview/CMakeLists.txt index 8af82367..d24327e6 100644 --- a/Sources/ContainersPreview/CMakeLists.txt +++ b/Sources/ContainersPreview/CMakeLists.txt @@ -23,9 +23,12 @@ else() endif() target_sources(${module_name} PRIVATE - "Borrow.swift" + "BorrowIteratorProtocol.swift" "Box.swift" - "Inout.swift" + "Container.swift" + "Container+Utilities.swift" "InputSpan.swift" + "Mut.swift" + "Ref.swift" "Shared.swift" ) From 5cc7f613d676e9b49901a4012bfa95fddff4d895 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 26 Sep 2025 20:05:12 -0700 Subject: [PATCH 13/16] Update README --- README.md | 47 +++++++++++++++-------------------------------- 1 file changed, 15 insertions(+), 32 deletions(-) diff --git a/README.md b/README.md index 323df766..9dc71ddf 100644 --- a/README.md +++ b/README.md @@ -10,9 +10,9 @@ Read more about the package, and the intent behind it, in the [announcement on s The package currently provides the following implementations: -- [`RigidArray`][RigidArray], a fixed capacity and no implicit resizing dynamic non-copyable array capable of storing non-copyable elements. +- [`UniqueArray`][UniqueArray], a dynamically self-resizing, heap allocated, noncopyable array of potentially noncopyable elements. -- [`UniqueArray`][UniqueArray], an implicitly resizable dynamic non-copyable array capable of storing non-copyable elements. +- [`RigidArray`][RigidArray], a fixed capacity, heap allocated, noncopyable array of potentially noncopyable elements. - [`BitSet`][BitSet] and [`BitArray`][BitArray], dynamic bit collections. @@ -24,7 +24,7 @@ The package currently provides the following implementations: - [`OrderedDictionary`][OrderedDictionary], an ordered variant of the standard `Dictionary`, providing similar benefits. -- [`TreeSet`][TreeSet] and [`TreeDictionary`][TreeDictionary], persistent hashed collections implementing Compressed Hash-Array Mapped Prefix Trees (CHAMP). These work similar to the standard `Set` and `Dictionary`, but they excel at use cases that mutate shared copies, offering dramatic memory savings and radical time improvements. +- [`TreeSet`][TreeSet] and [`TreeDictionary`][TreeDictionary], persistent hashed collections implementing Compressed Hash-Array Mapped Prefix Trees (CHAMP). These work similar to the standard `Set` and `Dictionary`, but they excel at use cases that mutate shared copies, offering dramatic memory savings and radical time improvements. [RigidArray]: https://swiftpackageindex.com/apple/swift-collections/documentation/basiccontainers/rigidarray [UniqueArray]: https://swiftpackageindex.com/apple/swift-collections/documentation/basiccontainers/uniquearray @@ -54,9 +54,9 @@ The Swift Collections package is source stable. The version numbers follow [Sema [semver]: https://semver.org -### Public API +### Public API -The public API of version 1.2 of the `swift-collections` package consists of non-underscored declarations that are marked `public` in the `Collections`, `BitCollections`, `DequeModule`, `HeapModule`, `OrderedCollections` and `HashTreeCollections` modules. +The public API of version 1.3 of the `swift-collections` package consists of non-underscored declarations that are marked `public` in the `Collections`, `BitCollections`, `DequeModule`, `HeapModule`, `OrderedCollections` and `HashTreeCollections` modules. Interfaces that aren't part of the public API may continue to change in any release, including patch releases. @@ -86,6 +86,7 @@ The following table maps package releases to their minimum required Swift toolch | swift-collections 1.0.x | >= Swift 5.3.2 | >= Xcode 12.4 | | swift-collections 1.1.x | >= Swift 5.7.2 | >= Xcode 14.2 | | swift-collections 1.2.x | >= Swift 5.10.0 | >= Xcode 15.3 | +| swift-collections 1.3.x | >= Swift 6.0.3 | >= Xcode 16.2 | (Note: the package has no minimum deployment target, so while it does require clients to use a recent Swift toolchain to build it, the code itself is able to run on any OS release that supports running Swift code.) @@ -101,8 +102,8 @@ let package = Package( name: "MyPackage", dependencies: [ .package( - url: "https://github.com/apple/swift-collections.git", - .upToNextMinor(from: "1.2.0") // or `.upToNextMajor + url: "https://github.com/apple/swift-collections.git", + .upToNextMinor(from: "1.3.0") // or `.upToNextMajor ) ], targets: [ @@ -131,16 +132,16 @@ We maintain separate branches for each minor version of the package: | Package version | Branch | Status | | ----------------------- | ----------- | -------- | | swift-collections 1.0.x | release/1.0 | Obsolete | -| swift-collections 1.1.x | release/1.1 | Critical bugfixes only | +| swift-collections 1.1.x | release/1.1 | Critical bugfixes only | | swift-collections 1.2.x | release/1.2 | Critical bugfixes only | -| swift-collections 1.3.x | main | Feature work towards next minor release | -| n.a. | future | Experimental prototyping | +| swift-collections 1.3.x | release/1.3 | Bugfixes only | +| n.a. | main | Feature work towards next minor release | Changes must land on the branch corresponding to the earliest release that they will need to ship on. They are periodically propagated to subsequent branches, in the following direction: -`release/1.0` → `release/1.1` → `release/1.2` → `main` +`release/1.0` → `release/1.1` → `release/1.2` → `release/1.3` → `main` -For example, anything landing on `release/1.1` will eventually appear on `release/1.2` and then `main` too; there is no need to file standalone PRs for each release line. Change propagation is not instantaneous, as it currently requires manual work -- it is performed by project maintainers. +For example, anything landing on `release/1.2` will eventually appear on `release/1.3` and then `main` too; there is no need to file standalone PRs for each release line. Change propagation is not instantaneous, as it currently requires manual work -- it is performed by project maintainers. ### Working on the package @@ -163,32 +164,14 @@ By submitting a pull request, you represent that you have the right to license y 1. Raise a [Feature Request][enhancement]. Discuss why it would be important to implement it. 2. Submit a PR with your implementation, participate in the review discussion. -3. When there is a consensus that the feature is desirable, and the implementation works well, it is fully tested and documented, then it will be merged. +3. When there is a consensus that the feature is desirable, and the implementation works well, it is fully tested and documented, then it will be merged. 4. Rejoice! [enhancement]: https://github.com/apple/swift-collections/issues/new?assignees=&labels=enhancement&template=FEATURE_REQUEST.md #### Proposing the addition of a new data structure -**Note:** As of 2024, we are fully preoccupied with refactoring our existing data structures to support noncopyable and/or nonescapable element types; this includes designing new container protocols around them. I don't expect we'll have capacity to work on any major new data structure implementations until this effort is complete. - - +**Note:** As of 2025, we are fully preoccupied with refactoring our existing data structures to support noncopyable and/or nonescapable element types; this includes designing new container protocols around them. I don't expect we'll have capacity to work on any major new data structure implementations until this effort is complete. ### Code of Conduct From 485e69bfb14e67747d711a696272f1b8b2286b6a Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 26 Sep 2025 21:46:54 -0700 Subject: [PATCH 14/16] =?UTF-8?q?Don=E2=80=99t=20allow=20backdeployment=20?= =?UTF-8?q?of=20any=20Span=20types=20below=20the=20most=20recent=20Darwin?= =?UTF-8?q?=20OS=20releases?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit References to Span types trigger an issue where SwiftPM isn’t able to run command line executable targets or tests on older OSes. Set the availability of everything that needs span types to the most recent Apple OS releases. Hopefully we’ll be able to revert this once we figure out a better workaround. --- CMakeLists.txt | 2 ++ Package.swift | 2 ++ .../BasicContainers/RigidArray+Append.swift | 10 +++--- .../RigidArray+Experimental.swift | 8 ++--- .../RigidArray+Initializers.swift | 6 ++-- .../RigidArray+Insertions.swift | 10 +++--- .../BasicContainers/RigidArray+Removals.swift | 6 ++-- .../RigidArray+Replacements.swift | 8 ++--- Sources/BasicContainers/RigidArray.swift | 34 +++++++++---------- .../BasicContainers/UniqueArray+Append.swift | 10 +++--- .../UniqueArray+Experimental.swift | 4 +-- .../UniqueArray+Initializers.swift | 8 ++--- .../UniqueArray+Insertions.swift | 10 +++--- .../UniqueArray+Removals.swift | 6 ++-- .../UniqueArray+Replacements.swift | 8 ++--- Sources/BasicContainers/UniqueArray.swift | 26 +++++++------- .../BorrowIteratorProtocol.swift | 8 ++--- Sources/ContainersPreview/Box.swift | 4 +-- .../Container+Utilities.swift | 6 ++-- Sources/ContainersPreview/Container.swift | 6 ++-- Sources/ContainersPreview/InputSpan.swift | 30 ++++++++-------- ...nsafeMutableBufferPointer+Extras.swift.gyb | 4 +-- .../UnsafeMutableBufferPointer+Extras.swift | 8 ++--- .../TrailingArray.swift | 10 +++--- Tests/BasicContainersTests/ArrayLayout.swift | 3 ++ .../RigidArrayTests.swift | 6 ++-- .../UniqueArrayTests.swift | 6 ++-- Tests/ContainersTests/RefTests.swift | 2 +- .../TrailingElementsTests.swift | 6 ++++ .../Assertions+Containers.swift | 12 +++---- .../ConformanceCheckers/CheckContainer.swift | 4 +-- .../MinimalTypes/StaccatoContainer.swift | 6 ++-- .../Utilities/TestPrintable.swift | 8 ++--- Xcode/Shared.xcconfig | 3 +- 34 files changed, 152 insertions(+), 138 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 215f1441..07d1e488 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -69,6 +69,8 @@ set(availability_defs "SwiftStdlib 6.0: macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0" "SwiftStdlib 6.1: macOS 15.4, iOS 18.4, watchOS 11.4, tvOS 18.4, visionOS 2.4" "SwiftStdlib 6.2: macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, visionOS 26.0" + // FIXME: This should be the same as SwiftStdlib 5.0, except Span deployment doesn't work in SwiftPM (rdar://161459068) + "SpanAvailability 1.0: macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, visionOS 26.0" ) foreach(def ${availability_defs}) add_compile_options("$<$:SHELL:-enable-experimental-feature \"AvailabilityMacro=${def}\">") diff --git a/Package.swift b/Package.swift index d95fcbf9..a832bda2 100644 --- a/Package.swift +++ b/Package.swift @@ -81,6 +81,8 @@ let availabilityMacros: KeyValuePairs = [ "SwiftStdlib 6.0": "macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0", "SwiftStdlib 6.1": "macOS 15.4, iOS 18.4, watchOS 11.4, tvOS 18.4, visionOS 2.4", "SwiftStdlib 6.2": "macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, visionOS 26.0", + // FIXME: This should be the same as SwiftStdlib 5.0, except Span deployment doesn't work in SwiftPM (rdar://161459068) + "SpanAvailability 1.0": "macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, visionOS 26.0", // 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+Append.swift b/Sources/BasicContainers/RigidArray+Append.swift index ded035f4..c2c006ad 100644 --- a/Sources/BasicContainers/RigidArray+Append.swift +++ b/Sources/BasicContainers/RigidArray+Append.swift @@ -16,7 +16,7 @@ import ContainersPreview #if compiler(>=6.2) -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray where Element: ~Copyable { /// Adds an element to the end of the array. /// @@ -52,7 +52,7 @@ extension RigidArray where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray where Element: ~Copyable { @_alwaysEmitIntoClient public mutating func append( @@ -71,7 +71,7 @@ extension RigidArray where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray where Element: ~Copyable { /// Moves the elements of a buffer to the end of this array, leaving the /// buffer uninitialized. @@ -144,7 +144,7 @@ extension RigidArray where Element: ~Copyable { } #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray where Element: ~Copyable { /// Appends the elements of a given container to the end of this array by /// consuming the source container. @@ -168,7 +168,7 @@ extension RigidArray where Element: ~Copyable { } #endif -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray { /// Copies the elements of a buffer to the end of this array. /// diff --git a/Sources/BasicContainers/RigidArray+Experimental.swift b/Sources/BasicContainers/RigidArray+Experimental.swift index 214e0b44..aaa189e8 100644 --- a/Sources/BasicContainers/RigidArray+Experimental.swift +++ b/Sources/BasicContainers/RigidArray+Experimental.swift @@ -17,7 +17,7 @@ import ContainersPreview #if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW #if false // FIXME -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray where Element: ~Copyable { @inlinable @_lifetime(borrow self) @@ -32,7 +32,7 @@ extension RigidArray where Element: ~Copyable { #endif #if false // FIXME -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray where Element: ~Copyable { @inlinable @_lifetime(&self) @@ -47,7 +47,7 @@ extension RigidArray where Element: ~Copyable { #endif #if false // FIXME -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray where Element: ~Copyable { @inlinable public mutating func reallocate( @@ -75,7 +75,7 @@ extension RigidArray where Element: ~Copyable { #endif #if false // FIXME -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray where Element: ~Copyable { /// Removes all the elements that satisfy the given predicate. /// diff --git a/Sources/BasicContainers/RigidArray+Initializers.swift b/Sources/BasicContainers/RigidArray+Initializers.swift index dd395144..98d17f47 100644 --- a/Sources/BasicContainers/RigidArray+Initializers.swift +++ b/Sources/BasicContainers/RigidArray+Initializers.swift @@ -16,7 +16,7 @@ import ContainersPreview #if compiler(>=6.2) -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray where Element: ~Copyable { @inlinable public init( @@ -28,7 +28,7 @@ extension RigidArray where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray /*where Element: Copyable*/ { /// Creates a new array containing the specified number of a single, /// repeated value. @@ -44,7 +44,7 @@ extension RigidArray /*where Element: Copyable*/ { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray /*where Element: Copyable*/ { @_alwaysEmitIntoClient @inline(__always) diff --git a/Sources/BasicContainers/RigidArray+Insertions.swift b/Sources/BasicContainers/RigidArray+Insertions.swift index c1f076c4..e127b2f5 100644 --- a/Sources/BasicContainers/RigidArray+Insertions.swift +++ b/Sources/BasicContainers/RigidArray+Insertions.swift @@ -16,7 +16,7 @@ import ContainersPreview #if compiler(>=6.2) -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray where Element: ~Copyable { /// Inserts a new element into the array at the specified position. /// @@ -50,7 +50,7 @@ extension RigidArray where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray where Element: ~Copyable { @inlinable public mutating func insert( @@ -73,7 +73,7 @@ extension RigidArray where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray where Element: ~Copyable { /// Moves the elements of a fully initialized buffer into this array, /// starting at the specified position, and leaving the buffer @@ -157,7 +157,7 @@ extension RigidArray where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray where Element: ~Copyable { /// Inserts the elements of a given array into the given position in this /// array by consuming the source container. @@ -180,7 +180,7 @@ extension RigidArray where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray { /// Copies the elements of a fully initialized buffer pointer into this /// array at the specified position. diff --git a/Sources/BasicContainers/RigidArray+Removals.swift b/Sources/BasicContainers/RigidArray+Removals.swift index 888009d0..9eee4218 100644 --- a/Sources/BasicContainers/RigidArray+Removals.swift +++ b/Sources/BasicContainers/RigidArray+Removals.swift @@ -16,7 +16,7 @@ import ContainersPreview #if compiler(>=6.2) -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray where Element: ~Copyable { /// Removes all elements from the array, preserving its allocated capacity. /// @@ -120,7 +120,7 @@ extension RigidArray where Element: ~Copyable { } #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray where Element: ~Copyable { @_lifetime(&self) @_alwaysEmitIntoClient @@ -168,7 +168,7 @@ extension RigidArray where Element: ~Copyable { } #endif -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray where Element: ~Copyable { /// Removes and returns the last element of the array, if there is one. /// diff --git a/Sources/BasicContainers/RigidArray+Replacements.swift b/Sources/BasicContainers/RigidArray+Replacements.swift index f1541949..76a62d66 100644 --- a/Sources/BasicContainers/RigidArray+Replacements.swift +++ b/Sources/BasicContainers/RigidArray+Replacements.swift @@ -16,7 +16,7 @@ import ContainersPreview #if compiler(>=6.2) -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray where Element: ~Copyable { @inlinable public mutating func replaceSubrange( @@ -38,7 +38,7 @@ extension RigidArray where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray where Element: ~Copyable { /// Replaces the specified range of elements by moving the elements of a /// fully initialized buffer into their place. On return, the buffer is left @@ -147,7 +147,7 @@ extension RigidArray where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray where Element: ~Copyable { /// Replaces the specified range of elements by moving the elements of a /// given array into their place, consuming it in the process. @@ -184,7 +184,7 @@ extension RigidArray where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray { /// Replaces the specified subrange of elements by copying the elements of /// the given buffer pointer, which must be fully initialized. diff --git a/Sources/BasicContainers/RigidArray.swift b/Sources/BasicContainers/RigidArray.swift index c3c1b749..42d56ced 100644 --- a/Sources/BasicContainers/RigidArray.swift +++ b/Sources/BasicContainers/RigidArray.swift @@ -76,7 +76,7 @@ public struct RigidArray: ~Copyable { /// For use cases outside of these narrow domains, we generally recommmend /// the use of ``UniqueArray`` rather than `RigidArray`. (For copyable elements, /// the standard `Array` is an even more convenient choice.) -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) @safe @frozen public struct RigidArray: ~Copyable { @@ -111,13 +111,13 @@ public struct RigidArray: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray: @unchecked Sendable where Element: Sendable & ~Copyable {} //MARK: - Basics -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray where Element: ~Copyable { @inlinable @_transparent @@ -134,7 +134,7 @@ extension RigidArray where Element: ~Copyable { public var isFull: Bool { freeCapacity == 0 } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray where Element: ~Copyable { @inlinable internal var _items: UnsafeMutableBufferPointer { @@ -149,7 +149,7 @@ extension RigidArray where Element: ~Copyable { //MARK: - Span creation -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray where Element: ~Copyable { public var span: Span { @_lifetime(borrow self) @@ -185,7 +185,7 @@ extension RigidArray where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray where Element: ~Copyable { /// Arbitrarily edit the storage underlying this array by invoking a /// user-supplied closure with a mutable `OutputSpan` view over it. @@ -227,7 +227,7 @@ extension RigidArray where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray where Element: ~Copyable { @inlinable internal func _contiguousSubrange(following index: inout Int) -> Range { @@ -246,7 +246,7 @@ extension RigidArray where Element: ~Copyable { //MARK: - Container primitives -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray where Element: ~Copyable { @inlinable @inline(__always) @@ -258,7 +258,7 @@ extension RigidArray where Element: ~Copyable { } #if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray: Container where Element: ~Copyable { public typealias BorrowIterator = Span @@ -270,7 +270,7 @@ extension RigidArray: Container where Element: ~Copyable { } #endif -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray where Element: ~Copyable { public typealias Index = Int @@ -287,7 +287,7 @@ extension RigidArray where Element: ~Copyable { public var indices: Range { unsafe Range(uncheckedBounds: (0, count)) } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray where Element: ~Copyable { @inlinable @inline(__always) internal func _ptr(to index: Int) -> UnsafePointer { @@ -315,7 +315,7 @@ extension RigidArray where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray where Element: ~Copyable { @inlinable public mutating func swapAt(_ i: Int, _ j: Int) { @@ -326,7 +326,7 @@ extension RigidArray where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray where Element: ~Copyable { @inlinable @_lifetime(borrow self) @@ -341,7 +341,7 @@ extension RigidArray where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray where Element: ~Copyable { @_lifetime(&self) public mutating func mutableSpan( @@ -360,7 +360,7 @@ extension RigidArray where Element: ~Copyable { //MARK: - Resizing -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray where Element: ~Copyable { @inlinable public mutating func reallocate(capacity newCapacity: Int) { @@ -383,7 +383,7 @@ extension RigidArray where Element: ~Copyable { //MARK: - Copying helpers -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray { @inlinable public func copy() -> Self { @@ -404,7 +404,7 @@ extension RigidArray { //MARK: - Opening and closing gaps -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension RigidArray where Element: ~Copyable { @inlinable internal mutating func _closeGap( diff --git a/Sources/BasicContainers/UniqueArray+Append.swift b/Sources/BasicContainers/UniqueArray+Append.swift index 36d96574..90f86057 100644 --- a/Sources/BasicContainers/UniqueArray+Append.swift +++ b/Sources/BasicContainers/UniqueArray+Append.swift @@ -16,7 +16,7 @@ import ContainersPreview #if compiler(>=6.2) -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension UniqueArray where Element: ~Copyable { /// Adds an element to the end of the array. /// @@ -33,7 +33,7 @@ extension UniqueArray where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension UniqueArray where Element: ~Copyable { @_alwaysEmitIntoClient public mutating func append( @@ -45,7 +45,7 @@ extension UniqueArray where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension UniqueArray where Element: ~Copyable { /// Moves the elements of a buffer to the end of this array, leaving the /// buffer uninitialized. @@ -109,7 +109,7 @@ extension UniqueArray where Element: ~Copyable { } #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension UniqueArray where Element: ~Copyable { /// Appends the elements of a given container to the end of this array by /// consuming the source container. @@ -132,7 +132,7 @@ extension UniqueArray where Element: ~Copyable { } #endif -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension UniqueArray { /// Copies the elements of a buffer to the end of this array. /// diff --git a/Sources/BasicContainers/UniqueArray+Experimental.swift b/Sources/BasicContainers/UniqueArray+Experimental.swift index 1b807602..3c073873 100644 --- a/Sources/BasicContainers/UniqueArray+Experimental.swift +++ b/Sources/BasicContainers/UniqueArray+Experimental.swift @@ -61,7 +61,7 @@ extension UniqueArray where Element: ~Copyable { #endif #if false // TODO -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension UniqueArray where Element: ~Copyable { @_alwaysEmitIntoClient @_transparent @@ -80,7 +80,7 @@ extension UniqueArray where Element: ~Copyable { #endif #if false // TODO -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension UniqueArray where Element: ~Copyable { /// Removes all the elements that satisfy the given predicate. /// diff --git a/Sources/BasicContainers/UniqueArray+Initializers.swift b/Sources/BasicContainers/UniqueArray+Initializers.swift index 5a2dfe3f..9d92660b 100644 --- a/Sources/BasicContainers/UniqueArray+Initializers.swift +++ b/Sources/BasicContainers/UniqueArray+Initializers.swift @@ -16,7 +16,7 @@ import ContainersPreview #if compiler(>=6.2) -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension UniqueArray where Element: ~Copyable { @inlinable public init( @@ -28,7 +28,7 @@ extension UniqueArray where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension UniqueArray /*where Element: Copyable*/ { /// Creates a new array containing the specified number of a single, /// repeated value. @@ -42,7 +42,7 @@ extension UniqueArray /*where Element: Copyable*/ { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension UniqueArray where Element: ~Copyable { @inlinable public init(consuming storage: consuming RigidArray) { @@ -50,7 +50,7 @@ extension UniqueArray where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension UniqueArray /*where Element: Copyable*/ { #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW @_alwaysEmitIntoClient diff --git a/Sources/BasicContainers/UniqueArray+Insertions.swift b/Sources/BasicContainers/UniqueArray+Insertions.swift index 62d4f20e..0530a26a 100644 --- a/Sources/BasicContainers/UniqueArray+Insertions.swift +++ b/Sources/BasicContainers/UniqueArray+Insertions.swift @@ -16,7 +16,7 @@ import ContainersPreview #if compiler(>=6.2) -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension UniqueArray where Element: ~Copyable { /// Inserts a new element into the array at the specified position. /// @@ -44,7 +44,7 @@ extension UniqueArray where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension UniqueArray where Element: ~Copyable { @inlinable public mutating func insert( @@ -58,7 +58,7 @@ extension UniqueArray where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension UniqueArray where Element: ~Copyable { /// Moves the elements of a fully initialized buffer into this array, /// starting at the specified position, and leaving the buffer @@ -125,7 +125,7 @@ extension UniqueArray where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension UniqueArray where Element: ~Copyable { /// Inserts the elements of a given array into the given position in this /// array by consuming the source container. @@ -149,7 +149,7 @@ extension UniqueArray where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension UniqueArray { /// Copyies the elements of a fully initialized buffer pointer into this /// array at the specified position. diff --git a/Sources/BasicContainers/UniqueArray+Removals.swift b/Sources/BasicContainers/UniqueArray+Removals.swift index e84e9a8f..830afd44 100644 --- a/Sources/BasicContainers/UniqueArray+Removals.swift +++ b/Sources/BasicContainers/UniqueArray+Removals.swift @@ -16,7 +16,7 @@ import ContainersPreview #if compiler(>=6.2) -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension UniqueArray where Element: ~Copyable { /// Removes all elements from the array, optionally preserving its /// allocated capacity. @@ -106,7 +106,7 @@ extension UniqueArray where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension UniqueArray where Element: ~Copyable { /// Removes and returns the last element of the array, if there is one. /// @@ -122,7 +122,7 @@ extension UniqueArray where Element: ~Copyable { } #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension UniqueArray where Element: ~Copyable { @_lifetime(&self) @_alwaysEmitIntoClient diff --git a/Sources/BasicContainers/UniqueArray+Replacements.swift b/Sources/BasicContainers/UniqueArray+Replacements.swift index e4f72815..34d1f74a 100644 --- a/Sources/BasicContainers/UniqueArray+Replacements.swift +++ b/Sources/BasicContainers/UniqueArray+Replacements.swift @@ -16,7 +16,7 @@ import ContainersPreview #if compiler(>=6.2) -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension UniqueArray where Element: ~Copyable { @inlinable public mutating func replaceSubrange( @@ -34,7 +34,7 @@ extension UniqueArray where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension UniqueArray where Element: ~Copyable { /// Replaces the specified range of elements by moving the elements of a /// fully initialized buffer into their place. On return, the buffer is left @@ -135,7 +135,7 @@ extension UniqueArray where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension UniqueArray where Element: ~Copyable { /// Replaces the specified range of elements by moving the elements of a /// given array into their place, consuming it in the process. @@ -172,7 +172,7 @@ extension UniqueArray where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension UniqueArray { /// Replaces the specified subrange of elements by copying the elements of /// the given buffer pointer, which must be fully initialized. diff --git a/Sources/BasicContainers/UniqueArray.swift b/Sources/BasicContainers/UniqueArray.swift index 7711122c..34a2c507 100644 --- a/Sources/BasicContainers/UniqueArray.swift +++ b/Sources/BasicContainers/UniqueArray.swift @@ -57,7 +57,7 @@ public struct UniqueArray: ~Copyable { /// resizing array types as a matter of policy. The type `RigidArray` provides /// a fixed-capacity array variant that caters specifically for these use cases, /// trading ease-of-use for more consistent/predictable execution. -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) @frozen public struct UniqueArray: ~Copyable { @usableFromInline @@ -74,12 +74,12 @@ public struct UniqueArray: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension UniqueArray: Sendable where Element: Sendable & ~Copyable {} //MARK: - Basics -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension UniqueArray where Element: ~Copyable { @inlinable @inline(__always) @@ -94,7 +94,7 @@ extension UniqueArray where Element: ~Copyable { //MARK: - Span creation -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension UniqueArray where Element: ~Copyable { public var span: Span { @_lifetime(borrow self) @@ -104,7 +104,7 @@ extension UniqueArray where Element: ~Copyable { } } - @available(SwiftStdlib 5.0, *) + @available(SpanAvailability 1.0, *) public var mutableSpan: MutableSpan { @_lifetime(&self) @inlinable @@ -114,7 +114,7 @@ extension UniqueArray where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension UniqueArray where Element: ~Copyable { /// Arbitrarily edit the storage underlying this array by invoking a /// user-supplied closure with a mutable `OutputSpan` view over it. @@ -143,7 +143,7 @@ extension UniqueArray where Element: ~Copyable { //MARK: - Container primitives -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension UniqueArray where Element: ~Copyable { @inlinable @inline(__always) @@ -155,7 +155,7 @@ extension UniqueArray where Element: ~Copyable { } #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension UniqueArray: Container where Element: ~Copyable { public typealias BorrowIterator = RigidArray.BorrowIterator @@ -167,7 +167,7 @@ extension UniqueArray: Container where Element: ~Copyable { } #endif -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension UniqueArray where Element: ~Copyable { public typealias Index = Int @@ -194,7 +194,7 @@ extension UniqueArray where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension UniqueArray where Element: ~Copyable { @inlinable public mutating func swapAt(_ i: Int, _ j: Int) { @@ -202,7 +202,7 @@ extension UniqueArray where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension UniqueArray where Element: ~Copyable { @inlinable @_lifetime(borrow self) @@ -217,7 +217,7 @@ extension UniqueArray where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension UniqueArray where Element: ~Copyable { @_lifetime(&self) public mutating func mutableSpan( @@ -245,7 +245,7 @@ internal func _growDynamicArrayCapacity(_ capacity: Int) -> Int { return Int(bitPattern: c) } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension UniqueArray where Element: ~Copyable { @inlinable @inline(never) public mutating func reallocate(capacity: Int) { diff --git a/Sources/ContainersPreview/BorrowIteratorProtocol.swift b/Sources/ContainersPreview/BorrowIteratorProtocol.swift index f3452512..bcc23333 100644 --- a/Sources/ContainersPreview/BorrowIteratorProtocol.swift +++ b/Sources/ContainersPreview/BorrowIteratorProtocol.swift @@ -10,7 +10,7 @@ //===----------------------------------------------------------------------===// #if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) public protocol BorrowIteratorProtocol: ~Copyable, ~Escapable { associatedtype Element: ~Copyable /*& ~Escapable*/ @@ -65,7 +65,7 @@ public protocol BorrowIteratorProtocol: ~Copyable, ~Escapable { mutating func skip(by offset: Int) -> Int } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension BorrowIteratorProtocol where Self: ~Copyable & ~Escapable { @_lifetime(self: copy self) @inlinable @@ -80,7 +80,7 @@ extension BorrowIteratorProtocol where Self: ~Copyable & ~Escapable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension BorrowIteratorProtocol where Self: ~Copyable & ~Escapable { @_lifetime(copy self) @_lifetime(self: copy self) @@ -90,7 +90,7 @@ extension BorrowIteratorProtocol where Self: ~Copyable & ~Escapable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension Span: BorrowIteratorProtocol where Element: ~Copyable { @_lifetime(copy self) @_lifetime(self: copy self) diff --git a/Sources/ContainersPreview/Box.swift b/Sources/ContainersPreview/Box.swift index 3ff38888..afaf83c1 100644 --- a/Sources/ContainersPreview/Box.swift +++ b/Sources/ContainersPreview/Box.swift @@ -114,7 +114,7 @@ extension Box where T: Copyable { } extension Box where T: ~Copyable { - @available(SwiftStdlib 5.0, *) + @available(SpanAvailability 1.0, *) public var span: Span { @_alwaysEmitIntoClient @_lifetime(borrow self) @@ -123,7 +123,7 @@ extension Box where T: ~Copyable { } } - @available(SwiftStdlib 5.0, *) + @available(SpanAvailability 1.0, *) public var mutableSpan: MutableSpan { @_alwaysEmitIntoClient @_lifetime(&self) diff --git a/Sources/ContainersPreview/Container+Utilities.swift b/Sources/ContainersPreview/Container+Utilities.swift index 407594ad..8cb61ad3 100644 --- a/Sources/ContainersPreview/Container+Utilities.swift +++ b/Sources/ContainersPreview/Container+Utilities.swift @@ -15,7 +15,7 @@ import InternalCollectionsUtilities #if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension Container where Self: ~Copyable & ~Escapable, Element: Copyable { @inlinable package func _copyContents( @@ -36,7 +36,7 @@ extension Container where Self: ~Copyable & ~Escapable, Element: Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension Container where Self: ~Copyable & ~Escapable { @inlinable @discardableResult @@ -120,7 +120,7 @@ extension Container where Self: ~Copyable & ~Escapable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension Container where Self: ~Copyable & ~Escapable, Element: Equatable { @inlinable public func borrowingElementsEqual< diff --git a/Sources/ContainersPreview/Container.swift b/Sources/ContainersPreview/Container.swift index a804e5aa..0d5c4dee 100644 --- a/Sources/ContainersPreview/Container.swift +++ b/Sources/ContainersPreview/Container.swift @@ -11,7 +11,7 @@ #if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) public protocol Container: ~Copyable, ~Escapable { associatedtype Element: ~Copyable /*& ~Escapable*/ associatedtype BorrowIterator: BorrowIteratorProtocol & ~Copyable & ~Escapable @@ -23,7 +23,7 @@ public protocol Container: ~Copyable, ~Escapable { borrowing func startBorrowIteration() -> BorrowIterator } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension Container where Self: ~Copyable & ~Escapable { /// Implementation demo of what borrowing for-in loops would need to expand into. @inlinable @@ -43,7 +43,7 @@ extension Container where Self: ~Copyable & ~Escapable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension Container where Self: ~Copyable & ~Escapable { @inlinable public func borrowingReduce( diff --git a/Sources/ContainersPreview/InputSpan.swift b/Sources/ContainersPreview/InputSpan.swift index 63e7dbc8..6774b7df 100644 --- a/Sources/ContainersPreview/InputSpan.swift +++ b/Sources/ContainersPreview/InputSpan.swift @@ -16,7 +16,7 @@ import InternalCollectionsUtilities #endif import Builtin -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) @safe @frozen public struct InputSpan: ~Copyable, ~Escapable { @@ -47,10 +47,10 @@ public struct InputSpan: ~Copyable, ~Escapable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension InputSpan: @unchecked Sendable where Element: Sendable & ~Copyable {} -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension InputSpan where Element: ~Copyable { @_alwaysEmitIntoClient @_transparent @@ -89,7 +89,7 @@ extension InputSpan where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension InputSpan where Element: ~Copyable { /// Consume the input span and return the number of initialized elements /// remaining at the end of the underlying memory region. @@ -122,7 +122,7 @@ extension InputSpan where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension InputSpan { /// Consume the input span and return the number of initialized elements /// remaining at the end of the underlying memory region. @@ -149,7 +149,7 @@ extension InputSpan { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension InputSpan where Element: ~Copyable { /// The number of initialized elements in this span. @_alwaysEmitIntoClient @@ -168,7 +168,7 @@ extension InputSpan where Element: ~Copyable { public var isFull: Bool { _count == capacity } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension InputSpan where Element: ~Copyable { @unsafe @_alwaysEmitIntoClient @@ -202,7 +202,7 @@ extension InputSpan where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension InputSpan { /// Unsafely create an input span over partially initialized memory. /// @@ -230,7 +230,7 @@ extension InputSpan { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension InputSpan where Element: ~Copyable { /// The type that represents an initialized position in an `InputSpan`. public typealias Index = Int @@ -310,7 +310,7 @@ extension InputSpan where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension InputSpan where Element: ~Copyable { /// Prepend a single element to this span. @_alwaysEmitIntoClient @@ -365,7 +365,7 @@ extension InputSpan where Element: ~Copyable { //MARK: Bulk append functions -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension InputSpan { /// Repeatedly append an element to this span. @_alwaysEmitIntoClient @@ -379,10 +379,10 @@ extension InputSpan { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension InputSpan where Element: ~Copyable { /// Borrow the underlying initialized memory for read-only access. - @available(SwiftStdlib 5.0, *) + @available(SpanAvailability 1.0, *) @_alwaysEmitIntoClient public var span: Span { @_lifetime(borrow self) @@ -397,7 +397,7 @@ extension InputSpan where Element: ~Copyable { } /// Exclusively borrow the underlying initialized memory for mutation. - @available(SwiftStdlib 5.0, *) + @available(SpanAvailability 1.0, *) @_alwaysEmitIntoClient public var mutableSpan: MutableSpan { @_lifetime(&self) @@ -413,7 +413,7 @@ extension InputSpan where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension InputSpan where Element: ~Copyable { /// Call the given closure with the unsafe buffer pointer addressed by this /// InputSpan and a mutable reference to its count of initialized elements. diff --git a/Sources/InternalCollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift.gyb b/Sources/InternalCollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift.gyb index 2bed0319..e1fec1ca 100644 --- a/Sources/InternalCollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift.gyb +++ b/Sources/InternalCollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift.gyb @@ -123,7 +123,7 @@ extension UnsafeMutableBufferPointer { /// The `source` span must fit entirely in `self`. /// /// - Returns: The index after the last item that was initialized in this buffer. - @available(SwiftStdlib 5.0, *) + @available(SpanAvailability 1.0, *) @inlinable ${modifier} func _initializePrefix(copying source: Span) -> Int { source.withUnsafeBufferPointer { self._initializePrefix(copying: $0) } @@ -153,7 +153,7 @@ extension UnsafeMutableBufferPointer { /// entirely uninitialized. /// /// The count of `span` must not be greater than `self.count`. - @available(SwiftStdlib 5.0, *) + @available(SpanAvailability 1.0, *) @inlinable ${modifier} mutating func _initializeAndDropPrefix(copying span: Span) { span.withUnsafeBufferPointer { buffer in diff --git a/Sources/InternalCollectionsUtilities/autogenerated/UnsafeMutableBufferPointer+Extras.swift b/Sources/InternalCollectionsUtilities/autogenerated/UnsafeMutableBufferPointer+Extras.swift index 7abcc67e..8f85911e 100644 --- a/Sources/InternalCollectionsUtilities/autogenerated/UnsafeMutableBufferPointer+Extras.swift +++ b/Sources/InternalCollectionsUtilities/autogenerated/UnsafeMutableBufferPointer+Extras.swift @@ -129,7 +129,7 @@ extension UnsafeMutableBufferPointer { /// The `source` span must fit entirely in `self`. /// /// - Returns: The index after the last item that was initialized in this buffer. - @available(SwiftStdlib 5.0, *) + @available(SpanAvailability 1.0, *) @inlinable internal func _initializePrefix(copying source: Span) -> Int { source.withUnsafeBufferPointer { self._initializePrefix(copying: $0) } @@ -159,7 +159,7 @@ extension UnsafeMutableBufferPointer { /// entirely uninitialized. /// /// The count of `span` must not be greater than `self.count`. - @available(SwiftStdlib 5.0, *) + @available(SpanAvailability 1.0, *) @inlinable internal mutating func _initializeAndDropPrefix(copying span: Span) { span.withUnsafeBufferPointer { buffer in @@ -407,7 +407,7 @@ extension UnsafeMutableBufferPointer { /// The `source` span must fit entirely in `self`. /// /// - Returns: The index after the last item that was initialized in this buffer. - @available(SwiftStdlib 5.0, *) + @available(SpanAvailability 1.0, *) @inlinable public func _initializePrefix(copying source: Span) -> Int { source.withUnsafeBufferPointer { self._initializePrefix(copying: $0) } @@ -437,7 +437,7 @@ extension UnsafeMutableBufferPointer { /// entirely uninitialized. /// /// The count of `span` must not be greater than `self.count`. - @available(SwiftStdlib 5.0, *) + @available(SpanAvailability 1.0, *) @inlinable public mutating func _initializeAndDropPrefix(copying span: Span) { span.withUnsafeBufferPointer { buffer in diff --git a/Sources/TrailingElementsModule/TrailingArray.swift b/Sources/TrailingElementsModule/TrailingArray.swift index 1098d556..de978bc3 100644 --- a/Sources/TrailingElementsModule/TrailingArray.swift +++ b/Sources/TrailingElementsModule/TrailingArray.swift @@ -50,7 +50,7 @@ where Header: ~Copyable _pointer.initialize(to: header) } - @available(SwiftStdlib 5.1, *) + @available(SpanAvailability 1.0, *) @_alwaysEmitIntoClient mutating func _initializeTrailingElements( initializer: (inout OutputSpan) throws(E) -> Void @@ -63,7 +63,7 @@ where Header: ~Copyable /// Allocate an intrusive managed buffer with the given header and calling /// the initializer to fill in the trailing elements. - @available(SwiftStdlib 5.1, *) + @available(SpanAvailability 1.0, *) @_alwaysEmitIntoClient public init( header: consuming Header, @@ -183,7 +183,7 @@ where Header: ~Copyable } /// Accesses the trailing elements following the header. - @available(SwiftStdlib 5.1, *) + @available(SpanAvailability 1.0, *) @_alwaysEmitIntoClient public var elements: Span { @_lifetime(self) @@ -194,7 +194,7 @@ where Header: ~Copyable /// Accesses the trailing elements following the header, allowing mutation /// of those elements. - @available(SwiftStdlib 5.1, *) + @available(SpanAvailability 1.0, *) @_alwaysEmitIntoClient public var mutableElements: MutableSpan { @_lifetime(self) @@ -317,7 +317,7 @@ extension TrailingArray where Header: Copyable { /// That instance is provided to the given `body` to operate on for the /// duration of the call. The temporary is allocated on the stack, unless /// it is very large according to `withUnsafeTemporaryAllocation`. - @available(SwiftStdlib 5.1, *) + @available(SpanAvailability 1.0, *) @_alwaysEmitIntoClient public static func withTemporaryValue( header: consuming Header, diff --git a/Tests/BasicContainersTests/ArrayLayout.swift b/Tests/BasicContainersTests/ArrayLayout.swift index 6ae6e1dd..1ab14795 100644 --- a/Tests/BasicContainersTests/ArrayLayout.swift +++ b/Tests/BasicContainersTests/ArrayLayout.swift @@ -67,6 +67,7 @@ func withSomeArrayLayouts( } #if compiler(>=6.2) +@available(SpanAvailability 1.0, *) extension RigidArray where Element: ~Copyable { init(layout: ArrayLayout, using generator: (Int) -> Element) { self.init(capacity: layout.capacity) { span in @@ -77,12 +78,14 @@ extension RigidArray where Element: ~Copyable { } } +@available(SpanAvailability 1.0, *) extension UniqueArray where Element: ~Copyable { init(layout: ArrayLayout, using generator: (Int) -> Element) { self.init(consuming: RigidArray(layout: layout, using: generator)) } } +@available(SpanAvailability 1.0, *) extension LifetimeTracker { func rigidArray( layout: ArrayLayout, diff --git a/Tests/BasicContainersTests/RigidArrayTests.swift b/Tests/BasicContainersTests/RigidArrayTests.swift index 935de351..129d4c5f 100644 --- a/Tests/BasicContainersTests/RigidArrayTests.swift +++ b/Tests/BasicContainersTests/RigidArrayTests.swift @@ -21,7 +21,7 @@ import BasicContainers #if !COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW /// Check if `left` and `right` contain equal elements in the same order. -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) public func expectContainerContents< Element: Equatable, C2: Collection, @@ -40,7 +40,7 @@ public func expectContainerContents< } /// Check if `left` and `right` contain equal elements in the same order. -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) public func expectContainerContents< E1: ~Copyable, C2: Collection, @@ -61,7 +61,7 @@ public func expectContainerContents< } #endif -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) class RigidArrayTests: CollectionTestCase { func test_validate_Container() { withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in diff --git a/Tests/BasicContainersTests/UniqueArrayTests.swift b/Tests/BasicContainersTests/UniqueArrayTests.swift index 3eaf7488..0b47fa4e 100644 --- a/Tests/BasicContainersTests/UniqueArrayTests.swift +++ b/Tests/BasicContainersTests/UniqueArrayTests.swift @@ -21,7 +21,7 @@ import BasicContainers #if !COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW /// Check if `left` and `right` contain equal elements in the same order. -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) public func expectContainerContents< Element: Equatable, C2: Collection, @@ -40,7 +40,7 @@ public func expectContainerContents< } /// Check if `left` and `right` contain equal elements in the same order. -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) public func expectContainerContents< E1: ~Copyable, C2: Collection, @@ -62,7 +62,7 @@ public func expectContainerContents< #endif -@available(SwiftStdlib 6.2, *) +@available(SpanAvailability 1.0, *) class UniqueArrayTests: CollectionTestCase { func test_validate_Container() { withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in diff --git a/Tests/ContainersTests/RefTests.swift b/Tests/ContainersTests/RefTests.swift index c23ed74d..5e0d20e7 100644 --- a/Tests/ContainersTests/RefTests.swift +++ b/Tests/ContainersTests/RefTests.swift @@ -15,7 +15,7 @@ import ContainersPreview import Synchronization final class RefTests: XCTestCase { - @available(SwiftStdlib 5.0, *) + @available(SpanAvailability 1.0, *) func test_basic() { let x: Atomic? = Atomic(0) diff --git a/Tests/TrailingElementsTests/TrailingElementsTests.swift b/Tests/TrailingElementsTests/TrailingElementsTests.swift index 666f1d8e..d638903a 100644 --- a/Tests/TrailingElementsTests/TrailingElementsTests.swift +++ b/Tests/TrailingElementsTests/TrailingElementsTests.swift @@ -59,6 +59,7 @@ struct ManyBytesWithPointers: TrailingElements { @Suite("Trailing elements tests") struct TrailingElementsTests { + @available(SpanAvailability 1.0, *) @Test func simpleCoordinates() { var coords = TrailingArray( header: Coordinates(numCoordinates: 3) @@ -90,6 +91,7 @@ struct TrailingElementsTests { #expect(coords[2].x == 1) } + @available(SpanAvailability 1.0, *) @Test func temporaryCoordinates() { TrailingArray.withTemporaryValue( header: Coordinates(numCoordinates: 3) @@ -104,6 +106,7 @@ struct TrailingElementsTests { } } + @available(SpanAvailability 1.0, *) @Test(arguments: 0 ... 10) func underalignedByteOnHeap(count: Int) { var pointers = TrailingArray( @@ -125,6 +128,7 @@ struct TrailingElementsTests { } } + @available(SpanAvailability 1.0, *) @Test(arguments: 0 ... 10) func underalignedByteOnStack(count: Int) { TrailingArray.withTemporaryValue(header: OneByteWithPointers(count: count)) { outputSpan in @@ -144,6 +148,7 @@ struct TrailingElementsTests { } } + @available(SpanAvailability 1.0, *) @Test(arguments: 0 ... 10) func underalignedBytesOnHeap(count: Int) { var pointers = TrailingArray(header: ManyBytesWithPointers(count: count)) { outputSpan in @@ -163,6 +168,7 @@ struct TrailingElementsTests { } } + @available(SpanAvailability 1.0, *) @Test(arguments: 0 ... 10) func underalignedBytesOnStack(count: Int) { TrailingArray.withTemporaryValue(header: ManyBytesWithPointers(count: count)) { outputSpan in diff --git a/Tests/_CollectionsTestSupport/AssertionContexts/Assertions+Containers.swift b/Tests/_CollectionsTestSupport/AssertionContexts/Assertions+Containers.swift index e153de16..ae3cd8af 100644 --- a/Tests/_CollectionsTestSupport/AssertionContexts/Assertions+Containers.swift +++ b/Tests/_CollectionsTestSupport/AssertionContexts/Assertions+Containers.swift @@ -18,7 +18,7 @@ import ContainersPreview #if compiler(>=6.2) /// Check if `left` and `right` contain equal elements in the same order. -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) public func expectContainerContents< Element: Equatable, C2: Collection, @@ -57,7 +57,7 @@ public func expectContainerContents< } /// Check if `left` and `right` contain equal elements in the same order. -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) public func expectContainerContents< E1: ~Copyable, C2: Collection, @@ -96,7 +96,7 @@ public func expectContainerContents< } #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) public func expectContainersWithEquivalentElements< C1: Container & ~Copyable & ~Escapable, C2: Container & ~Copyable & ~Escapable @@ -116,7 +116,7 @@ public func expectContainersWithEquivalentElements< } /// Check if `left` and `right` contain equal elements in the same order. -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) public func expectContainersWithEqualElements< Element: Equatable, C1: Container & ~Copyable & ~Escapable, @@ -136,7 +136,7 @@ public func expectContainersWithEqualElements< } /// Check if `left` and `right` contain equal elements in the same order. -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) public func expectContainerContents< Element: Equatable, C1: Container & ~Copyable & ~Escapable, @@ -178,7 +178,7 @@ public func expectContainerContents< } /// Check if `left` and `right` contain equal elements in the same order. -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) public func expectContainerContents< C1: Container & ~Copyable & ~Escapable, C2: Collection, diff --git a/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift b/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift index 032ec094..3c8b5f40 100644 --- a/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift +++ b/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift @@ -13,7 +13,7 @@ import XCTest import ContainersPreview -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) @inlinable public func checkContainer< C: Container & ~Copyable & ~Escapable, @@ -31,7 +31,7 @@ public func checkContainer< file: file, line: line) } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) @inlinable public func checkContainer< C: Container & ~Copyable & ~Escapable, diff --git a/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift b/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift index b61709f8..8a0bff3b 100644 --- a/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift +++ b/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift @@ -19,7 +19,7 @@ import ContainersPreview #if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW /// A container type with user-defined contents and storage chunks. /// Useful for testing. -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) public struct StaccatoContainer: ~Copyable { internal let _contents: RigidArray internal let _spanCounts: [Int] @@ -34,7 +34,7 @@ public struct StaccatoContainer: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) public struct _StaccatoBorrowIterator: BorrowIteratorProtocol, ~Escapable { internal let _contents: Span internal let _spanCounts: [Int] @@ -75,7 +75,7 @@ public struct _StaccatoBorrowIterator: BorrowIteratorProtoco } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension StaccatoContainer: Container where Element: ~Copyable { public typealias BorrowIterator = _StaccatoBorrowIterator // FIXME rdar://150240032 public var isEmpty: Bool { _contents.isEmpty } diff --git a/Tests/_CollectionsTestSupport/Utilities/TestPrintable.swift b/Tests/_CollectionsTestSupport/Utilities/TestPrintable.swift index 5c872d65..a931d129 100644 --- a/Tests/_CollectionsTestSupport/Utilities/TestPrintable.swift +++ b/Tests/_CollectionsTestSupport/Utilities/TestPrintable.swift @@ -74,7 +74,7 @@ where Element: ~Copyable } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension Span: TestPrintable where Element: ~Copyable { public var testDescription: String { self.withUnsafeBufferPointer { buffer in @@ -82,7 +82,7 @@ extension Span: TestPrintable where Element: ~Copyable { } } } -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension MutableSpan: TestPrintable where Element: ~Copyable { public var testDescription: String { self.withUnsafeBufferPointer { buffer in @@ -91,7 +91,7 @@ extension MutableSpan: TestPrintable where Element: ~Copyable { } } #if compiler(>=6.2) -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension OutputSpan: TestPrintable where Element: ~Copyable { public var testDescription: String { let capacity = self.capacity @@ -108,7 +108,7 @@ extension OutputSpan: TestPrintable where Element: ~Copyable { #endif #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW -@available(SwiftStdlib 5.0, *) +@available(SpanAvailability 1.0, *) extension InputSpan: TestPrintable where Element: ~Copyable { public var testDescription: String { let capacity = self.capacity diff --git a/Xcode/Shared.xcconfig b/Xcode/Shared.xcconfig index 21cf3511..a41ca655 100644 --- a/Xcode/Shared.xcconfig +++ b/Xcode/Shared.xcconfig @@ -27,7 +27,8 @@ OTHER_SWIFT_FLAGS = $(inherited) \ -enable-experimental-feature "AvailabilityMacro=SwiftStdlib 5.10: macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4, visionOS 1.1" \ -enable-experimental-feature "AvailabilityMacro=SwiftStdlib 6.0: macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0" \ -enable-experimental-feature "AvailabilityMacro=SwiftStdlib 6.1: macOS 15.4, iOS 18.4, watchOS 11.4, tvOS 18.4, visionOS 2.4" \ - -enable-experimental-feature "AvailabilityMacro=SwiftStdlib 6.2: macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, visionOS 26.0" + -enable-experimental-feature "AvailabilityMacro=SwiftStdlib 6.2: macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, visionOS 26.0" \ + -enable-experimental-feature "AvailabilityMacro=SpanAvailability 1.0: macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, visionOS 26.0" ONLY_ACTIVE_ARCH[config=Debug] = YES From 3a4dba97b5dc125f105a2055c18c360f1a66905c Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 26 Sep 2025 22:38:09 -0700 Subject: [PATCH 15/16] =?UTF-8?q?Don=E2=80=99t=20set=20`TrailingElementsMo?= =?UTF-8?q?dule`=20as=20a=20dependency=20of=20`Collections`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit We are not reexporting this from the top-level `Collections` module. --- Package.swift | 2 -- 1 file changed, 2 deletions(-) diff --git a/Package.swift b/Package.swift index a832bda2..daad4915 100644 --- a/Package.swift +++ b/Package.swift @@ -351,8 +351,6 @@ let targets: [CustomTarget] = [ "HeapModule", "OrderedCollections", "_RopeModule", - "TrailingElementsModule", - //"SortedCollections", ], exclude: ["CMakeLists.txt"]) ] From f4d851a739f6f1cfd0364b1c1ceb9aadd1b07f2f Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 26 Sep 2025 22:44:36 -0700 Subject: [PATCH 16/16] Disable CI testing with Xcode 26 for now MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SwiftPM’s command line test runner is unable to load the Span backdeployment library (libswiftCompatibilitySpan.dylib) when trying to execute tests for the new modules (BasicContainers, ContainersPreview and TrailingElementsModule) on older macOS releases. I see no obvious way to work around this. --- .github/workflows/pull_request.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index cedd1dfd..506c4a3d 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -11,7 +11,7 @@ jobs: with: linux_exclude_swift_versions: '[{"swift_version": "5.8"}, {"swift_version": "5.9"}, {"swift_version": "5.10"}]' windows_exclude_swift_versions: '[{"swift_version": "5.9"}, {"swift_version": "5.10"}]' - macos_exclude_xcode_versions: '[{"xcode_version": "16.0"}, {"xcode_version": "16.1"}, {"xcode_version": "26.b6"}]' + macos_exclude_xcode_versions: '[{"xcode_version": "26.0"}]' enable_macos_checks: true enable_wasm_sdk_build: true