diff --git a/Sources/BasicContainers/RigidArray+Append.swift b/Sources/BasicContainers/RigidArray+Append.swift index aa5c6d13..43805a6b 100644 --- a/Sources/BasicContainers/RigidArray+Append.swift +++ b/Sources/BasicContainers/RigidArray+Append.swift @@ -274,9 +274,9 @@ extension RigidArray { #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW @inlinable internal mutating func _append< - Source: Iterable & ~Copyable & ~Escapable + Source: BorrowingSequence & ~Copyable & ~Escapable >( - copyingIterable newElements: borrowing Source + copying newElements: borrowing Source ) { let target = _freeSpace _count += newElements._copyContents(intoPrefixOf: target) @@ -284,10 +284,10 @@ extension RigidArray { #endif #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW - /// Copies the elements of a container to the end of this array. + /// Copies the elements of a borrowing sequence 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. + /// source sequence, then this triggers a runtime error. /// /// - Parameters /// - newElements: A container whose contents to copy into the array. @@ -296,11 +296,11 @@ extension RigidArray { @_alwaysEmitIntoClient @inline(__always) public mutating func append< - Source: Iterable & ~Copyable & ~Escapable + Source: BorrowingSequence & ~Copyable & ~Escapable >( copying newElements: borrowing Source ) { - _append(copyingIterable: newElements) + _append(copying: newElements) } #endif @@ -326,10 +326,10 @@ extension RigidArray { } #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW - /// Copies the elements of a container to the end of this array. + /// Copies the elements of a borrowing sequence 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. + /// source sequence, then this triggers a runtime error. /// /// - Parameters /// - newElements: The new elements to copy into the array. @@ -338,9 +338,9 @@ extension RigidArray { @_alwaysEmitIntoClient @inline(__always) public mutating func append< - Source: Iterable & Sequence + Source: BorrowingSequence & Sequence >(copying newElements: Source) { - _append(copyingIterable: newElements) + _append(copying: newElements) } #endif } diff --git a/Sources/BasicContainers/RigidArray+Initializers.swift b/Sources/BasicContainers/RigidArray+Initializers.swift index 3fd7f2e7..bd88514a 100644 --- a/Sources/BasicContainers/RigidArray+Initializers.swift +++ b/Sources/BasicContainers/RigidArray+Initializers.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors +// Copyright (c) 2024 - 2026 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information @@ -98,7 +98,7 @@ extension RigidArray /*where Element: Copyable*/ { /// The container must not contain more than `capacity` elements. @_alwaysEmitIntoClient @inline(__always) - public init & ~Copyable & ~Escapable>( + public init & ~Copyable & ~Escapable>( capacity: Int, copying contents: borrowing Source ) { @@ -119,7 +119,7 @@ extension RigidArray /*where Element: Copyable*/ { /// The container must not contain more than `capacity` elements. @_alwaysEmitIntoClient @inline(__always) - public init & Sequence>( + public init & Sequence>( capacity: Int, copying contents: Source ) { diff --git a/Sources/BasicContainers/RigidArray.swift b/Sources/BasicContainers/RigidArray.swift index e661a306..e636cad6 100644 --- a/Sources/BasicContainers/RigidArray.swift +++ b/Sources/BasicContainers/RigidArray.swift @@ -286,9 +286,9 @@ extension RigidArray where Element: ~Copyable { #if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW @available(SwiftStdlib 5.0, *) -extension RigidArray: Iterable where Element: ~Copyable { +extension RigidArray: BorrowingSequence where Element: ~Copyable { @frozen - public struct BorrowIterator: ~Copyable, ~Escapable, BorrowIteratorProtocol { + public struct BorrowingIterator: ~Copyable, ~Escapable, BorrowingIteratorProtocol { @usableFromInline internal let _span: Span @@ -327,7 +327,7 @@ extension RigidArray: Iterable where Element: ~Copyable { @_alwaysEmitIntoClient @inline(__always) - public func startBorrowIteration() -> BorrowIterator { + public func makeBorrowingIterator() -> BorrowingIterator { .init(_span: self.span, offset: 0) } } diff --git a/Sources/BasicContainers/UniqueArray+Append.swift b/Sources/BasicContainers/UniqueArray+Append.swift index bb114597..6843b9ab 100644 --- a/Sources/BasicContainers/UniqueArray+Append.swift +++ b/Sources/BasicContainers/UniqueArray+Append.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors +// Copyright (c) 2024 - 2026 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information @@ -233,12 +233,12 @@ extension UniqueArray { #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW @inlinable internal mutating func _append< - Source: Iterable & ~Copyable & ~Escapable + Source: BorrowingSequence & ~Copyable & ~Escapable >( - copyingIterable newElements: borrowing Source + copying newElements: borrowing Source ) { _ensureFreeCapacity(newElements.underestimatedCount) - var it = newElements.startBorrowIteration() + var it = newElements.makeBorrowingIterator() while true { let span = it.nextSpan() if span.isEmpty { break } @@ -250,7 +250,7 @@ extension UniqueArray { #endif #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW - /// Copies the elements of an iterable to the end of this array. + /// Copies the elements of a borrowing 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, using @@ -266,11 +266,11 @@ extension UniqueArray { @_alwaysEmitIntoClient @inline(__always) public mutating func append< - Source: Iterable & ~Copyable & ~Escapable + Source: BorrowingSequence & ~Copyable & ~Escapable >( copying newElements: borrowing Source ) { - self._append(copyingIterable: newElements) + self._append(copying: newElements) } #endif @@ -320,9 +320,9 @@ extension UniqueArray { @_alwaysEmitIntoClient @inline(__always) public mutating func append< - Source: Iterable & Sequence + Source: BorrowingSequence & Sequence >(copying newElements: Source) { - self._append(copyingIterable: newElements) + self._append(copying: newElements) } #endif } diff --git a/Sources/BasicContainers/UniqueArray+Initializers.swift b/Sources/BasicContainers/UniqueArray+Initializers.swift index ee731b61..950cbb82 100644 --- a/Sources/BasicContainers/UniqueArray+Initializers.swift +++ b/Sources/BasicContainers/UniqueArray+Initializers.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors +// Copyright (c) 2024 - 2026 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information @@ -70,16 +70,16 @@ extension UniqueArray where Element: ~Copyable { extension UniqueArray /*where Element: Copyable*/ { #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW /// Creates a new array with the specified initial capacity, holding a copy - /// of the contents of a given iterable. + /// of the contents of a given borrowing sequence. /// /// - Parameters: /// - capacity: The storage capacity of the new array, or nil to allocate /// just enough capacity to store the contents. - /// - contents: An iterable whose contents to copy into the new array. - /// The iterable must not contain more than `capacity` elements. + /// - contents: A sequence whose contents to copy into the new array. + /// The sequence must not contain more than `capacity` elements. @_alwaysEmitIntoClient @inline(__always) - public init & ~Copyable & ~Escapable>( + public init & ~Copyable & ~Escapable>( capacity: Int? = nil, copying contents: borrowing Source ) { @@ -115,7 +115,7 @@ extension UniqueArray /*where Element: Copyable*/ { /// - contents: The container whose contents to copy into the new array. @_alwaysEmitIntoClient @inline(__always) - public init & Sequence>( + public init & Sequence>( capacity: Int? = nil, copying contents: Source ) { diff --git a/Sources/BasicContainers/UniqueArray.swift b/Sources/BasicContainers/UniqueArray.swift index 0c3122ad..a1ff802b 100644 --- a/Sources/BasicContainers/UniqueArray.swift +++ b/Sources/BasicContainers/UniqueArray.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors +// Copyright (c) 2024 - 2026 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information @@ -177,8 +177,8 @@ extension UniqueArray where Element: ~Copyable { #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW @available(SwiftStdlib 5.0, *) -extension UniqueArray: Iterable where Element: ~Copyable { - public typealias BorrowIterator = RigidArray.BorrowIterator +extension UniqueArray: BorrowingSequence where Element: ~Copyable { + public typealias BorrowingIterator = RigidArray.BorrowingIterator public var estimatedCount: ContainersPreview.EstimatedCount { .exactly(count) @@ -186,8 +186,8 @@ extension UniqueArray: Iterable where Element: ~Copyable { @_alwaysEmitIntoClient @inline(__always) - public func startBorrowIteration() -> BorrowIterator { - self._storage.startBorrowIteration() + public func makeBorrowingIterator() -> BorrowingIterator { + self._storage.makeBorrowingIterator() } } #endif diff --git a/Sources/ContainersPreview/CMakeLists.txt b/Sources/ContainersPreview/CMakeLists.txt index d24327e6..a7f43d1d 100644 --- a/Sources/ContainersPreview/CMakeLists.txt +++ b/Sources/ContainersPreview/CMakeLists.txt @@ -23,7 +23,7 @@ else() endif() target_sources(${module_name} PRIVATE - "BorrowIteratorProtocol.swift" + "BorrowingIteratorProtocol.swift" "Box.swift" "Container.swift" "Container+Utilities.swift" diff --git a/Sources/ContainersPreview/OutputSpan+Extras.swift b/Sources/ContainersPreview/Extensions/OutputSpan+Extras.swift similarity index 63% rename from Sources/ContainersPreview/OutputSpan+Extras.swift rename to Sources/ContainersPreview/Extensions/OutputSpan+Extras.swift index 8cad92ad..df6c849e 100644 --- a/Sources/ContainersPreview/OutputSpan+Extras.swift +++ b/Sources/ContainersPreview/Extensions/OutputSpan+Extras.swift @@ -53,7 +53,7 @@ extension OutputSpan where Element: ~Copyable { extension OutputSpan where Element: ~Copyable { @_lifetime(source: copy source) @inlinable - internal mutating func _append(moving source: inout InputSpan) { + package mutating func _append(moving source: inout InputSpan) { // FIXME: This needs to be in the stdlib. self.withUnsafeMutableBufferPointer { dst, dstCount in source.withUnsafeMutableBufferPointer { src, srcCount in @@ -69,6 +69,42 @@ extension OutputSpan where Element: ~Copyable { } } } + + @_lifetime(source: copy source) + @inlinable + package mutating func _append(moving source: inout OutputSpan) { + // FIXME: This needs to be in the stdlib. + self.withUnsafeMutableBufferPointer { dst, dstCount in + source.withUnsafeMutableBufferPointer { src, srcCount in + let dstEnd = dstCount + srcCount + precondition(dstEnd <= dst.count, "OutputSpan capacity overflow") + let srcItems = src._extracting(uncheckedFrom: 0, to: srcCount) + dst + ._extracting(uncheckedFrom: dstCount, to: dstEnd) + .moveInitializeAll(fromContentsOf: srcItems) + dstCount &+= srcCount + srcCount = 0 + } + } + } +} + +@available(SwiftStdlib 5.0, *) +extension OutputSpan /* where Element: Copyable */ { + @inlinable + package mutating func _append(copying source: borrowing Span) { + // FIXME: This needs to be in the stdlib. + self.withUnsafeMutableBufferPointer { dst, dstCount in + source.withUnsafeBufferPointer { src in + let dstEnd = dstCount + src.count + precondition(dstEnd <= dst.count, "OutputSpan capacity overflow") + dst + ._extracting(uncheckedFrom: dstCount, to: dstEnd) + .initializeAll(fromContentsOf: src) + dstCount &+= src.count + } + } + } } diff --git a/Sources/ContainersPreview/TemporaryAllocation.swift b/Sources/ContainersPreview/Extensions/TemporaryAllocation.swift similarity index 100% rename from Sources/ContainersPreview/TemporaryAllocation.swift rename to Sources/ContainersPreview/Extensions/TemporaryAllocation.swift diff --git a/Sources/ContainersPreview/BorrowIteratorProtocol.swift b/Sources/ContainersPreview/Protocols/BorrowIteratorProtocol.swift similarity index 85% rename from Sources/ContainersPreview/BorrowIteratorProtocol.swift rename to Sources/ContainersPreview/Protocols/BorrowIteratorProtocol.swift index 864de931..d0f4894b 100644 --- a/Sources/ContainersPreview/BorrowIteratorProtocol.swift +++ b/Sources/ContainersPreview/Protocols/BorrowIteratorProtocol.swift @@ -16,7 +16,7 @@ import InternalCollectionsUtilities #endif @available(SwiftStdlib 5.0, *) -public protocol BorrowIteratorProtocol: ~Copyable, ~Escapable { +public protocol BorrowingIteratorProtocol: ~Copyable, ~Escapable { associatedtype Element: ~Copyable // FIXME: This ought to be a core requirement, but `Ref` is not a thing yet. @@ -27,15 +27,15 @@ public protocol BorrowIteratorProtocol: ~Copyable, ~Escapable { /// Advance the iterator, returning an ephemeral span over the elements /// that are ready to be visited. /// - /// If the underlying iterable is a container type, then the returned span + /// If the underlying sequence is a container type, then the returned span /// typically directly addresses one of its storage buffers. On the other - /// hand, if the underlying iterable materializes its elements on demand, + /// hand, if the underlying sequence materializes its elements on demand, /// then the returned span addresses some temporary buffer associated with /// the iterator itself. Consequently, the returned span is tied to this /// particular invocation of `nextSpan`, and it cannot survive until the next /// invocation of it. /// - /// If the iterator has not yet reached the end of the underlying iterable, + /// If the iterator has not yet reached the end of the underlying sequence, /// then this method returns a non-empty span of at most `maximumCount` /// elements, and updates the iterator's current position to the element /// following the last item in the returned span (or the end, if there is @@ -50,7 +50,7 @@ public protocol BorrowIteratorProtocol: ~Copyable, ~Escapable { /// in bulk, by directly iterating over its piecewise contiguous pieces of /// storage: /// - /// var it = items.startBorrowIteration() + /// var it = items.makeBorrowingIterator() /// while true { /// let span = it.nextSpan(after: &index) /// if span.isEmpty { break } @@ -75,27 +75,27 @@ public protocol BorrowIteratorProtocol: ~Copyable, ~Escapable { mutating func nextSpan(maximumCount: Int) -> Span /// Advance the position of this iterator by the specified offset, or until - /// the end of the underlying iterable. + /// the end of the underlying sequence. /// /// Returns the number of items that were skipped. If this is less than - /// `maximumOffset`, then the iterable did not have enough elements left to + /// `maximumOffset`, then the sequence did not have enough elements left to /// skip the requested number of items. In this case, the iterator's current - /// position is set to the end of the iterable. + /// position is set to the end of the sequence. /// /// `maximumOffset` must be nonnegative, unless this is a bidirectional /// or random-access iterator. @_lifetime(self: copy self) mutating func skip(by maximumOffset: Int) -> Int - // FIXME: Add BidirectionalBorrowIteratorProtocol and RandomAccessBorrowIteratorProtocol. - // BidirectionalBorrowIteratorProtocol would need to have a `previousSpan` + // FIXME: Add BidirectionalBorrowingIteratorProtocol and RandomAccessBorrowingIteratorProtocol. + // BidirectionalBorrowingIteratorProtocol would need to have a `previousSpan` // method, which considerably complicates implementation. // Perhaps these would be better left to as variants of protocol Container, // which do not need a separate iterator concept. } @available(SwiftStdlib 5.0, *) -extension BorrowIteratorProtocol where Self: ~Copyable & ~Escapable { +extension BorrowingIteratorProtocol where Self: ~Copyable & ~Escapable { @_lifetime(&self) @_lifetime(self: copy self) @_transparent @@ -105,7 +105,7 @@ extension BorrowIteratorProtocol where Self: ~Copyable & ~Escapable { } @available(SwiftStdlib 5.0, *) -extension BorrowIteratorProtocol where Self: ~Copyable & ~Escapable { +extension BorrowingIteratorProtocol where Self: ~Copyable & ~Escapable { @_lifetime(self: copy self) @inlinable public mutating func skip(by offset: Int) -> Int { @@ -120,7 +120,7 @@ extension BorrowIteratorProtocol where Self: ~Copyable & ~Escapable { } @available(SwiftStdlib 5.0, *) -extension BorrowIteratorProtocol where Self: ~Copyable & ~Escapable { +extension BorrowingIteratorProtocol where Self: ~Copyable & ~Escapable { #if false // FIXME: This doesn't work, but it should? @_lifetime(&self) @_lifetime(self: copy self) @@ -140,7 +140,7 @@ extension BorrowIteratorProtocol where Self: ~Copyable & ~Escapable { } @available(SwiftStdlib 5.0, *) -extension BorrowIteratorProtocol +extension BorrowingIteratorProtocol where Self: ~Copyable & ~Escapable, Element: Copyable { @_lifetime(self: copy self) @@ -159,7 +159,7 @@ where Self: ~Copyable & ~Escapable, Element: Copyable } @available(SwiftStdlib 5.0, *) -extension Span: BorrowIteratorProtocol where Element: ~Copyable { +extension Span: BorrowingIteratorProtocol where Element: ~Copyable { @_lifetime(copy self) @_lifetime(self: copy self) @inlinable @@ -174,7 +174,7 @@ extension Span: BorrowIteratorProtocol where Element: ~Copyable { #if false // FIXME: Implement this @available(SwiftStdlib 5.0, *) -extension MutableSpan: BorrowIteratorProtocol where Element: ~Copyable { +extension MutableSpan: BorrowingIteratorProtocol where Element: ~Copyable { @_lifetime(copy self) @_lifetime(self: copy self) @inlinable @@ -186,7 +186,7 @@ extension MutableSpan: BorrowIteratorProtocol where Element: ~Copyable { #if false // FIXME: Implement this @available(SwiftStdlib 5.0, *) -extension OutputSpan: BorrowIteratorProtocol where Element: ~Copyable { +extension OutputSpan: BorrowingIteratorProtocol where Element: ~Copyable { @_lifetime(copy self) @_lifetime(self: copy self) @inlinable diff --git a/Sources/ContainersPreview/Container.swift b/Sources/ContainersPreview/Protocols/Container.swift similarity index 96% rename from Sources/ContainersPreview/Container.swift rename to Sources/ContainersPreview/Protocols/Container.swift index bb851f0b..ff635855 100644 --- a/Sources/ContainersPreview/Container.swift +++ b/Sources/ContainersPreview/Protocols/Container.swift @@ -12,7 +12,7 @@ #if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW @available(SwiftStdlib 5.0, *) -public protocol Container: Iterable, ~Copyable, ~Escapable { +public protocol Container: BorrowingSequence, ~Copyable, ~Escapable { associatedtype Index: Comparable var count: Int { get } @@ -261,18 +261,18 @@ extension Container where Self: ~Copyable & ~Escapable { public struct ContainerIterator< Base: Container & ~Copyable /*FIXME: & ~Escapable*/ >: ~Copyable, ~Escapable { - let _base: Ref // FIXME: This doesn't support nonescapable Bases + let _base: Borrow // FIXME: This doesn't support nonescapable Bases var _position: Base.Index @_lifetime(borrow base) init(_borrowing base: borrowing @_addressable Base, from position: Base.Index) { - self._base = Ref(_borrowing: base) + self._base = Borrow(_borrowing: base) self._position = position } } @available(SwiftStdlib 5.0, *) -extension ContainerIterator: BorrowIteratorProtocol +extension ContainerIterator: BorrowingIteratorProtocol where Base: ~Copyable /*FIXME: & ~Escapable*/ { public typealias Element = Base.Element @@ -288,10 +288,10 @@ where Base: ~Copyable /*FIXME: & ~Escapable*/ extension Container where Self: ~Copyable /*FIXME: & ~Escapable*/, - BorrowIterator == ContainerIterator + BorrowingIterator == ContainerIterator { @_lifetime(borrow self) - public func startBorrowIteration() -> BorrowIterator { + public func makeBorrowingIterator() -> BorrowingIterator { ContainerIterator(_borrowing: self, from: self.startIndex) } } diff --git a/Sources/ContainersPreview/Drain.swift b/Sources/ContainersPreview/Protocols/Drain.swift similarity index 96% rename from Sources/ContainersPreview/Drain.swift rename to Sources/ContainersPreview/Protocols/Drain.swift index 943b4385..60a6d7a9 100644 --- a/Sources/ContainersPreview/Drain.swift +++ b/Sources/ContainersPreview/Protocols/Drain.swift @@ -55,7 +55,7 @@ where ProducerError == Never /// the end of the sequence. @_lifetime(&self) @_lifetime(self: copy self) - mutating func drainNext(maximumCount: Int?) -> InputSpan + mutating func drainNext(maximumCount: Int) -> InputSpan // TODO: The primary use case does not need this to throw; do we need to allow that? // Note: making this failable is not entirely straightforward, as there is no // easy way to signal partial success -- conforming implementations @@ -109,7 +109,7 @@ extension Drain where Self: ~Copyable & ~Escapable { @_lifetime(self: copy self) @_transparent mutating func drainNext() -> InputSpan { - drainNext(maximumCount: nil) + drainNext(maximumCount: Int.max) } /// Generate the next batch of items into the supplied output span instance, @@ -158,8 +158,9 @@ extension Drain where Self: ~Copyable & ~Escapable { /// - Returns: A boolean value indicating whether the operation was able to /// append at least one item to the supplied output span without hitting /// the end of the underlying sequence. + @inlinable @_lifetime(target: copy target) - mutating func generate( + public mutating func generate( into target: inout OutputSpan ) throws(Never) -> Bool { var source = self.drainNext(maximumCount: target.freeCapacity) @@ -200,16 +201,15 @@ extension Drain where Self: ~Copyable & ~Escapable { @inlinable @_lifetime(self: copy self) public mutating func skip( - remainder: inout Int + upTo n: inout Int ) throws(ProducerError) -> Bool { - precondition(remainder >= 0, "Can't skip a negative number of elements") - guard remainder > 0 else { return true } - let span = drainNext(maximumCount: remainder) + precondition(n >= 0, "Can't skip a negative number of elements") + guard n > 0 else { return true } + let span = drainNext(maximumCount: n) let success = span.count > 0 - remainder &-= span.count + n &-= span.count return success } - } #endif diff --git a/Sources/ContainersPreview/Iterable+Standard Conformances.swift b/Sources/ContainersPreview/Protocols/Iterable+Standard Conformances.swift similarity index 63% rename from Sources/ContainersPreview/Iterable+Standard Conformances.swift rename to Sources/ContainersPreview/Protocols/Iterable+Standard Conformances.swift index 22bc7dbd..0131f8ec 100644 --- a/Sources/ContainersPreview/Iterable+Standard Conformances.swift +++ b/Sources/ContainersPreview/Protocols/Iterable+Standard Conformances.swift @@ -12,11 +12,11 @@ #if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW @available(SwiftStdlib 5.0, *) -extension Span: Iterable where Element: ~Copyable { +extension Span: BorrowingSequence where Element: ~Copyable { // FIXME: This simple definition cannot also be a backward (or bidirectional) // iterator, nor a random-access iterator. If we want to go in that direction, - // we'll need to rather introduce a type more like `RigidArray.BorrowIterator`. - public typealias BorrowIterator = Self + // we'll need to rather introduce a type more like `RigidArray.BorrowingIterator`. + public typealias BorrowingIterator = Self @inlinable public var estimatedCount: EstimatedCount { @@ -25,14 +25,14 @@ extension Span: Iterable where Element: ~Copyable { @_lifetime(copy self) @inlinable - public func startBorrowIteration() -> Span { + public func makeBorrowingIterator() -> Span { self } } @available(SwiftStdlib 5.0, *) -extension MutableSpan: Iterable where Element: ~Copyable { - public typealias BorrowIterator = Span.BorrowIterator +extension MutableSpan: BorrowingSequence where Element: ~Copyable { + public typealias BorrowingIterator = Span.BorrowingIterator @inlinable public var estimatedCount: EstimatedCount { @@ -41,14 +41,14 @@ extension MutableSpan: Iterable where Element: ~Copyable { @_lifetime(borrow self) @inlinable - public func startBorrowIteration() -> Span { + public func makeBorrowingIterator() -> Span { self.span } } @available(SwiftStdlib 5.0, *) -extension OutputSpan: Iterable where Element: ~Copyable { - public typealias BorrowIterator = Span.BorrowIterator +extension OutputSpan: BorrowingSequence where Element: ~Copyable { + public typealias BorrowingIterator = Span.BorrowingIterator @inlinable public var estimatedCount: EstimatedCount { @@ -57,14 +57,14 @@ extension OutputSpan: Iterable where Element: ~Copyable { @_lifetime(borrow self) @inlinable - public func startBorrowIteration() -> Span { + public func makeBorrowingIterator() -> Span { self.span } } @available(SwiftStdlib 5.0, *) -extension InputSpan: Iterable where Element: ~Copyable { - public typealias BorrowIterator = Span.BorrowIterator +extension InputSpan: BorrowingSequence where Element: ~Copyable { + public typealias BorrowingIterator = Span.BorrowingIterator @inlinable public var estimatedCount: EstimatedCount { @@ -73,14 +73,14 @@ extension InputSpan: Iterable where Element: ~Copyable { @_lifetime(borrow self) @inlinable - public func startBorrowIteration() -> Span { + public func makeBorrowingIterator() -> Span { self.span } } @available(SwiftStdlib 6.2, *) -extension Array: Iterable { - public typealias BorrowIterator = Span.BorrowIterator +extension Array: BorrowingSequence { + public typealias BorrowingIterator = Span.BorrowingIterator @inlinable public var estimatedCount: EstimatedCount { @@ -89,7 +89,7 @@ extension Array: Iterable { @_lifetime(borrow self) @inlinable - public func startBorrowIteration() -> Span { + public func makeBorrowingIterator() -> Span { self.span } } diff --git a/Sources/ContainersPreview/Iterable+Utilities.swift b/Sources/ContainersPreview/Protocols/Iterable+Utilities.swift similarity index 78% rename from Sources/ContainersPreview/Iterable+Utilities.swift rename to Sources/ContainersPreview/Protocols/Iterable+Utilities.swift index 31a86d5e..4032273b 100644 --- a/Sources/ContainersPreview/Iterable+Utilities.swift +++ b/Sources/ContainersPreview/Protocols/Iterable+Utilities.swift @@ -16,13 +16,13 @@ import InternalCollectionsUtilities #if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW @available(SwiftStdlib 5.0, *) -extension Iterable where Self: ~Copyable & ~Escapable, Element: Copyable { +extension BorrowingSequence where Self: ~Copyable & ~Escapable, Element: Copyable { @inlinable package func _copyContents( intoPrefixOf buffer: UnsafeMutableBufferPointer ) -> Int { var target = buffer - var it = self.startBorrowIteration() + var it = self.makeBorrowingIterator() while target.count != 0 { let span = it.nextSpan(maximumCount: target.count) if span.isEmpty { @@ -38,10 +38,10 @@ extension Iterable where Self: ~Copyable & ~Escapable, Element: Copyable { #if true @available(SwiftStdlib 5.0, *) -extension Iterable where Self: ~Copyable & ~Escapable { +extension BorrowingSequence where Self: ~Copyable & ~Escapable { @inlinable public func elementsEqual< - Other: Iterable & ~Copyable & ~Escapable + Other: BorrowingSequence & ~Copyable & ~Escapable >( _ other: borrowing Other, ) -> Bool where Element: Equatable { @@ -51,8 +51,8 @@ extension Iterable where Self: ~Copyable & ~Escapable { default: break } - var it1 = self.startBorrowIteration() - var it2 = other.startBorrowIteration() + var it1 = self.makeBorrowingIterator() + var it2 = other.makeBorrowingIterator() while true { let a = it1.nextSpan() var i = 0 @@ -78,10 +78,10 @@ extension Iterable where Self: ~Copyable & ~Escapable { } @available(SwiftStdlib 5.0, *) -extension Iterable where Self: ~Copyable & ~Escapable { - /// Returns a Boolean value indicating whether this Iterable and another - /// Iterable contain equivalent elements in the same order, using the given - /// predicate as the equivalence test. +extension BorrowingSequence where Self: ~Copyable & ~Escapable { + /// Returns a Boolean value indicating whether two borrowing sequences 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 @@ -93,17 +93,17 @@ extension Iterable where Self: ~Copyable & ~Escapable { /// `areEquivalent(a, c)` is also `true`. (Transitivity) /// /// - Parameters: - /// - other: A Iterable to compare to this Iterable. + /// - other: A BorrowingSequence to compare to this BorrowingSequence. /// - areEquivalent: A predicate that returns `true` if its two arguments /// are equivalent; otherwise, `false`. - /// - Returns: `true` if this Iterable and `other` contain equivalent items, + /// - Returns: `true` if this BorrowingSequence 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 Iterables. + /// - Complexity: O(*m*), where *m* is the count of the longer of the input sequences. @inlinable public func elementsEqual< E: Error, - Other: Iterable & ~Copyable & ~Escapable + Other: BorrowingSequence & ~Copyable & ~Escapable >( _ other: borrowing Other, by areEquivalent: (borrowing Element, borrowing Other.Element) throws(E) -> Bool @@ -114,8 +114,8 @@ extension Iterable where Self: ~Copyable & ~Escapable { default: break } - var it1 = self.startBorrowIteration() - var it2 = other.startBorrowIteration() + var it1 = self.makeBorrowingIterator() + var it2 = other.makeBorrowingIterator() while true { let a = it1.nextSpan() var i = 0 @@ -144,15 +144,15 @@ extension Iterable where Self: ~Copyable & ~Escapable { #else // rdar://150228920 @available(SwiftStdlib 5.0, *) -extension Iterable where Self: ~Copyable & ~Escapable { +extension BorrowingSequence where Self: ~Copyable & ~Escapable { @inlinable public func elementsEqual< - Other: Iterable & ~Copyable & ~Escapable + Other: BorrowingSequence & ~Copyable & ~Escapable >( _ other: borrowing Other, ) -> Bool where Element: Equatable { - var it1 = self.startBorrowIteration() - var it2 = other.startBorrowIteration() + var it1 = self.makeBorrowingIterator() + var it2 = other.makeBorrowingIterator() var a = Span() var b = Span() loop: @@ -180,19 +180,19 @@ extension Iterable where Self: ~Copyable & ~Escapable { } @available(SwiftStdlib 5.0, *) -extension Iterable where Self: ~Copyable & ~Escapable { +extension BorrowingSequence where Self: ~Copyable & ~Escapable { @inlinable @discardableResult internal func _spanwiseZip< - Other: Iterable & ~Copyable & ~Escapable, + Other: BorrowingSequence & ~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 it1 = self.makeBorrowingIterator() + var it2 = other.makeBorrowingIterator() var a = Span() var b = Span() var offset = 0 // Offset of the start of the current spans @@ -218,8 +218,8 @@ extension Iterable where Self: ~Copyable & ~Escapable { } } - /// Returns a Boolean value indicating whether this Iterable and another - /// Iterable contain equivalent elements in the same order, using the given + /// Returns a Boolean value indicating whether this BorrowingSequence and another + /// BorrowingSequence 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 @@ -232,17 +232,17 @@ extension Iterable where Self: ~Copyable & ~Escapable { /// `areEquivalent(a, c)` is also `true`. (Transitivity) /// /// - Parameters: - /// - other: A Iterable to compare to this Iterable. + /// - other: A BorrowingSequence to compare to this BorrowingSequence. /// - areEquivalent: A predicate that returns `true` if its two arguments /// are equivalent; otherwise, `false`. - /// - Returns: `true` if this Iterable and `other` contain equivalent items, + /// - Returns: `true` if this BorrowingSequence 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 Iterables. + /// - Complexity: O(*m*), where *m* is the count of the longer of the input sequences. @inlinable public func elementsEqual< E: Error, - Other: Iterable & ~Copyable & ~Escapable + Other: BorrowingSequence & ~Copyable & ~Escapable >( _ other: borrowing Other, by areEquivalent: (borrowing Element, borrowing Other.Element) throws(E) -> Bool @@ -264,10 +264,10 @@ extension Iterable where Self: ~Copyable & ~Escapable { } @available(SwiftStdlib 5.0, *) -extension Iterable where Self: ~Copyable & ~Escapable, Element: Equatable { +extension BorrowingSequence where Self: ~Copyable & ~Escapable, Element: Equatable { @inlinable public func elementsEqual< - Other: Iterable & ~Copyable & ~Escapable + Other: BorrowingSequence & ~Copyable & ~Escapable >( _ other: borrowing Other, ) -> Bool { diff --git a/Sources/ContainersPreview/Iterable.swift b/Sources/ContainersPreview/Protocols/Iterable.swift similarity index 82% rename from Sources/ContainersPreview/Iterable.swift rename to Sources/ContainersPreview/Protocols/Iterable.swift index e7306cc7..19ece213 100644 --- a/Sources/ContainersPreview/Iterable.swift +++ b/Sources/ContainersPreview/Protocols/Iterable.swift @@ -18,16 +18,16 @@ public enum EstimatedCount { } @available(SwiftStdlib 5.0, *) -public protocol Iterable: ~Copyable, ~Escapable { +public protocol BorrowingSequence: ~Copyable, ~Escapable { associatedtype Element: ~Copyable - associatedtype BorrowIterator: BorrowIteratorProtocol & ~Copyable & ~Escapable + associatedtype BorrowingIterator: BorrowingIteratorProtocol & ~Copyable & ~Escapable var isEmpty: Bool { get } var estimatedCount: EstimatedCount { get } @_lifetime(borrow self) - borrowing func startBorrowIteration() -> BorrowIterator + borrowing func makeBorrowingIterator() -> BorrowingIterator func _customContainsEquatableElement( _ element: borrowing Element @@ -35,7 +35,7 @@ public protocol Iterable: ~Copyable, ~Escapable { } @available(SwiftStdlib 5.0, *) -extension Iterable where Self: ~Copyable & ~Escapable { +extension BorrowingSequence where Self: ~Copyable & ~Escapable { @inlinable public var underestimatedCount: Int { switch estimatedCount { @@ -55,7 +55,7 @@ extension Iterable where Self: ~Copyable & ~Escapable { } @available(SwiftStdlib 5.0, *) -extension Iterable where Self: Sequence { +extension BorrowingSequence where Self: Sequence { @inlinable public func _customContainsEquatableElement(_ element: borrowing Element) -> Bool? { nil @@ -63,10 +63,10 @@ extension Iterable where Self: Sequence { } @available(SwiftStdlib 5.0, *) -extension Iterable where Element: Copyable { +extension BorrowingSequence where Element: Copyable { // FIXME: How do we expect this to work for ~Copyable elements? public var first: Element? { - var it = startBorrowIteration() + var it = makeBorrowingIterator() let span = it.nextSpan(maximumCount: 1) guard !span.isEmpty else { return nil } return span[0] @@ -76,13 +76,13 @@ extension Iterable where Element: Copyable { @available(SwiftStdlib 5.0, *) -extension Iterable where Self: ~Copyable & ~Escapable { +extension BorrowingSequence 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() + var it = makeBorrowingIterator() while true { let span = it.nextSpan() if span.isEmpty { break } @@ -96,7 +96,7 @@ extension Iterable where Self: ~Copyable & ~Escapable { } @available(SwiftStdlib 5.0, *) -extension Iterable where Self: ~Copyable & ~Escapable { +extension BorrowingSequence where Self: ~Copyable & ~Escapable { @inlinable public func borrowingReduce( into initial: consuming Result, @@ -120,7 +120,7 @@ extension Iterable where Self: ~Copyable & ~Escapable { result = try next(result, item) } #else - var it = startBorrowIteration() + var it = makeBorrowingIterator() while true { let span = it.nextSpan() if span.isEmpty { break } diff --git a/Sources/ContainersPreview/Producer.swift b/Sources/ContainersPreview/Protocols/Producer.swift similarity index 89% rename from Sources/ContainersPreview/Producer.swift rename to Sources/ContainersPreview/Protocols/Producer.swift index db4c2230..5ce8ce54 100644 --- a/Sources/ContainersPreview/Producer.swift +++ b/Sources/ContainersPreview/Protocols/Producer.swift @@ -25,6 +25,13 @@ public protocol Producer: ~Copyable, ~Escapable { /// always succeeds. associatedtype ProducerError: Error = Never + /// A value less than or equal to the number of remaining items that this + /// producer is able to generate until it reaches its end. + /// + /// The default implementation returns 0. If you provide your own + /// implementation, make sure to compute the value nondestructively. + var underestimatedCount: Int { get } + /// Generate the next batch of items into the supplied output span instance, /// which must have room for at least one new element. /// @@ -44,6 +51,11 @@ public protocol Producer: ~Copyable, ~Escapable { /// method was able to make progress towards filling `target` without hitting /// the end of the underlying sequence. /// + /// If `target` is a full span, this method is allowed to unconditionally + /// return true. Passing an empty span is not a reliable way to test if the + /// producer has reached its end. (Some producers may only be able to detect + /// that they are finished while trying to generate the next item.) + /// /// ### Error handling /// /// This method throws an error to indicate a failure while trying to generate @@ -73,6 +85,7 @@ public protocol Producer: ~Copyable, ~Escapable { /// the end of the underlying sequence. @_lifetime(target: copy target) @_lifetime(self: copy self) + @discardableResult mutating func generate( into target: inout OutputSpan ) throws(ProducerError) -> Bool @@ -146,6 +159,14 @@ public protocol Producer: ~Copyable, ~Escapable { @available(SwiftStdlib 5.0, *) extension Producer where Self: ~Copyable & ~Escapable { + /// A value less than or equal to the number of remaining items that this + /// producer is able to generate until it reaches its end. + /// + /// The default implementation returns 0. If you provide your own + /// implementation, make sure to compute the value nondestructively. + @inline(__always) + public var underestimatedCount: Int { 0 } + /// Skip at most the given number items in the underlying generative sequence, /// decreasing it by the number of items successfully skipped. /// @@ -231,4 +252,17 @@ extension Producer where Self: ~Copyable & ~Escapable { } } +@available(SwiftStdlib 5.0, *) +extension Producer where Self: ~Copyable & ~Escapable { + /// Returns true if the producer has no more elements, consuming it in + /// the process. This is implemented by checking if it is possible to + /// skip one item. + /// + /// This is useful in preconditions. + public consuming func _isAtEnd() throws(ProducerError) -> Bool { + var c = 1 + return try !skip(upTo: &c) + } +} + #endif diff --git a/Sources/ContainersPreview/Ref.swift b/Sources/ContainersPreview/Types/Borrow.swift similarity index 88% rename from Sources/ContainersPreview/Ref.swift rename to Sources/ContainersPreview/Types/Borrow.swift index e3bfc786..f909262b 100644 --- a/Sources/ContainersPreview/Ref.swift +++ b/Sources/ContainersPreview/Types/Borrow.swift @@ -9,13 +9,13 @@ // //===----------------------------------------------------------------------===// -#if compiler(>=6.2) +#if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW import Builtin @available(SwiftStdlib 5.0, *) @frozen @safe -public struct Ref: Copyable, ~Escapable { +public struct Borrow: Copyable, ~Escapable { @usableFromInline package let _pointer: UnsafePointer @@ -68,7 +68,7 @@ extension Optional where Wrapped: ~Copyable /* FIXME: ~Escapable */ { @available(SwiftStdlib 5.0, *) @_lifetime(borrow self) @_addressableSelf - public func borrow() -> Ref? { + public func borrow() -> Borrow? { if self == nil { return nil } @@ -77,7 +77,7 @@ extension Optional where Wrapped: ~Copyable /* FIXME: ~Escapable */ { Builtin.unprotectedAddressOfBorrow(self) ) - return unsafe Ref(unsafeAddress: pointer, borrowing: self) + return unsafe Borrow(unsafeAddress: pointer, borrowing: self) } } #endif diff --git a/Sources/ContainersPreview/Box.swift b/Sources/ContainersPreview/Types/Box.swift similarity index 91% rename from Sources/ContainersPreview/Box.swift rename to Sources/ContainersPreview/Types/Box.swift index 64f37693..a3099914 100644 --- a/Sources/ContainersPreview/Box.swift +++ b/Sources/ContainersPreview/Types/Box.swift @@ -94,8 +94,8 @@ extension Box where T: ~Copyable { @_alwaysEmitIntoClient @_transparent @_lifetime(immortal) - public consuming func leak() -> Mut { - let result = unsafe Mut(unsafeImmortalAddress: _pointer) + public consuming func leak() -> Inout { + let result = unsafe Inout(unsafeImmortalAddress: _pointer) discard self return result } @@ -107,8 +107,8 @@ extension Box where T: ~Copyable { @_alwaysEmitIntoClient @_transparent @_lifetime(borrow self) - public func borrow() -> Ref { - unsafe Ref(unsafeAddress: UnsafePointer(_pointer), borrowing: self) + public func borrow() -> Borrow { + unsafe Borrow(unsafeAddress: UnsafePointer(_pointer), borrowing: self) } #endif @@ -117,8 +117,8 @@ extension Box where T: ~Copyable { @_alwaysEmitIntoClient @_transparent @_lifetime(&self) - public mutating func mutate() -> Mut { - unsafe Mut(unsafeAddress: _pointer, mutating: &self) + public mutating func mutate() -> Inout { + unsafe Inout(unsafeAddress: _pointer, mutating: &self) } #endif } diff --git a/Sources/ContainersPreview/Mut.swift b/Sources/ContainersPreview/Types/Inout.swift similarity index 79% rename from Sources/ContainersPreview/Mut.swift rename to Sources/ContainersPreview/Types/Inout.swift index fcc57f87..a7526630 100644 --- a/Sources/ContainersPreview/Mut.swift +++ b/Sources/ContainersPreview/Types/Inout.swift @@ -2,23 +2,23 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors +// Copyright (c) 2024 - 2026 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // //===----------------------------------------------------------------------===// -#if compiler(>=6.2) +#if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW import Builtin /// A safe mutable reference allowing in-place mutation to an exclusive value. /// -/// In order to get an instance of a `Mut`, one must have exclusive access +/// In order to get an instance of a `Inout`, one must have exclusive access /// to the instance of `Target`. This is achieved through the 'inout' operator, '&'. @frozen @safe -public struct Mut: ~Copyable, ~Escapable { +public struct Inout: ~Copyable, ~Escapable { @usableFromInline package let _pointer: UnsafeMutablePointer @@ -68,7 +68,7 @@ public struct Mut: ~Copyable, ~Escapa } } -extension Mut where Target: ~Copyable { +extension Inout where Target: ~Copyable { /// Dereferences the mutable reference allowing for in-place reads and writes /// to the underlying instance. @_alwaysEmitIntoClient @@ -79,28 +79,38 @@ extension Mut where Target: ~Copyable { } @_transparent - @_lifetime(self: copy self) unsafeMutableAddress { unsafe _pointer } } } + +extension Inout where Target: ~Copyable { + package func _withUnsafeTarget( + _ body: (inout Target) throws(E) -> R + ) throws(E) -> R { + try body(&_pointer.pointee) + } +} + + extension Optional where Wrapped: ~Copyable /* FIXME: ~Escapable */ { @_lifetime(&self) - public mutating func mutate() -> Mut? { + @_alwaysEmitIntoClient + public mutating func mutate() -> Inout? { if self == nil { return nil } let pointer = unsafe UnsafeMutablePointer( Builtin.unprotectedAddressOf(&self)) - return unsafe Mut(unsafeAddress: pointer, mutating: &self) + return unsafe Inout(unsafeAddress: pointer, mutating: &self) } @_lifetime(&self) @_alwaysEmitIntoClient @_transparent - public mutating func insert(_ value: consuming Wrapped) -> Mut { + public mutating func insert(_ value: consuming Wrapped) -> Inout { self = .some(value) return mutate()._consumingUnsafelyUnwrap() } diff --git a/Sources/ContainersPreview/InputSpan.swift b/Sources/ContainersPreview/Types/InputSpan.swift similarity index 93% rename from Sources/ContainersPreview/InputSpan.swift rename to Sources/ContainersPreview/Types/InputSpan.swift index fdf5a979..9eeaebed 100644 --- a/Sources/ContainersPreview/InputSpan.swift +++ b/Sources/ContainersPreview/Types/InputSpan.swift @@ -75,10 +75,10 @@ extension InputSpan where Element: ~Copyable { @_alwaysEmitIntoClient @_transparent internal func _unsafeAddressOfElement( - unchecked index: Index + uncheckedOffset offset: Index ) -> UnsafeMutablePointer { _unsafeRawAddressOfSlot( - uncheckedOffset: index + uncheckedOffset: offset ).assumingMemoryBound(to: Element.self) } } @@ -244,13 +244,13 @@ extension InputSpan where Element: ~Copyable { public subscript(_ index: Index) -> Element { unsafeAddress { precondition(indices.contains(index), "Index out of bounds") - return unsafe UnsafePointer(_unsafeAddressOfElement(unchecked: index)) + return unsafe UnsafePointer(_unsafeAddressOfElement(uncheckedOffset: index)) } @_lifetime(self: copy self) unsafeMutableAddress { precondition(indices.contains(index), "Index out of bounds") - return unsafe _unsafeAddressOfElement(unchecked: index) + return unsafe _unsafeAddressOfElement(uncheckedOffset: index) } } @@ -265,11 +265,11 @@ extension InputSpan where Element: ~Copyable { @_alwaysEmitIntoClient public subscript(unchecked index: Index) -> Element { unsafeAddress { - unsafe UnsafePointer(_unsafeAddressOfElement(unchecked: index)) + unsafe UnsafePointer(_unsafeAddressOfElement(uncheckedOffset: index)) } @_lifetime(self: copy self) unsafeMutableAddress { - unsafe _unsafeAddressOfElement(unchecked: index) + unsafe _unsafeAddressOfElement(uncheckedOffset: index) } } @@ -296,8 +296,8 @@ extension InputSpan where Element: ~Copyable { @_lifetime(self: copy self) public mutating func swapAt(unchecked i: Index, unchecked j: Index) { guard i != j else { return } - let pi = unsafe _unsafeAddressOfElement(unchecked: i) - let pj = unsafe _unsafeAddressOfElement(unchecked: j) + let pi = unsafe _unsafeAddressOfElement(uncheckedOffset: i) + let pj = unsafe _unsafeAddressOfElement(uncheckedOffset: j) let temporary = unsafe pi.move() unsafe pi.initialize(to: pj.move()) unsafe pj.initialize(to: consume temporary) @@ -325,7 +325,7 @@ extension InputSpan where Element: ~Copyable { public mutating func removeFirst() -> Element { precondition(_count > 0, "InputSpan underflow") defer { _count &-= 1 } - return _unsafeAddressOfElement(unchecked: 0).move() + return _unsafeAddressOfElement(uncheckedOffset: 0).move() } /// Remove the last N elements of this span, returning the memory they occupy @@ -354,7 +354,7 @@ extension InputSpan where Element: ~Copyable { @inlinable public mutating func popFirst() -> Element? { guard _count > 0 else { return nil } - let result = unsafe _unsafeAddressOfElement(unchecked: 0).move() + let result = unsafe _unsafeAddressOfElement(uncheckedOffset: 0).move() _count &-= 1 return result } @@ -481,6 +481,26 @@ extension InputSpan where Element: ~Copyable { } } +@available(SwiftStdlib 5.0, *) +extension InputSpan where Element: ~Copyable { + @_alwaysEmitIntoClient + @_lifetime(&self) + public mutating func consumePrefix(upTo n: Int) -> InputSpan { + precondition(n >= 0, "Cannot consume a negative number of elements") + let c = Swift.min(n, self.count) + + let buffer = unsafe _unsafeRawAddressOfSlot( + uncheckedOffset: 0 + ).withMemoryRebound(to: Element.self, capacity: c) { start in + UnsafeMutableBufferPointer(start: start, count: c) + } + _count -= c + return _overrideLifetime( + InputSpan(buffer: buffer, initializedCount: c), + mutating: &self) + } +} + @available(SwiftStdlib 5.0, *) internal func withTemporaryInputSpan( of type: Element.Type, diff --git a/Sources/ContainersPreview/Shared.swift b/Sources/ContainersPreview/Types/Shared.swift similarity index 100% rename from Sources/ContainersPreview/Shared.swift rename to Sources/ContainersPreview/Types/Shared.swift diff --git a/Tests/_CollectionsTestSupport/AssertionContexts/Assertions+Containers.swift b/Tests/_CollectionsTestSupport/AssertionContexts/Assertions+Containers.swift index 372dca21..47741132 100644 --- a/Tests/_CollectionsTestSupport/AssertionContexts/Assertions+Containers.swift +++ b/Tests/_CollectionsTestSupport/AssertionContexts/Assertions+Containers.swift @@ -123,12 +123,12 @@ public func expectIterableContents< #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW @available(SwiftStdlib 5.0, *) public func expectIterablesWithEquivalentElements< - I1: Iterable & ~Copyable & ~Escapable, - I2: Iterable & ~Copyable & ~Escapable + I1: BorrowingSequence & ~Copyable & ~Escapable, + I2: BorrowingSequence & ~Copyable & ~Escapable >( - _ left: borrowing I1, - _ right: borrowing I2, - by areEquivalent: (borrowing I1.Element, borrowing I2.Element) -> Bool, + _ left: borrowing S1, + _ right: borrowing S2, + by areEquivalent: (borrowing S1.Element, borrowing S2.Element) -> Bool, _ message: @autoclosure () -> String = "", trapping: Bool = false, file: StaticString = #filePath, @@ -144,11 +144,11 @@ public func expectIterablesWithEquivalentElements< @available(SwiftStdlib 5.0, *) public func expectIterablesWithEqualElements< Element: Equatable, - I1: Iterable & ~Copyable & ~Escapable, - I2: Iterable & ~Copyable & ~Escapable, + I1: BorrowingSequence & ~Copyable & ~Escapable, + I2: BorrowingSequence & ~Copyable & ~Escapable, >( - _ left: borrowing I1, - _ right: borrowing I2, + _ left: borrowing S1, + _ right: borrowing S2, _ message: @autoclosure () -> String = "", trapping: Bool = false, file: StaticString = #filePath, @@ -164,17 +164,17 @@ public func expectIterablesWithEqualElements< @available(SwiftStdlib 5.0, *) public func expectIterableContents< Element: Equatable, - I1: Iterable & ~Copyable & ~Escapable, + I1: BorrowingSequence & ~Copyable & ~Escapable, C2: Collection, >( - _ left: borrowing I1, + _ left: borrowing S1, equalTo right: C2, _ message: @autoclosure () -> String = "", trapping: Bool = false, file: StaticString = #filePath, line: UInt = #line ) { - var it1 = left.startBorrowIteration() + var it1 = left.makeBorrowingIterator() var it2 = right.makeIterator() while true { let span = it1.nextSpan() @@ -205,19 +205,19 @@ public func expectIterableContents< /// Check if `left` and `right` contain equal elements in the same order. @available(SwiftStdlib 5.0, *) public func expectIterableContents< - I1: Iterable & ~Copyable & ~Escapable, + I1: BorrowingSequence & ~Copyable & ~Escapable, C2: Collection, >( - _ left: borrowing I1, + _ left: borrowing S1, equivalentTo right: C2, - by areEquivalent: (borrowing I1.Element, C2.Element) -> Bool, - printer: (borrowing I1.Element) -> String, + by areEquivalent: (borrowing S1.Element, C2.Element) -> Bool, + printer: (borrowing S1.Element) -> String, _ message: @autoclosure () -> String = "", trapping: Bool = false, file: StaticString = #filePath, line: UInt = #line ) { - var it1 = left.startBorrowIteration() + var it1 = left.makeBorrowingIterator() var it2 = right.makeIterator() var offset = 0 while true { diff --git a/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift b/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift index a18e6d66..4280134f 100644 --- a/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift +++ b/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift @@ -16,10 +16,10 @@ import ContainersPreview @available(SwiftStdlib 5.0, *) @inlinable public func checkIterable< - I: Iterable & ~Copyable & ~Escapable, + S: BorrowingSequence & ~Copyable & ~Escapable, Expected: Sequence >( - _ iterable: borrowing I, + _ iterable: borrowing S, expectedContents: Expected, file: StaticString = #filePath, line: UInt = #line @@ -34,10 +34,10 @@ public func checkIterable< @available(SwiftStdlib 5.0, *) @inlinable public func checkIterable< - I: Iterable & ~Copyable & ~Escapable, + S: BorrowingSequence & ~Copyable & ~Escapable, Expected: Sequence >( - _ iterable: borrowing I, + _ iterable: borrowing S, expectedContents: Expected, by areEquivalent: (I.Element, I.Element) -> Bool, file: StaticString = #filePath, @@ -64,7 +64,7 @@ public func checkIterable< let spanShapes: [Range] = { var r: [Range] = [] var pos = 0 - var it = iterable.startBorrowIteration() + var it = iterable.makeBorrowingIterator() while true { let origPos = pos let span = it.nextSpan() @@ -83,7 +83,7 @@ public func checkIterable< // Check that the spans have stable sizes and the expected contents. do { var pos = 0 - var it = iterable.startBorrowIteration() + var it = iterable.makeBorrowingIterator() var spanIndex = 0 while true { let span = it.nextSpan() @@ -104,7 +104,7 @@ public func checkIterable< // Check that we can iterate one by one. do { var pos = 0 - var it = iterable.startBorrowIteration() + var it = iterable.makeBorrowingIterator() while true { let span = it.nextSpan(maximumCount: 1) if span.isEmpty { break } @@ -120,7 +120,7 @@ public func checkIterable< // Check that we can iterate with huge maximum counts do { var pos = 0 - var it = iterable.startBorrowIteration() + var it = iterable.makeBorrowingIterator() var spanIndex = 0 while true { let span = it.nextSpan(maximumCount: Int.max) diff --git a/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift b/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift index 068b47f3..6e220149 100644 --- a/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift +++ b/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift @@ -36,7 +36,7 @@ public struct StaccatoContainer: ~Copyable { } @available(SwiftStdlib 5.0, *) -public struct _StaccatoBorrowIterator: BorrowIteratorProtocol, ~Escapable { +public struct _StaccatoBorrowingIterator: BorrowingIteratorProtocol, ~Escapable { internal let _contents: Span internal let _spanCounts: [Int] internal let _modulus: Int @@ -78,12 +78,12 @@ public struct _StaccatoBorrowIterator: BorrowIteratorProtoco @available(SwiftStdlib 5.0, *) extension StaccatoContainer: Container where Element: ~Copyable { - public typealias BorrowIterator = _StaccatoBorrowIterator // FIXME rdar://150240032 + public typealias BorrowingIterator = _StaccatoBorrowingIterator // FIXME rdar://150240032 public var isEmpty: Bool { _contents.isEmpty } public var count: Int { _contents.count } - public func startBorrowIteration() -> BorrowIterator { - BorrowIterator(contents: _contents.span, spanCounts: _spanCounts) + public func makeBorrowingIterator() -> BorrowingIterator { + BorrowingIterator(contents: _contents.span, spanCounts: _spanCounts) } } #endif