Add draft version of borrowable Container protocol

This commit is contained in:
Karoy Lorentey committed 2025-09-26 18:40:00 -07:00
1 parent 155a8a010e
commit 2ae7f11ecf
8 files changed
+461 -245

No files matched your search

+6 -2
View File
@@ -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",
+5 -1
View File
@@ -214,7 +214,11 @@ let targets: [CustomTarget] = [
.target(
kind: .testSupport,
name: "_CollectionsTestSupport",
dependencies: ["InternalCollectionsUtilities", "ContainersPreview"]),
dependencies: [
"InternalCollectionsUtilities",
"ContainersPreview",
"BasicContainers",
]),
.target(
kind: .test,
name: "CollectionsTestSupportTests",
@@ -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<Element>: ~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<Element>
@_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<Element> {
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<Element> {
let c = maximumCount ?? self.count
let result = self.extracting(first: c)
self = self.extracting(droppingFirst: c)
return result
}
}
#endif
@@ -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<Element>
) -> 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<Element>, Span<Other.Element>) 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<Element> & ~Copyable & ~Escapable
>(
_ other: borrowing Other,
) -> Bool {
self.borrowingElementsEqual(other, by: ==)
}
}
#endif
+87
View File
@@ -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<Element>: ~Copyable, ~Escapable {
associatedtype Element: ~Copyable /*& ~Escapable*/
associatedtype BorrowIterator: BorrowIteratorProtocol<Element> & ~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<E: Error>(
_ 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<Result: ~Copyable, E: Error>(
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<Result: ~Copyable, E: Error>(
_ 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
@@ -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<Element> & ~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<Element> & ~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)
@@ -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<Int>, indexRange: Range<C.Index>)] = {
var r: [(offsetRange: Range<Int>, indexRange: Range<C.Index>)] = []
let spanShapes: [Range<Int>] = {
var r: [Range<Int>] = []
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
@@ -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<Element: ~Copyable>: ~Copyable {
internal let _contents: RigidArray<Element>
internal let _spanCounts: [Int]
@@ -32,20 +34,21 @@ public struct StaccatoContainer<Element: ~Copyable>: ~Copyable {
}
}
public struct _StaccatoContainerIndex: Comparable {
@available(SwiftStdlib 5.0, *)
public struct _StaccatoBorrowIterator<Element: ~Copyable>: BorrowIteratorProtocol, ~Escapable {
internal let _contents: Span<Element>
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<Element>, 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<Element> {
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<Element> // 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<Element> {
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<Element> {
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