mirror of
https://github.com/apple/swift-collections
synced 2026-11-29 05:14:20 +00:00
MutableContainer: Add tests; resolve issues uncovered
This commit is contained in:
20 files changed
+1037
-86
No files matched your search
@@ -46,6 +46,7 @@ target_sources(${module_name} PRIVATE
|
||||
"Protocols/Container/DrainableContainer.swift"
|
||||
"Protocols/Container/DynamicContainer.swift"
|
||||
"Protocols/Container/MutableContainer.swift"
|
||||
"Protocols/Container/MutableContainer+UpdateSubrange.swift"
|
||||
"Protocols/Container/PermutableContainer.swift"
|
||||
"Protocols/Container/PermutableContainer+HeapSort.swift"
|
||||
"Protocols/Container/PermutableContainer+MoveSubrange.swift"
|
||||
|
||||
+52
-49
@@ -45,40 +45,43 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable
|
||||
) throws(Failure) where Source.Element: ~Copyable {
|
||||
// We cannot do in-place bulk updates, because we wouldn't be able to
|
||||
// gracefully recover from a producer failure.
|
||||
// See the `Failure == Never` refinement below for the faster (& far more
|
||||
// convenient) in-place variant.
|
||||
|
||||
// `offset` is the offset of the next item to update in the mutable span
|
||||
// that starts at `index`. The loop invariant is that this remains zero;
|
||||
// however, when `source` terminates before we reach the end of the
|
||||
// container, then this can be left with some positive value that we must
|
||||
// use to advance `index` before returning -- so that we properly indicate
|
||||
// how far we updated elements in `self`.
|
||||
var offset = 0
|
||||
defer {
|
||||
if offset > 0 {
|
||||
index = self.index(index, offsetBy: offset)
|
||||
// See the `CountedProducer<Element, Never>` refinement below for the faster
|
||||
// in-place variant.
|
||||
try withTemporaryAllocation(
|
||||
of: Element.self, capacity: _producerBufferSize
|
||||
) { scratch throws(Failure) in
|
||||
// `offset` is the offset of the next item to update in the mutable span
|
||||
// that starts at `index`. The loop invariant is that this remains zero;
|
||||
// however, when `source` terminates before we reach the end of the
|
||||
// container, then this can be left with some positive value that we must
|
||||
// use to advance `index` before returning -- so that we properly indicate
|
||||
// how far we updated elements in `self`.
|
||||
var offset = 0
|
||||
defer {
|
||||
if offset > 0 {
|
||||
index = self.index(index, offsetBy: offset)
|
||||
}
|
||||
}
|
||||
}
|
||||
while offset == 0 {
|
||||
var next = index
|
||||
var dst = self.nextMutableSpan(after: &next)
|
||||
guard !dst.isEmpty else { break }
|
||||
try withTemporaryAllocation(
|
||||
of: Element.self,
|
||||
capacity: Swift.min(_producerBufferSize, dst.count)
|
||||
) { buf throws(Failure) in
|
||||
while offset == 0 {
|
||||
var next = index
|
||||
var dst = self.nextMutableSpan(after: &next)
|
||||
guard !dst.isEmpty else { break }
|
||||
while offset < dst.count {
|
||||
defer {
|
||||
if !buf.isEmpty {
|
||||
// We need to updating all items that were successfully generated,
|
||||
if !scratch.isEmpty {
|
||||
// We need to update all items that were successfully generated,
|
||||
// whether or not we've run into failure/eof.
|
||||
let j = offset &+ buf.count
|
||||
dst._updateSubrange(Range(uncheckedBounds: (offset, j)), moving: &buf)
|
||||
let j = offset &+ scratch.count
|
||||
dst._updateSubrange(
|
||||
Range(uncheckedBounds: (offset, j)),
|
||||
moving: &scratch)
|
||||
offset = j
|
||||
}
|
||||
}
|
||||
guard try source.fill(&buf) else { return }
|
||||
let r = try scratch._append(
|
||||
addingCount: Swift.min(dst.count &- offset, scratch.freeCapacity)
|
||||
) { src throws(Failure) in try source.fill(&src) }
|
||||
guard r else { return }
|
||||
}
|
||||
index = next
|
||||
offset = 0
|
||||
@@ -100,12 +103,9 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable
|
||||
var target = self.nextMutableSpan(after: &index, maxCount: remaining)
|
||||
guard !target.isEmpty else { break }
|
||||
remaining -= target.count
|
||||
target.withUnsafeMutableBufferPointer { buf in
|
||||
buf.deinitialize()
|
||||
var dst = OutputSpan(buffer: buf, initializedCount: 0)
|
||||
target._edit { dst in
|
||||
dst.removeAll()
|
||||
source.fill(&dst)
|
||||
let c = dst.finalize(for: buf)
|
||||
precondition(c == buf.count, "Invalid CountedProducer")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -117,6 +117,8 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable
|
||||
_ subrange: Range<Index>,
|
||||
from source: consuming Source
|
||||
) where Source.Element: ~Copyable {
|
||||
// With a CountedProducer that doesn't throw, we can implement
|
||||
// bulk updating in place.
|
||||
var remaining = source.count
|
||||
var i = subrange.lowerBound
|
||||
while remaining > 0 {
|
||||
@@ -126,17 +128,19 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable
|
||||
limitedBy: subrange.upperBound)
|
||||
guard !target.isEmpty else { break }
|
||||
remaining -= target.count
|
||||
target.withUnsafeMutableBufferPointer { buf in
|
||||
buf.deinitialize()
|
||||
var dst = OutputSpan(buffer: buf, initializedCount: 0)
|
||||
target._edit { dst in
|
||||
// Note: we cannot throw here while `dst` isn't full -- this is why
|
||||
// `Source` is required not to throw. (We have
|
||||
// `updateElements(after:from:)` to support the throwing case, but at
|
||||
// the cost of slower operation and a far more unwieldy interface.)
|
||||
dst.removeAll()
|
||||
source.fill(&dst)
|
||||
let c = dst.finalize(for: buf)
|
||||
precondition(c == buf.count, "Invalid CountedProducer")
|
||||
precondition(dst.isFull, "Invalid CountedProducer")
|
||||
}
|
||||
precondition(
|
||||
remaining == 0 && i == subrange.upperBound,
|
||||
"updateSubrange source length does not match target range")
|
||||
}
|
||||
precondition(
|
||||
remaining == 0 && i == subrange.upperBound,
|
||||
"updateSubrange source length does not match target range")
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@@ -149,7 +153,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable
|
||||
var dst = self.nextMutableSpan(after: &i, limitedBy: subrange.upperBound)
|
||||
var j = 0
|
||||
guard !dst.isEmpty else { break }
|
||||
repeat {
|
||||
while j < dst.count {
|
||||
var src = source.drainNext(maxCount: dst.count &- j)
|
||||
precondition(
|
||||
!src.isEmpty,
|
||||
@@ -157,7 +161,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable
|
||||
let k = j &+ src.count
|
||||
dst._updateSubrange(Range(uncheckedBounds: (j, k)), moving: &src)
|
||||
j = k
|
||||
} while !dst.isEmpty
|
||||
}
|
||||
}
|
||||
precondition(i == subrange.upperBound, "Invalid MutableContainer")
|
||||
source._expectEnd("updateSubrange source length does not match target range")
|
||||
@@ -188,12 +192,11 @@ where Self: ~Copyable & ~Escapable, Element: Copyable
|
||||
}
|
||||
}
|
||||
while offset < dst.count {
|
||||
let src = try source.nextSpan(maxCount: dst.count)
|
||||
let src = try source.nextSpan(maxCount: dst.count &- offset)
|
||||
if src.isEmpty { break outer }
|
||||
dst._updateSubrange(
|
||||
Range(uncheckedBounds: (offset, offset + src.count)),
|
||||
copying: src)
|
||||
|
||||
let range = Range(uncheckedBounds: (offset, offset &+ src.count))
|
||||
dst._updateSubrange(range, copying: src)
|
||||
offset = range.upperBound
|
||||
}
|
||||
index = next
|
||||
offset = 0
|
||||
@@ -203,7 +206,7 @@ where Self: ~Copyable & ~Escapable, Element: Copyable
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func updateSubrange(
|
||||
_ subrange: Range<Index>,
|
||||
from source: borrowing some Container<Element> & ~Copyable & ~Escapable
|
||||
copying source: borrowing some Container<Element> & ~Copyable & ~Escapable
|
||||
) {
|
||||
var it = source.makeBorrowingIterator()
|
||||
var index = subrange.lowerBound
|
||||
@@ -212,7 +215,7 @@ where Self: ~Copyable & ~Escapable, Element: Copyable
|
||||
guard !dst.isEmpty else { break }
|
||||
var offset = 0
|
||||
while offset < dst.count {
|
||||
let src = it.nextSpan(maxCount: dst.count)
|
||||
let src = it.nextSpan(maxCount: dst.count &- offset)
|
||||
precondition(!src.isEmpty, "updateSubrange source length does not match target range")
|
||||
let end = offset + src.count
|
||||
dst._updateSubrange(Range(uncheckedBounds: (offset, end)), copying: src)
|
||||
|
||||
@@ -46,6 +46,7 @@ target_sources(${module_name} PRIVATE
|
||||
"RigidDeque/RigidDeque+Append.swift"
|
||||
"RigidDeque/RigidDeque+Consumption.swift"
|
||||
"RigidDeque/RigidDeque+ContainerOperations.swift"
|
||||
"RigidDeque/RigidDeque+Deprecations.swift"
|
||||
"RigidDeque/RigidDeque+Descriptions.swift"
|
||||
"RigidDeque/RigidDeque+Equatable.swift"
|
||||
"RigidDeque/RigidDeque+Hashable.swift"
|
||||
@@ -60,7 +61,7 @@ target_sources(${module_name} PRIVATE
|
||||
"UniqueDeque/UniqueDeque+Append.swift"
|
||||
"UniqueDeque/UniqueDeque+Consumption.swift"
|
||||
"UniqueDeque/UniqueDeque+ContainerOperations.swift"
|
||||
"UniqueDeque/UniqueDeque+Deprecated.swift"
|
||||
"UniqueDeque/UniqueDeque+Deprecations.swift"
|
||||
"UniqueDeque/UniqueDeque+Descriptions.swift"
|
||||
"UniqueDeque/UniqueDeque+Equatable.swift"
|
||||
"UniqueDeque/UniqueDeque+Hashable.swift"
|
||||
|
||||
File renamed without changes.
@@ -39,6 +39,7 @@ target_sources(${module_name} PRIVATE
|
||||
"Iterable+CopyContents.swift"
|
||||
"Iterable+Equality.swift"
|
||||
"LifetimeOverride.swift"
|
||||
"MutableSpan+Extras.swift"
|
||||
"MutableRef.swift"
|
||||
"Optional+Extras.swift"
|
||||
"OutputSpan+Extras.swift"
|
||||
|
||||
@@ -13,27 +13,59 @@
|
||||
|
||||
#if compiler(>=6.2)
|
||||
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
extension MutableSpan where Element: ~Copyable {
|
||||
// FIXME: Replace with stdlib implementation when it becomes available
|
||||
@_alwaysEmitIntoClient
|
||||
@_lifetime(self: copy self)
|
||||
package mutating func _edit<E: Error, R: ~Copyable>(
|
||||
_ body: (inout OutputSpan<Element>) throws(E) -> R
|
||||
) throws(E) -> R {
|
||||
// Note: while `body` is allowed to throw, it must always leave
|
||||
// the output span fully populated, even if it ends up doing that.
|
||||
try self.withUnsafeMutableBufferPointer { buf throws(E) in
|
||||
var span = unsafe OutputSpan(buffer: buf, initializedCount: buf.count)
|
||||
defer {
|
||||
let c = unsafe span.finalize(for: buf)
|
||||
span = OutputSpan()
|
||||
precondition(c == buf.count, "MutableSpan.edit must not change the size of the span")
|
||||
}
|
||||
return try body(&span)
|
||||
}
|
||||
}
|
||||
|
||||
// FIXME: Replace with stdlib implementation when it becomes available
|
||||
// (See also InputSpan-taking variant in SpanPreview)
|
||||
@_alwaysEmitIntoClient
|
||||
@_lifetime(self: copy self)
|
||||
package mutating func _updateSubrange(
|
||||
_ subrange: Range<Index>,
|
||||
moving source: inout OutputSpan<Element>
|
||||
) {
|
||||
precondition(
|
||||
subrange.lowerBound >= 0 && subrange.upperBound <= count,
|
||||
subrange.lowerBound >= 0 && subrange.upperBound <= self.count,
|
||||
"Index range out of bounds")
|
||||
precondition(
|
||||
subrange.count == source.count,
|
||||
"updateSubrange source count doesn't match target")
|
||||
guard !subrange.isEmpty else { return }
|
||||
self.withUnsafeMutableBufferPointer { dst in
|
||||
source.withUnsafeMutableBufferPointer { src, c in
|
||||
// FIXME: Make sure this calls memcpy when Element is bitwise movable.
|
||||
#if false // FIXME: UMBP.moveUpdate(fromContentsOf:) is broken as of 2026-09-17 (rdar://187733648)
|
||||
let i = dst
|
||||
.extracting(unchecked: subrange)
|
||||
.moveUpdate(fromContentsOf: src.extracting(first: c))
|
||||
._extracting(unchecked: subrange)
|
||||
.moveUpdate(fromContentsOf: src._extracting(first: c))
|
||||
precondition(i == subrange.count)
|
||||
#else
|
||||
var d = dst._ptr(at: subrange.lowerBound)
|
||||
var s = src._ptr(at: 0)
|
||||
for i in 0 ..< c {
|
||||
d.pointee = s.move()
|
||||
d += 1
|
||||
s += 1
|
||||
}
|
||||
#endif
|
||||
c = 0
|
||||
}
|
||||
}
|
||||
@@ -42,6 +74,7 @@ extension MutableSpan where Element: ~Copyable {
|
||||
// FIXME: Replace with stdlib implementation when it becomes available
|
||||
// (See also InputSpan-taking variant in SpanPreview)
|
||||
@_alwaysEmitIntoClient
|
||||
@_lifetime(self: copy self)
|
||||
package mutating func _updateAll(
|
||||
moving source: inout OutputSpan<Element>
|
||||
) {
|
||||
@@ -49,19 +82,33 @@ extension MutableSpan where Element: ~Copyable {
|
||||
precondition(
|
||||
source.count == count,
|
||||
"updateSubrange source count doesn't match target")
|
||||
guard !self.isEmpty else { return }
|
||||
self.withUnsafeMutableBufferPointer { dst in
|
||||
source.withUnsafeMutableBufferPointer { src, c in
|
||||
// FIXME: Make sure this calls memcpy when Element is bitwise movable.
|
||||
let i = dst.moveUpdate(fromContentsOf: src.extracting(first: c))
|
||||
#if false // FIXME: UMBP.moveUpdate(fromContentsOf:) is broken as of 2026-09-17 (rdar://187733648)
|
||||
let i = dst.moveUpdate(fromContentsOf: src._extracting(first: c))
|
||||
assert(i == count)
|
||||
#else
|
||||
var d = dst._ptr(at: 0)
|
||||
var s = src._ptr(at: 0)
|
||||
for i in 0 ..< c {
|
||||
d.pointee = s.move()
|
||||
d += 1
|
||||
s += 1
|
||||
}
|
||||
#endif
|
||||
c = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
extension MutableSpan /* where Element: Copyable */ {
|
||||
// FIXME: Replace with stdlib implementation when it becomes available
|
||||
@_alwaysEmitIntoClient
|
||||
@_lifetime(self: copy self)
|
||||
package mutating func _updateSubrange(
|
||||
_ subrange: Range<Index>,
|
||||
copying source: borrowing Span<Element>
|
||||
@@ -75,7 +122,7 @@ extension MutableSpan /* where Element: Copyable */ {
|
||||
self.withUnsafeMutableBufferPointer { dst in
|
||||
source.withUnsafeBufferPointer { src in
|
||||
// FIXME: Make sure this calls memcpy when Element is BitwiseCopyable.
|
||||
let i = dst.extracting(unchecked: subrange).update(fromContentsOf: src)
|
||||
let i = dst._extracting(unchecked: subrange).update(fromContentsOf: src)
|
||||
precondition(i == subrange.count)
|
||||
}
|
||||
}
|
||||
@@ -83,6 +130,7 @@ extension MutableSpan /* where Element: Copyable */ {
|
||||
|
||||
// FIXME: Replace with stdlib implementation when it becomes available
|
||||
@_alwaysEmitIntoClient
|
||||
@_lifetime(self: copy self)
|
||||
package mutating func _updateAll(
|
||||
copying source: borrowing Span<Element>
|
||||
) {
|
||||
|
||||
@@ -115,6 +115,7 @@ extension OutputSpan where Element: ~Copyable {
|
||||
from index: Int,
|
||||
where shouldBeRemoved: (borrowing Element) -> Bool
|
||||
) {
|
||||
// FIXME: This needs to be in the stdlib.
|
||||
precondition(index >= 0 && index <= count, "Index out of bounds")
|
||||
self.withUnsafeMutableBufferPointer { buffer, count in
|
||||
var i = index
|
||||
@@ -137,5 +138,36 @@ extension OutputSpan where Element: ~Copyable {
|
||||
}
|
||||
}
|
||||
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
extension OutputSpan where Element: ~Copyable {
|
||||
@_alwaysEmitIntoClient
|
||||
@discardableResult
|
||||
@_lifetime(self: copy self)
|
||||
package mutating func _append<E: Error, R: ~Copyable>(
|
||||
addingCount newItemCount: Int,
|
||||
initializingWith initializer: (inout OutputSpan<Element>) throws(E) -> R
|
||||
) throws(E) -> R {
|
||||
// FIXME: This needs to be in the stdlib.
|
||||
// Note: This is the wrong shape for append, as it doesn't generalize
|
||||
// to piecewise contiguous containers and doesn't return indices.
|
||||
// However, it feels like we need to _also_ provide a simple append
|
||||
// implementation for flat containers, as the ability return things out of
|
||||
// the closure is quite important for usability. We can't name them both
|
||||
// `append(addingCount:initializingWith:)` though!
|
||||
precondition(newItemCount >= 0, "Cannot add a negative number of items")
|
||||
return try withUnsafeMutableBufferPointer { buf, c throws(E) in
|
||||
precondition(newItemCount <= buf.count - c, "OutputSpan capacity overflow")
|
||||
let dst = buf._extracting(unchecked: Range(
|
||||
uncheckedBounds: (c, c &+ newItemCount)))
|
||||
var span = OutputSpan(buffer: dst, initializedCount: 0)
|
||||
defer {
|
||||
c &+= span.finalize(for: dst)
|
||||
span = OutputSpan()
|
||||
}
|
||||
return try initializer(&span)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
@@ -25,4 +25,5 @@ endif()
|
||||
|
||||
target_sources(${module_name} PRIVATE
|
||||
"InputSpan.swift"
|
||||
"MutableSpan+InputSpanHelpers.swift"
|
||||
"OutputSpan+InputSpanHelpers.swift")
|
||||
@@ -11,10 +11,17 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#if compiler(>=6.2) && UnstableContainersPreview
|
||||
#if !COLLECTIONS_SINGLE_MODULE
|
||||
import InternalCollectionsUtilities
|
||||
#endif
|
||||
|
||||
#if compiler(>=6.4) && UnstableContainersPreview
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
extension MutableSpan where Element: ~Copyable {
|
||||
// FIXME: Replace with stdlib implementation when it becomes available
|
||||
@_alwaysEmitIntoClient
|
||||
@_lifetime(self: copy self)
|
||||
@_lifetime(source: copy source)
|
||||
package mutating func _updateSubrange(
|
||||
_ subrange: Range<Index>,
|
||||
moving source: inout InputSpan<Element>
|
||||
@@ -25,13 +32,24 @@ extension MutableSpan where Element: ~Copyable {
|
||||
precondition(
|
||||
subrange.count == source.count,
|
||||
"updateSubrange source count doesn't match target")
|
||||
guard !subrange.isEmpty else { return }
|
||||
self.withUnsafeMutableBufferPointer { dst in
|
||||
source.withUnsafeMutableBufferPointer { src, c in
|
||||
// FIXME: Make sure this calls memcpy when Element is bitwise movable.
|
||||
#if false // FIXME: UMBP.moveUpdate(fromContentsOf:) is broken as of 2026-09-17 (rdar://187733648)
|
||||
let i = dst
|
||||
.extracting(unchecked: subrange)
|
||||
.moveUpdate(fromContentsOf: src.extracting(last: c))
|
||||
._extracting(unchecked: subrange)
|
||||
.moveUpdate(fromContentsOf: src._extracting(last: c))
|
||||
precondition(i == subrange.count)
|
||||
#else
|
||||
var d = dst._ptr(at: subrange.lowerBound)
|
||||
var s = src._ptr(at: src.count - c)
|
||||
for i in 0 ..< c {
|
||||
d.pointee = s.move()
|
||||
d += 1
|
||||
s += 1
|
||||
}
|
||||
#endif
|
||||
c = 0
|
||||
}
|
||||
}
|
||||
@@ -39,6 +57,8 @@ extension MutableSpan where Element: ~Copyable {
|
||||
|
||||
// FIXME: Replace with stdlib implementation when it becomes available
|
||||
@_alwaysEmitIntoClient
|
||||
@_lifetime(self: copy self)
|
||||
@_lifetime(source: copy source)
|
||||
package mutating func _updateAll(
|
||||
moving source: inout InputSpan<Element>
|
||||
) {
|
||||
@@ -46,11 +66,22 @@ extension MutableSpan where Element: ~Copyable {
|
||||
precondition(
|
||||
source.count == count,
|
||||
"updateSubrange source count doesn't match target")
|
||||
guard !self.isEmpty else { return }
|
||||
self.withUnsafeMutableBufferPointer { dst in
|
||||
source.withUnsafeMutableBufferPointer { src, c in
|
||||
// FIXME: Make sure this calls memcpy when Element is bitwise movable.
|
||||
let i = dst.moveUpdate(fromContentsOf: src.extracting(last: c))
|
||||
#if false // FIXME: UMBP.moveUpdate(fromContentsOf:) is broken as of 2026-09-17 (rdar://187733648)
|
||||
let i = dst.moveUpdate(fromContentsOf: src._extracting(last: c))
|
||||
assert(i == count)
|
||||
#else
|
||||
var d = dst._ptr(at: 0)
|
||||
var s = src._ptr(at: src.count - c)
|
||||
for i in 0 ..< c {
|
||||
d.pointee = s.move()
|
||||
d += 1
|
||||
s += 1
|
||||
}
|
||||
#endif
|
||||
c = 0
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,10 +18,10 @@ import InternalCollectionsUtilities
|
||||
#if compiler(>=6.2) && UnstableContainersPreview
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
extension OutputSpan where Element: ~Copyable {
|
||||
@_lifetime(source: copy source)
|
||||
@inlinable
|
||||
@inline(__always)
|
||||
@_lifetime(self: copy self)
|
||||
@_lifetime(source: copy source)
|
||||
package mutating func _append(moving source: inout InputSpan<Element>) {
|
||||
// FIXME: This needs to be in the stdlib.
|
||||
source.withUnsafeMutableBufferPointer { src, srcCount in
|
||||
|
||||
@@ -396,14 +396,12 @@ class RigidSetTests: CollectionTestCase {
|
||||
withLifetimeTracking { tracker in
|
||||
var s = RigidSet<LifetimeTracked<Int>>(capacity: capacity)
|
||||
|
||||
var i = 0
|
||||
var p = CustomProducer<LifetimeTracked<Int>, Never>(
|
||||
underestimatedCount: 0,
|
||||
chunkSize: chunkSize
|
||||
) {
|
||||
guard i < count else { return nil }
|
||||
defer { i += 1 }
|
||||
return tracker.instance(for: i)
|
||||
) { offset in
|
||||
guard offset < count else { return nil }
|
||||
return tracker.instance(for: offset)
|
||||
}
|
||||
s.insert(from: &p)
|
||||
expectConsistentSet(s)
|
||||
|
||||
@@ -0,0 +1,329 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Collections open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
|
||||
#if COLLECTIONS_SINGLE_MODULE
|
||||
import Collections
|
||||
#else
|
||||
import _CollectionsTestSupport
|
||||
import SpanPreview
|
||||
import ContainersPreview
|
||||
import InternalCollectionsUtilities
|
||||
import BasicContainers
|
||||
import DequeModule
|
||||
#endif
|
||||
|
||||
#if compiler(>=6.4) && UnstableContainersPreview
|
||||
#if !COLLECTIONS_SINGLE_MODULE
|
||||
// For testing piecewise contiguous MutableContainer operations.
|
||||
// (FIXME: Use something like an extended StaccatoContainer instead.)
|
||||
struct DequeLayout: Hashable, CustomStringConvertible {
|
||||
let capacity: Int
|
||||
let startSlot: Int
|
||||
let count: Int
|
||||
let startValue: Int
|
||||
|
||||
init(capacity: Int, startSlot: Int, count: Int, startValue: Int = 0) {
|
||||
self.capacity = capacity
|
||||
self.startSlot = startSlot
|
||||
self.count = count
|
||||
self.startValue = startValue
|
||||
}
|
||||
|
||||
var freeCapacity: Int { capacity - count }
|
||||
var valueRange: Range<Int> { startValue ..< startValue + count }
|
||||
|
||||
var description: String {
|
||||
var result = "DequeLayout(capacity: \(capacity), startSlot: \(startSlot), count: \(count)"
|
||||
if count > 0 {
|
||||
result += ", startValue: \(startValue)"
|
||||
}
|
||||
result += ")"
|
||||
return result
|
||||
}
|
||||
|
||||
var isWrapped: Bool {
|
||||
startSlot + count > capacity
|
||||
}
|
||||
}
|
||||
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
internal struct RigidTestData<Element>: ~Copyable {
|
||||
var deque: RigidDeque<Element>
|
||||
var contents: [Element]
|
||||
|
||||
init(_ deque: consuming RigidDeque<Element>, _ contents: [Element]) {
|
||||
self.deque = deque
|
||||
self.contents = contents
|
||||
}
|
||||
|
||||
mutating func take() -> RigidDeque<Element> {
|
||||
exchange(&self.deque, with: .init())
|
||||
}
|
||||
|
||||
consuming func consume() -> RigidDeque<Element> {
|
||||
exchange(&self.deque, with: .init())
|
||||
}
|
||||
}
|
||||
|
||||
extension LifetimeTracker {
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
func rigidDeque(
|
||||
with layout: DequeLayout
|
||||
) -> RigidTestData<LifetimeTracked<Int>> {
|
||||
let contents = self.instances(for: layout.valueRange)
|
||||
let deque = RigidDeque(layout: layout, contents: contents)
|
||||
return RigidTestData(deque, contents)
|
||||
}
|
||||
}
|
||||
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
extension RigidDeque where Element: ~Copyable {
|
||||
init<C: Collection<Element>>(layout: DequeLayout, contents: C) {
|
||||
precondition(contents.count == layout.count)
|
||||
self.init(
|
||||
_capacity: layout.capacity,
|
||||
startSlot: layout.startSlot,
|
||||
copying: contents)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
private func withEveryFullDeque<C: Collection>(
|
||||
_ label: String,
|
||||
ofCapacities capacities: C,
|
||||
startValue: Int = 0,
|
||||
file: StaticString = #filePath, line: UInt = #line,
|
||||
_ body: (DequeLayout) throws -> Void
|
||||
) rethrows -> Void where C.Element == Int {
|
||||
// Exhaustive tests for all deque layouts of various capacities
|
||||
for capacity in capacities {
|
||||
for startSlot in 0 ..< capacity {
|
||||
let layout = DequeLayout(
|
||||
capacity: capacity,
|
||||
startSlot: startSlot,
|
||||
count: capacity,
|
||||
startValue: startValue)
|
||||
let entry = TestContext.current.push("\(label): \(layout)", file: file, line: line)
|
||||
defer { TestContext.current.pop(entry) }
|
||||
try body(layout)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(SwiftStdlib 6.4, *)
|
||||
final class MutableContainer_Update_Tests: CollectionTestCase {
|
||||
func test_updateSubrange_updatingWith() {
|
||||
withEveryFullDeque("layout", ofCapacities: [0, 1, 10]) { layout in
|
||||
withEveryRange("subrange", in: 0 ..< layout.count) { subrange in
|
||||
withLifetimeTracking { tracker in
|
||||
var expected = Array(0 ..< layout.count)
|
||||
let replacements1 = layout.count ..< (layout.count + subrange.count)
|
||||
expected.replaceSubrange(subrange, with: replacements1)
|
||||
|
||||
var actual = tracker.rigidDeque(with: layout)
|
||||
var i = layout.count
|
||||
actual.deque.updateSubrange(subrange) { span in
|
||||
var items = UniqueArray(copying: tracker.instances(
|
||||
count: span.count, generator: { i + $0 }))
|
||||
i += span.count
|
||||
items.edit { src in
|
||||
span._updateAll(moving: &src)
|
||||
}
|
||||
}
|
||||
expectIterablePayloads(actual.deque, equalTo: expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func test_updateElements_after_from_Producer() {
|
||||
// Note: We don't test throwing producers, as prematurely terminating
|
||||
// producers end up covering the same code paths. (FIXME: Do it anyway)
|
||||
withEveryFullDeque("layout", ofCapacities: [0, 1, 10]) { layout in
|
||||
withEvery("start", in: 0 ..< layout.count) { start in
|
||||
withEvery("length", in: 0 ..< layout.count - start + 2) { length in
|
||||
withEvery("chunkSize", in: [1, 2, length] as Set) { chunkSize in
|
||||
withLifetimeTracking { tracker in
|
||||
var expected = Array(0 ..< layout.count)
|
||||
let replacements1 = layout.count ..< (layout.count + length)
|
||||
let end = Swift.min(start + length, layout.count)
|
||||
expected.replaceSubrange(
|
||||
start ..< end,
|
||||
with: replacements1.prefix(end - start))
|
||||
|
||||
var actual = tracker.rigidDeque(with: layout)
|
||||
var replacements2 = CustomProducer<LifetimeTracked<Int>, Never>(
|
||||
underestimatedCount: 0,
|
||||
chunkSize: chunkSize
|
||||
) { offset in
|
||||
guard offset < end - start else { return nil }
|
||||
return tracker.instance(for: layout.count + offset)
|
||||
}
|
||||
|
||||
var i = start
|
||||
actual.deque.updateElements(after: &i, from: &replacements2)
|
||||
|
||||
expectIterablePayloads(actual.deque, equalTo: expected)
|
||||
expectEqual(i, end)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func test_updateElements_after_from_CountedProducer() {
|
||||
withEveryFullDeque("layout", ofCapacities: [0, 1, 10]) { layout in
|
||||
withEvery("start", in: 0 ..< layout.count) { start in
|
||||
withEvery("length", in: 0 ..< layout.count - start + 2) { length in
|
||||
withEvery("chunkSize", in: [1, 2, length] as Set) { chunkSize in
|
||||
withLifetimeTracking { tracker in
|
||||
var expected = Array(0 ..< layout.count)
|
||||
let replacements1 = layout.count ..< (layout.count + length)
|
||||
let end = Swift.min(start + length, layout.count)
|
||||
expected.replaceSubrange(
|
||||
start ..< end,
|
||||
with: replacements1.prefix(end - start))
|
||||
|
||||
var actual = tracker.rigidDeque(with: layout)
|
||||
var replacements2 = CustomCountedProducer<LifetimeTracked<Int>, Never>(
|
||||
count: length,
|
||||
chunkSize: chunkSize
|
||||
) { offset in
|
||||
tracker.instance(for: layout.count + offset)
|
||||
}
|
||||
|
||||
var i = start
|
||||
actual.deque.updateElements(after: &i, from: &replacements2)
|
||||
|
||||
expectIterablePayloads(actual.deque, equalTo: expected)
|
||||
expectEqual(i, end)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func test_updateSubrange_from_CountedProducer() {
|
||||
withEveryFullDeque("targetLayout", ofCapacities: [0, 1, 10]) { targetLayout in
|
||||
withEveryRange("subrange", in: 0 ..< targetLayout.count) { subrange in
|
||||
withEvery("chunkSize", in: [1, 2, subrange.count] as Set) { chunkSize in
|
||||
withLifetimeTracking { tracker in
|
||||
var expected = Array(0 ..< targetLayout.count)
|
||||
let replacements1 = targetLayout.count ..< (targetLayout.count + subrange.count)
|
||||
expected.replaceSubrange(subrange, with: replacements1)
|
||||
|
||||
var actual = tracker.rigidDeque(with: targetLayout).consume()
|
||||
let replacements2 = CustomCountedProducer<LifetimeTracked<Int>, Never>(
|
||||
count: subrange.count,
|
||||
chunkSize: chunkSize
|
||||
) { offset in
|
||||
tracker.instance(for: targetLayout.count + offset)
|
||||
}
|
||||
actual.updateSubrange(subrange, from: replacements2)
|
||||
expectIterablePayloads(actual, equalTo: expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func test_updateSubrange_from_Drain() {
|
||||
withEveryFullDeque("targetLayout", ofCapacities: [0, 1, 10]) { targetLayout in
|
||||
withEveryRange("subrange", in: 0 ..< targetLayout.count) { subrange in
|
||||
withEveryFullDeque(
|
||||
"sourceLayout",
|
||||
ofCapacities: [subrange.count],
|
||||
startValue: targetLayout.count
|
||||
) { sourceLayout in
|
||||
withLifetimeTracking { tracker in
|
||||
var expected = Array(0 ..< targetLayout.count)
|
||||
let replacements1 = targetLayout.count ..< (targetLayout.count + subrange.count)
|
||||
expected.replaceSubrange(subrange, with: replacements1)
|
||||
|
||||
var actual = tracker.rigidDeque(with: targetLayout).consume()
|
||||
var replacements2 = tracker.rigidDeque(with: sourceLayout).consume()
|
||||
actual.updateSubrange(subrange, from: replacements2.consumeAll())
|
||||
|
||||
expectIterablePayloads(actual, equalTo: expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func test_updateElements_after_copying_BorrowingIteratorProtocol() {
|
||||
// Note: We don't test throwing producers, as prematurely terminating
|
||||
// producers end up covering the same code paths. (FIXME: Do it anyway)
|
||||
withEveryFullDeque("layout", ofCapacities: [0, 1, 10]) { layout in
|
||||
withEvery("start", in: 0 ..< layout.count) { start in
|
||||
withEvery("length", in: 0 ..< layout.count - start + 2) { length in
|
||||
withEvery("chunkSize", in: [1, 2, length] as Set) { chunkSize in
|
||||
withLifetimeTracking { tracker in
|
||||
var expected = Array(0 ..< layout.count)
|
||||
let replacements1 = layout.count ..< (layout.count + length)
|
||||
let end = Swift.min(start + length, layout.count)
|
||||
expected.replaceSubrange(
|
||||
start ..< end,
|
||||
with: replacements1.prefix(end - start))
|
||||
|
||||
var actual = tracker.rigidDeque(with: layout)
|
||||
var replacements2 = CustomBorrowingIterator<LifetimeTracked<Int>, Never>(
|
||||
underestimatedCount: 0,
|
||||
chunkSize: chunkSize
|
||||
) { offset in
|
||||
guard offset < end - start else { return nil }
|
||||
return tracker.instance(for: layout.count + offset)
|
||||
}
|
||||
|
||||
var i = start
|
||||
actual.deque.updateElements(after: &i, copying: &replacements2)
|
||||
|
||||
expectIterablePayloads(actual.deque, equalTo: expected)
|
||||
expectEqual(i, end)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func test_updateSubrange_copying_Container() {
|
||||
withEveryFullDeque("targetLayout", ofCapacities: [0, 1, 10]) { targetLayout in
|
||||
withEveryRange("subrange", in: 0 ..< targetLayout.count) { subrange in
|
||||
withEveryFullDeque(
|
||||
"sourceLayout",
|
||||
ofCapacities: [subrange.count],
|
||||
startValue: targetLayout.count
|
||||
) { sourceLayout in
|
||||
withLifetimeTracking { tracker in
|
||||
var expected = Array(0 ..< targetLayout.count)
|
||||
let replacements1 = targetLayout.count ..< (targetLayout.count + subrange.count)
|
||||
expected.replaceSubrange(subrange, with: replacements1)
|
||||
|
||||
var actual = tracker.rigidDeque(with: targetLayout).consume()
|
||||
let replacements2 = tracker.rigidDeque(with: sourceLayout).consume()
|
||||
actual.updateSubrange(subrange, copying: replacements2)
|
||||
|
||||
expectIterablePayloads(actual, equalTo: expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,190 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Collections open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
|
||||
#if COLLECTIONS_SINGLE_MODULE
|
||||
import Collections
|
||||
#else
|
||||
import _CollectionsTestSupport
|
||||
import ContainersPreview
|
||||
import InternalCollectionsUtilities
|
||||
import BasicContainers
|
||||
import SpanPreview
|
||||
#endif
|
||||
|
||||
#if compiler(>=6.4) && UnstableContainersPreview
|
||||
@available(SwiftStdlib 6.4, *)
|
||||
final class MutableSpanUpdateTests: CollectionTestCase {
|
||||
func testMutableSpan_edit() {
|
||||
withEvery("c", in: [0, 1, 10]) { c in
|
||||
withEvery("suffix", in: 0 ..< c) { suffix in
|
||||
withLifetimeTracking { tracker in
|
||||
var expected = Array(0 ..< c)
|
||||
expected.removeLast(suffix)
|
||||
expected.append(contentsOf: c ..< c + suffix)
|
||||
|
||||
var actual = tracker.structInstances(count: c, generator: { $0 })
|
||||
expectEqual(tracker.instances, c)
|
||||
var span = actual.mutableSpan
|
||||
span._edit { out in
|
||||
out.removeLast(suffix)
|
||||
expectEqual(tracker.instances, c - suffix)
|
||||
for i in 0 ..< suffix {
|
||||
out.append(tracker.structInstance(for: c + i))
|
||||
}
|
||||
}
|
||||
expectEqual(tracker.instances, c)
|
||||
expectIterablePayloads(actual, equalTo: expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testMutableSpan_updateSubrange_moving_OutputSpan() {
|
||||
withEvery("c", in: [0, 1, 10]) { c in
|
||||
withEveryRange("subrange", in: 0 ..< c) { subrange in
|
||||
withLifetimeTracking { tracker in
|
||||
var expected = Array(0 ..< c)
|
||||
let replacements1 = c ..< (c + subrange.count)
|
||||
expected.replaceSubrange(subrange, with: replacements1)
|
||||
|
||||
var actual = tracker.structInstances(count: c, generator: { $0 })
|
||||
var replacements2 = tracker.structInstances(
|
||||
count: subrange.count, generator: { c + $0 })
|
||||
replacements2.edit { source in
|
||||
var span = actual.mutableSpan
|
||||
span._updateSubrange(subrange, moving: &source)
|
||||
}
|
||||
|
||||
expectTrue(replacements2.isEmpty)
|
||||
expectEqual(actual.count, expected.count)
|
||||
expectIterablePayloads(actual, equalTo: expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if UnstableContainersPreview
|
||||
func testMutableSpan_updateSubrange_moving_InputSpan() {
|
||||
withEvery("c", in: [0, 1, 10]) { c in
|
||||
withEveryRange("subrange", in: 0 ..< c) { subrange in
|
||||
withLifetimeTracking { tracker in
|
||||
var expected = Array(0 ..< c)
|
||||
let replacements1 = c ..< (c + subrange.count)
|
||||
expected.replaceSubrange(subrange, with: replacements1)
|
||||
|
||||
var actual = tracker.structInstances(count: c, generator: { $0 })
|
||||
var replacements2 = tracker.structInstances(
|
||||
count: subrange.count, generator: { c + $0 })
|
||||
replacements2.edit { source in
|
||||
source._consumeAll { source in
|
||||
var span = actual.mutableSpan
|
||||
span._updateSubrange(subrange, moving: &source)
|
||||
}
|
||||
}
|
||||
|
||||
expectTrue(replacements2.isEmpty)
|
||||
expectEqual(actual.count, expected.count)
|
||||
expectIterablePayloads(actual, equalTo: expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
func testMutableSpan_updateAll_moving_OutputSpan() {
|
||||
withEvery("c", in: 0 ..< 10) { c in
|
||||
withLifetimeTracking { tracker in
|
||||
let expected = c ..< 2 * c
|
||||
|
||||
var actual = tracker.structInstances(count: c, generator: { $0 })
|
||||
var replacements2 = tracker.structInstances(
|
||||
count: c, generator: { c + $0 })
|
||||
replacements2.edit { source in
|
||||
var span = actual.mutableSpan
|
||||
span._updateAll(moving: &source)
|
||||
}
|
||||
|
||||
expectTrue(replacements2.isEmpty)
|
||||
expectEqual(actual.count, expected.count)
|
||||
expectIterablePayloads(actual, equalTo: expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if UnstableContainersPreview
|
||||
func testMutableSpan_updateAll_moving_InputSpan() {
|
||||
withEvery("c", in: 0 ..< 10) { c in
|
||||
withLifetimeTracking { tracker in
|
||||
let expected = c ..< 2 * c
|
||||
|
||||
var actual = tracker.structInstances(count: c, generator: { $0 })
|
||||
var replacements2 = tracker.structInstances(
|
||||
count: c, generator: { c + $0 })
|
||||
replacements2.edit { source in
|
||||
source._consumeAll { source in
|
||||
var span = actual.mutableSpan
|
||||
span._updateAll(moving: &source)
|
||||
}
|
||||
}
|
||||
|
||||
expectTrue(replacements2.isEmpty)
|
||||
expectEqual(actual.count, expected.count)
|
||||
expectIterablePayloads(actual, equalTo: expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
func testMutableSpan_updateSubrange_copying_Span() {
|
||||
withEvery("c", in: [0, 1, 10]) { c in
|
||||
withEveryRange("subrange", in: 0 ..< c) { subrange in
|
||||
withLifetimeTracking { tracker in
|
||||
var expected = Array(0 ..< c)
|
||||
let replacements1 = c ..< (c + subrange.count)
|
||||
expected.replaceSubrange(subrange, with: replacements1)
|
||||
|
||||
var actual = tracker.instances(count: c, generator: { $0 })
|
||||
let replacements2 = tracker.instances(
|
||||
count: subrange.count, generator: { c + $0 })
|
||||
var span = actual.mutableSpan
|
||||
span._updateSubrange(subrange, copying: replacements2.span)
|
||||
|
||||
expectEqual(replacements2.count, subrange.count)
|
||||
expectEqual(actual.count, expected.count)
|
||||
expectIterablePayloads(actual, equalTo: expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testMutableSpan_updateAll_copying_Span() {
|
||||
withEvery("c", in: 0 ..< 10) { c in
|
||||
withLifetimeTracking { tracker in
|
||||
let expected = c ..< 2 * c
|
||||
|
||||
var actual = tracker.instances(count: c, generator: { $0 })
|
||||
let replacements2 = tracker.instances(count: c, generator: { c + $0 })
|
||||
|
||||
var span = actual.mutableSpan
|
||||
span._updateAll(copying: replacements2.span)
|
||||
|
||||
expectEqual(replacements2.count, c)
|
||||
expectEqual(actual.count, expected.count)
|
||||
expectIterablePayloads(actual, equalTo: expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -364,19 +364,16 @@ final class RigidDequeTests: CollectionTestCase {
|
||||
withEvery("capacity", in: [count, count + 1, 2 * count] as Set) { capacity in
|
||||
withLifetimeTracking { tracker in
|
||||
var invocations = 0
|
||||
let producer = CustomProducer<LifetimeTrackedStruct<Int>, Never> {
|
||||
if invocations >= count {
|
||||
return nil
|
||||
}
|
||||
defer { invocations += 1 }
|
||||
return tracker.structInstance(for: invocations)
|
||||
let producer = CustomProducer<LifetimeTrackedStruct<Int>, Never> { offset in
|
||||
guard offset < count else { return nil }
|
||||
invocations += 1
|
||||
return tracker.structInstance(for: offset)
|
||||
}
|
||||
|
||||
let deque = RigidDeque(capacity: capacity, from: producer)
|
||||
expectEqual(invocations, count)
|
||||
expectEqual(deque.count, count)
|
||||
expectEqual(tracker.instances, count)
|
||||
expectEqual(invocations, count)
|
||||
|
||||
for i in 0 ..< count {
|
||||
expectEqual(deque[i].payload, i)
|
||||
@@ -393,12 +390,12 @@ final class RigidDequeTests: CollectionTestCase {
|
||||
var invocations = 0
|
||||
expectThrows { () throws(TestError) in
|
||||
let producer = CustomProducer<LifetimeTrackedStruct<Int>, TestError>
|
||||
{ () throws(TestError) in
|
||||
if invocations >= count {
|
||||
{ offset throws(TestError) in
|
||||
if offset >= count {
|
||||
throw TestError(42)
|
||||
}
|
||||
defer { invocations += 1 }
|
||||
return tracker.structInstance(for: invocations)
|
||||
invocations += 1
|
||||
return tracker.structInstance(for: offset)
|
||||
}
|
||||
|
||||
let _ = try RigidDeque(capacity: count + 10, from: producer)
|
||||
@@ -794,7 +791,7 @@ final class RigidDequeTests: CollectionTestCase {
|
||||
|
||||
data.contents.insert(contentsOf: extras.prefix(layout.freeCapacity), at: 0)
|
||||
|
||||
var producer = CustomProducer<LifetimeTracked<Int>, Never> {
|
||||
var producer = CustomProducer<LifetimeTracked<Int>, Never> { offset in
|
||||
guard !extras.isEmpty else { return nil }
|
||||
return extras.removeFirst()
|
||||
}
|
||||
@@ -820,7 +817,7 @@ final class RigidDequeTests: CollectionTestCase {
|
||||
|
||||
data.contents.append(contentsOf: extras)
|
||||
|
||||
var producer = CustomProducer<LifetimeTracked<Int>, Never> {
|
||||
var producer = CustomProducer<LifetimeTracked<Int>, Never> { offset in
|
||||
guard !extras.isEmpty else { return nil }
|
||||
return extras.removeFirst()
|
||||
}
|
||||
@@ -847,7 +844,7 @@ final class RigidDequeTests: CollectionTestCase {
|
||||
|
||||
data.contents.insert(contentsOf: extras.reversed(), at: 0)
|
||||
|
||||
var producer = CustomProducer<LifetimeTracked<Int>, TestError> { () throws(TestError) in
|
||||
var producer = CustomProducer<LifetimeTracked<Int>, TestError> { offset throws(TestError) in
|
||||
guard !extras.isEmpty else { throw TestError(23) }
|
||||
return extras.removeLast()
|
||||
}
|
||||
@@ -878,7 +875,7 @@ final class RigidDequeTests: CollectionTestCase {
|
||||
|
||||
data.contents.append(contentsOf: extras.reversed())
|
||||
|
||||
var producer = CustomProducer<LifetimeTracked<Int>, TestError> { () throws(TestError) in
|
||||
var producer = CustomProducer<LifetimeTracked<Int>, TestError> { offset throws(TestError) in
|
||||
guard !extras.isEmpty else { throw TestError(23) }
|
||||
return extras.removeLast()
|
||||
}
|
||||
@@ -1207,7 +1204,7 @@ final class RigidDequeTests: CollectionTestCase {
|
||||
contentsOf: extras.prefix(layout.freeCapacity),
|
||||
at: i)
|
||||
|
||||
var producer = CustomProducer<LifetimeTracked<Int>, Never> {
|
||||
var producer = CustomProducer<LifetimeTracked<Int>, Never> { offset in
|
||||
guard !extras.isEmpty else { return nil }
|
||||
return extras.removeFirst()
|
||||
}
|
||||
@@ -1239,7 +1236,7 @@ final class RigidDequeTests: CollectionTestCase {
|
||||
|
||||
data.contents.insert(contentsOf: extras, at: i)
|
||||
|
||||
var producer = CustomProducer<LifetimeTracked<Int>, TestError> { () throws(TestError) in
|
||||
var producer = CustomProducer<LifetimeTracked<Int>, TestError> { offset throws(TestError) in
|
||||
guard !extras.isEmpty else { throw TestError(23) }
|
||||
return extras.removeFirst()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Collections open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
|
||||
#if COLLECTIONS_SINGLE_MODULE
|
||||
import Collections
|
||||
#else
|
||||
import InternalCollectionsUtilities
|
||||
import ContainersPreview
|
||||
import BasicContainers
|
||||
#endif
|
||||
|
||||
#if compiler(>=6.4) && UnstableContainersPreview
|
||||
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
package struct CustomBorrowingIterator<Element: ~Copyable, Failure: Error>: ~Copyable {
|
||||
package let _underestimatedCount: Int
|
||||
package let _generator: (Int) throws(Failure) -> Element?
|
||||
package var _offset: Int
|
||||
package var _scratch: RigidArray<Element>
|
||||
package var _pendingError: Failure?
|
||||
|
||||
package init(
|
||||
underestimatedCount: Int = 0,
|
||||
chunkSize: Int,
|
||||
generatingWith generator: borrowing @escaping (Int) throws(Failure) -> Element?
|
||||
) {
|
||||
self._underestimatedCount = underestimatedCount
|
||||
self._generator = copy generator
|
||||
self._offset = 0
|
||||
self._scratch = RigidArray(capacity: chunkSize)
|
||||
self._pendingError = nil
|
||||
}
|
||||
|
||||
package var offset: Int { _offset }
|
||||
}
|
||||
|
||||
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
extension CustomBorrowingIterator: BorrowingIteratorProtocol where Element: ~Copyable {
|
||||
@_lifetime(&self)
|
||||
package mutating func nextSpan(maxCount: Int) throws(Failure) -> Span<Element> {
|
||||
// Errors must only be thrown before we have generated any items, or the abstraction gets broken.
|
||||
if let error = _pendingError.take() { throw error }
|
||||
_scratch.removeAll()
|
||||
let c = Swift.min(maxCount, _scratch.capacity)
|
||||
try _scratch.append(addingCount: c) { target throws(Failure) in
|
||||
while !target.isFull {
|
||||
do throws(Failure) { // FIXME: Why is this necessary?
|
||||
guard let next = try _generator(_offset) else { return }
|
||||
target.append(next)
|
||||
_offset += 1
|
||||
} catch {
|
||||
guard !target.isEmpty else { throw error }
|
||||
_pendingError = error
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
return _scratch.span
|
||||
}
|
||||
|
||||
package mutating func skip(by maxOffset: Int) throws(Failure) -> Int {
|
||||
// Note: we still generate items, so that we throw when expected.
|
||||
var c = 0
|
||||
while c < maxOffset {
|
||||
guard let _ = try _generator(_offset) else { break }
|
||||
_offset += 1
|
||||
c += 1
|
||||
}
|
||||
return c
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,65 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Collections open source project
|
||||
//
|
||||
// Copyright (c) 2025 - 2026 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#if COLLECTIONS_SINGLE_MODULE
|
||||
import Collections
|
||||
#else
|
||||
import InternalCollectionsUtilities
|
||||
import ContainersPreview
|
||||
#endif
|
||||
|
||||
#if compiler(>=6.4) && UnstableContainersPreview
|
||||
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
package struct CustomCountedProducer<Element: ~Copyable, Failure: Error>: ~Copyable {
|
||||
package let count: Int
|
||||
package let underestimatedCount: Int
|
||||
package let _chunkSize: Int
|
||||
package let _generator: (Int) throws(Failure) -> Element
|
||||
package var _offset: Int
|
||||
|
||||
package init(
|
||||
count: Int = 0,
|
||||
underestimatedCount: Int? = nil,
|
||||
chunkSize: Int = Int.max,
|
||||
generatingWith generator: borrowing @escaping (Int) throws(Failure) -> Element
|
||||
) {
|
||||
precondition(count >= 0)
|
||||
self.count = count
|
||||
self.underestimatedCount = underestimatedCount ?? count
|
||||
precondition(self.underestimatedCount >= 0 && self.underestimatedCount <= count)
|
||||
precondition(count == 0 || chunkSize > 0)
|
||||
self._chunkSize = chunkSize
|
||||
self._generator = copy generator
|
||||
self._offset = 0
|
||||
}
|
||||
|
||||
package var offset: Int { _offset }
|
||||
}
|
||||
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
extension CustomCountedProducer: CountedProducer where Element: ~Copyable {
|
||||
package mutating func generate(
|
||||
into target: inout OutputSpan<Element>
|
||||
) throws(Failure) -> Bool {
|
||||
var success = false
|
||||
while !target.isFull, _offset < count {
|
||||
target.append(try _generator(_offset))
|
||||
_offset += 1
|
||||
success = true
|
||||
}
|
||||
return success
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,55 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Collections open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
|
||||
#if COLLECTIONS_SINGLE_MODULE
|
||||
import Collections
|
||||
#else
|
||||
import InternalCollectionsUtilities
|
||||
import ContainersPreview
|
||||
#endif
|
||||
|
||||
#if compiler(>=6.4) && UnstableContainersPreview
|
||||
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
package struct CustomIterable<Element: ~Copyable, Failure: Error>: ~Copyable {
|
||||
package let underestimatedCount: Int
|
||||
package let _chunkSize: Int
|
||||
package let _generator: (Int) throws(Failure) -> Element?
|
||||
|
||||
package init(
|
||||
underestimatedCount: Int = 0,
|
||||
chunkSize: Int,
|
||||
generatingWith generator: borrowing @escaping (Int) throws(Failure) -> Element?
|
||||
) {
|
||||
self.underestimatedCount = underestimatedCount
|
||||
self._chunkSize = chunkSize
|
||||
self._generator = copy generator
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
extension CustomIterable: Iterable where Element: ~Copyable {
|
||||
package typealias BorrowingIterator = CustomBorrowingIterator<Element, Failure>
|
||||
|
||||
package borrowing func makeBorrowingIterator() -> BorrowingIterator {
|
||||
BorrowingIterator(
|
||||
underestimatedCount: self.underestimatedCount,
|
||||
chunkSize: self._chunkSize,
|
||||
generatingWith: self._generator)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -24,17 +24,21 @@ import ContainersPreview
|
||||
package struct CustomProducer<Element: ~Copyable, Failure: Error>: ~Copyable {
|
||||
package let underestimatedCount: Int
|
||||
package let _chunkSize: Int
|
||||
package let _generator: () throws(Failure) -> Element?
|
||||
package let _generator: (Int) throws(Failure) -> Element?
|
||||
package var _offset: Int
|
||||
|
||||
package init(
|
||||
underestimatedCount: Int = 0,
|
||||
chunkSize: Int = Int.max,
|
||||
generatingWith generator: borrowing @escaping () throws(Failure) -> Element?
|
||||
generatingWith generator: borrowing @escaping (Int) throws(Failure) -> Element?
|
||||
) {
|
||||
self.underestimatedCount = underestimatedCount
|
||||
self._chunkSize = chunkSize
|
||||
self._generator = copy generator
|
||||
self._offset = 0
|
||||
}
|
||||
|
||||
package var offset: Int { _offset }
|
||||
}
|
||||
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
@@ -44,11 +48,12 @@ extension CustomProducer: Producer where Element: ~Copyable {
|
||||
) throws(Failure) -> Bool {
|
||||
var i = 0
|
||||
while !target.isFull, i < _chunkSize {
|
||||
guard let next = try _generator() else { return false }
|
||||
guard let next = try _generator(_offset) else { return i > 0 }
|
||||
target.append(next)
|
||||
_offset += 1
|
||||
i += 1
|
||||
}
|
||||
return true
|
||||
return i > 0
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Collections open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#if COLLECTIONS_SINGLE_MODULE
|
||||
import Collections
|
||||
#else
|
||||
import InternalCollectionsUtilities
|
||||
import ContainersPreview
|
||||
#endif
|
||||
|
||||
#if compiler(>=6.4) && UnstableContainersPreview
|
||||
|
||||
/// A wrapper over an arbitrary producer that _only_ conforms to the base
|
||||
/// `Producer` protocol, without any of its refinements, and without any
|
||||
/// extensions that may be present on the original type.
|
||||
///
|
||||
/// All requirements are implemented by directly forwarding to the base
|
||||
/// producer.
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
package struct PureProducer<Wrapped: Producer & ~Copyable & ~Escapable>
|
||||
: ~Copyable, ~Escapable
|
||||
where
|
||||
Wrapped.Element: ~Copyable
|
||||
{
|
||||
package var _base: Wrapped
|
||||
|
||||
@_lifetime(copy base)
|
||||
package init(_ base: consuming Wrapped) {
|
||||
self._base = base
|
||||
}
|
||||
}
|
||||
|
||||
#if false
|
||||
// FIXME: This is rejected:
|
||||
// > error: Conditional conformance to 'Copyable' must explicitly state whether
|
||||
// > 'Wrapped.Element' is required to conform to 'Escapable' or not
|
||||
// etc.
|
||||
extension PureProducer: Copyable
|
||||
where
|
||||
Wrapped: Copyable & ~Escapable,
|
||||
Wrapped.Element: ~Copyable & Escapable,
|
||||
Wrapped.Failure: Copyable & Escapable {}
|
||||
|
||||
extension PureProducer: Escapable
|
||||
where
|
||||
Wrapped: ~Copyable & Escapable,
|
||||
Wrapped.Element: ~Copyable & Escapable,
|
||||
Wrapped.Failure: Copyable & Escapable {}
|
||||
#endif
|
||||
|
||||
extension PureProducer: Producer
|
||||
where Wrapped: ~Copyable & ~Escapable, Wrapped.Element: ~Copyable {
|
||||
package typealias Element = Wrapped.Element
|
||||
package typealias Failure = Wrapped.Failure
|
||||
|
||||
package var underestimatedCount: Int { _base.underestimatedCount }
|
||||
|
||||
@discardableResult
|
||||
@_lifetime(target: copy target)
|
||||
package mutating func generate(
|
||||
into target: inout OutputSpan<Element>
|
||||
) throws(Failure) -> Bool {
|
||||
try _base.generate(into: &target)
|
||||
}
|
||||
|
||||
package mutating func skip(by n: inout Int) throws(Failure) {
|
||||
try _base.skip(by: &n)
|
||||
}
|
||||
|
||||
package mutating func next() throws(Failure) -> Element? {
|
||||
try _base.next()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#endif
|
||||
@@ -62,6 +62,16 @@ public class LifetimeTracker {
|
||||
return items.map { LifetimeTracked($0, for: self) }
|
||||
}
|
||||
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
public func instances<Element>(
|
||||
count: Int,
|
||||
generator: (Int) -> Element
|
||||
) -> [LifetimeTracked<Element>] {
|
||||
(0 ..< count).map {
|
||||
LifetimeTracked(generator($0), for: self)
|
||||
}
|
||||
}
|
||||
|
||||
#if compiler(>=6.2)
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
public func structInstances<Element>(
|
||||
@@ -76,6 +86,18 @@ public class LifetimeTracker {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
public func structInstances<S: Sequence>(
|
||||
for items: S
|
||||
) -> UniqueArray<LifetimeTrackedStruct<S.Element>> {
|
||||
var r = UniqueArray<LifetimeTrackedStruct<S.Element>>(
|
||||
minimumCapacity: items.underestimatedCount)
|
||||
for item in items {
|
||||
r.append(LifetimeTrackedStruct(item, for: self))
|
||||
}
|
||||
return r
|
||||
}
|
||||
#endif
|
||||
|
||||
public func instances<S: Sequence, T>(
|
||||
|
||||
Reference in new issue
Block a user