From c1ff9b9063996f3be4c74e56bde306d14ae7e810 Mon Sep 17 00:00:00 2001 From: Joseph Cursio Date: Fri, 30 Oct 2026 13:34:34 -0500 Subject: [PATCH 1/6] Build RigidArray's consumeLast drain without recursing RigidArray's _customConsumeLast(_:) hook called consumeLast(_:), but RigidArray has no one-argument consumeLast of its own, so the call went to DrainableContainer.consumeLast(_:), which starts by calling the hook. Every call to consumeLast(_:) on a RigidArray, directly or through generic code, recursed until the stack overflowed. Have the hook check the count and return consumeSubrange(_:) over the last n items directly, the way consumeLast(_:consumingWith:) does. Fixes #814. Co-Authored-By: Claude Opus 5.5 --- .../Conformances/RigidArray+Container.swift | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Sources/ContainersPreview/Conformances/RigidArray+Container.swift b/Sources/ContainersPreview/Conformances/RigidArray+Container.swift index ff3f0327..f5dc446d 100644 --- a/Sources/ContainersPreview/Conformances/RigidArray+Container.swift +++ b/Sources/ContainersPreview/Conformances/RigidArray+Container.swift @@ -169,7 +169,10 @@ extension RigidArray: RangeReplaceableContainer where Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(&self) public mutating func _customConsumeLast(_ n: Int) -> SubrangeConsumer? { - self.consumeLast(n) + precondition( + n >= 0 && n <= self.count, + "Count of elements to consume is out of bounds") + return self.consumeSubrange(self.count &- n ..< self.count) } @_alwaysEmitIntoClient From d60ceae0620c782b69a8ecfd5578d8bb448da43d Mon Sep 17 00:00:00 2001 From: Joseph Cursio Date: Fri, 30 Oct 2026 13:43:37 -0500 Subject: [PATCH 2/6] Add checkDrainableContainer Check the DrainableContainer requirements and extensions against Array's removeSubrange(_:), for every subrange: that a subrange drain hands out the removed items in order, in spans no longer than maxCount, then only empty spans, with an accurate count; that it removes the whole subrange whether it is finalized or dropped partway, and finalize() returns the index following the removed items; that consumeSubrange(_:consumingWith:) passes the removed items to its consumer and discards those it leaves; the items and indices returned by remove(at:), removeFirst() and the index-returning removals, including the RangeExpression2 and UnboundedRange overloads; and that no item is leaked or destroyed but the removed items not handed out. For a BidirectionalContainer, consumeLast(_:), removeLast(), removeLast(_:) and popLast() are checked too. Co-Authored-By: Claude Opus 5.5 --- .../CheckDrainableContainer.swift | 391 ++++++++++++++++++ 1 file changed, 391 insertions(+) create mode 100644 Tests/_CollectionsTestSupport/ConformanceCheckers/CheckDrainableContainer.swift diff --git a/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckDrainableContainer.swift b/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckDrainableContainer.swift new file mode 100644 index 00000000..4707a0a0 --- /dev/null +++ b/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckDrainableContainer.swift @@ -0,0 +1,391 @@ +//===----------------------------------------------------------------------===// +// +// 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 SpanPreview +#endif +import ContainersPreview + +#if compiler(>=6.4) && UnstableContainersPreview +/// Test that the removal and consumption operations of a `DrainableContainer` +/// edit it the way `removeSubrange(_:)` edits an `Array` holding the same +/// items: +/// +/// - The drain returned by `consumeSubrange(_:)` hands out the items of the +/// subrange in order, in spans of at most `maxCount` items, and then only +/// empty spans. Its `count` is the number of items it has yet to hand out. +/// - Whether it is finalized or dropped, and however many items it has handed +/// out, the drain removes the whole subrange, discarding the items it did +/// not hand out and those left in its spans. `finalize()` returns the index +/// following the removed items. +/// - `consumeSubrange(_:consumingWith:)` passes the removed items to its +/// consumer, in order, and discards any the consumer leaves. +/// - `remove(at:)` and `removeFirst()` return the removed item. +/// - The returned indices, and the index passed to `remove(at:)` as inout, +/// address the position following the removed items. +/// - The `RangeExpression2` and `UnboundedRange` overloads remove the items +/// they express. +/// - No item is leaked or destroyed, other than the removed items that are not +/// handed out. +/// +/// Every subrange of a container of `count` items is removed. `makeContainer` +/// must return a new container holding the given items in order. +@available(SwiftStdlib 6.4, *) +package func checkDrainableContainer( + count: Int, + file: StaticString = #filePath, + line: UInt = #line, + makeContainer: ([LifetimeTracked]) -> C +) where C.Element == LifetimeTracked { + let entry = TestContext.current.push( + "checkDrainableContainer", file: file, line: line) + defer { TestContext.current.pop(entry) } + checkDrainLaws( + count: count, file: file, line: line, makeContainer: makeContainer) +} + +/// Test the operations of a bidirectional `DrainableContainer` as above, along +/// with `consumeLast(_:)`, `removeLast()`, `removeLast(_:)` and `popLast()`, +/// which returns nil on an empty container. +@available(SwiftStdlib 6.4, *) +package func checkDrainableContainer< + C: BidirectionalContainer & DrainableContainer & ~Copyable +>( + count: Int, + file: StaticString = #filePath, + line: UInt = #line, + makeContainer: ([LifetimeTracked]) -> C +) where C.Element == LifetimeTracked { + let entry = TestContext.current.push( + "checkDrainableContainer", file: file, line: line) + defer { TestContext.current.pop(entry) } + checkDrainLaws( + count: count, file: file, line: line, makeContainer: makeContainer) + + func check( + _ label: String, + _ removed: Range, + taking takenCount: Int = 0, + _ remove: (inout C, inout [LifetimeTracked]) -> C.Index? + ) { + checkDrainLaw( + label, count: count, removing: removed, taking: takenCount, + file: file, line: line, makeContainer: makeContainer, remove) + } + + withEvery("n", in: 0 ... count) { n in + check("consumeLast(_:)", count - n ..< count, taking: n) { + container, taken in + drain( + container.consumeLast(n), count: n, into: &taken, + file: file, line: line) + } + check("removeLast(_:)", count - n ..< count) { container, _ in + container.removeLast(n) + return nil + } + } + let last = count - min(count, 1) ..< count + check("popLast()", last, taking: last.count) { container, taken in + if let item = container.popLast() { + taken.append(item) + } + return nil + } + if count > 0 { + check("removeLast()", last, taking: 1) { container, taken in + taken.append(container.removeLast()) + return nil + } + } +} + +@available(SwiftStdlib 6.4, *) +private func checkDrainLaws( + count: Int, + file: StaticString, + line: UInt, + makeContainer: ([LifetimeTracked]) -> C +) where C.Element == LifetimeTracked { + func check( + _ label: String, + _ removed: Range, + taking takenCount: Int = 0, + _ remove: (inout C, inout [LifetimeTracked]) -> C.Index? + ) { + checkDrainLaw( + label, count: count, removing: removed, taking: takenCount, + file: file, line: line, makeContainer: makeContainer, remove) + } + + func index(_ offset: Int, in container: borrowing C) -> C.Index { + container.index(container.startIndex, offsetBy: offset) + } + + func bounds( + _ subrange: Range, in container: borrowing C + ) -> Range { + index(subrange.lowerBound, in: container) + ..< index(subrange.upperBound, in: container) + } + + func checkExpression>( + _ name: String, + _ subrange: Range, + _ expression: (borrowing C) -> R + ) { + check("consumeSubrange(_: \(name))", subrange, taking: subrange.count) { + container, taken in + drain( + container.consumeSubrange(expression(container)), + count: subrange.count, into: &taken, file: file, line: line) + } + check( + "consumeSubrange(_: \(name), consumingWith:)", subrange, + taking: subrange.count + ) { container, taken in + container.consumeSubrange(expression(container)) { span in + while !span.isEmpty { + taken.append(span.removeFirst()) + } + } + } + check("removeSubrange(_: \(name))", subrange) { container, _ in + container.removeSubrange(expression(container)) + } + } + + withEveryRange("subrange", in: 0 ..< count) { subrange in + let takenCounts = Set([0, subrange.count / 2, subrange.count]).sorted() + withEvery("maxCount", in: [1, 2, Int.max]) { maxCount in + check("consumeSubrange(_:)", subrange, taking: subrange.count) { + container, taken in + drain( + container.consumeSubrange(bounds(subrange, in: container)), + count: subrange.count, maxCount: maxCount, into: &taken, + file: file, line: line) + } + withEvery("takenCount", in: takenCounts) { takenCount in + withEvery("finalized", in: [false, true]) { finalized in + check("consumeSubrange(_:)", subrange, taking: takenCount) { + container, taken in + drain( + container.consumeSubrange(bounds(subrange, in: container)), + count: subrange.count, maxCount: maxCount, taking: takenCount, + finalizing: finalized, into: &taken, file: file, line: line) + } + } + } + } + withEvery("takenCount", in: takenCounts) { takenCount in + check( + "consumeSubrange(_:consumingWith:)", subrange, taking: takenCount + ) { container, taken in + var offered: [Int] = [] + let index = container.consumeSubrange( + bounds(subrange, in: container) + ) { span in + for position in span.indices { + offered.append(span[position].payload) + } + while taken.count < takenCount, !span.isEmpty { + taken.append(span.removeFirst()) + } + } + expectEqual(offered, Array(subrange), + "consumer was not passed the removed items", + file: file, line: line) + return index + } + } + check("removeSubrange(_:)", subrange) { container, _ in + container.removeSubrange(bounds(subrange, in: container)) + } + checkExpression("Range", subrange) { bounds(subrange, in: $0) } + if !subrange.isEmpty { + checkExpression("ClosedRange", subrange) { + index(subrange.lowerBound, in: $0) + ... index(subrange.upperBound - 1, in: $0) + } + } + if subrange.upperBound == count { + checkExpression("PartialRangeFrom", subrange) { + index(subrange.lowerBound, in: $0)... + } + } + if subrange.lowerBound == 0 { + checkExpression("PartialRangeUpTo", subrange) { + .. 0 { + check("removeFirst()", 0 ..< 1, taking: 1) { container, taken in + taken.append(container.removeFirst()) + return nil + } + } + + check("consumeAll()", 0 ..< count, taking: count) { container, taken in + drain( + container.consumeAll(), count: count, into: &taken, + file: file, line: line) + } + check("consumeAll(consumingWith:)", 0 ..< count, taking: count) { + container, taken in + container.consumeAll { span in + while !span.isEmpty { + taken.append(span.removeFirst()) + } + } + return nil + } + check("consumeSubrange(_: UnboundedRange)", 0 ..< count, taking: count) { + container, taken in + drain( + container.consumeSubrange(...), count: count, into: &taken, + file: file, line: line) + } + check( + "consumeSubrange(_: UnboundedRange, consumingWith:)", 0 ..< count, + taking: count + ) { container, taken in + container.consumeSubrange(...) { span in + while !span.isEmpty { + taken.append(span.removeFirst()) + } + } + } + check("removeSubrange(_: UnboundedRange)", 0 ..< count) { container, _ in + container.removeSubrange(...) + } + check("removeAll()", 0 ..< count) { container, _ in + container.removeAll() + return nil + } +} + +@available(SwiftStdlib 6.4, *) +private func checkDrainLaw( + _ label: String, + count: Int, + removing removed: Range, + taking takenCount: Int, + file: StaticString, + line: UInt, + makeContainer: ([LifetimeTracked]) -> C, + _ remove: (inout C, inout [LifetimeTracked]) -> C.Index? +) where C.Element == LifetimeTracked { + let entry = TestContext.current.push(label, file: file, line: line) + defer { TestContext.current.pop(entry) } + var expected = Array(0 ..< count) + expected.removeSubrange(removed) + withLifetimeTracking(file: file, line: line) { tracker in + var container = makeContainer(tracker.instances(for: 0 ..< count)) + var taken: [LifetimeTracked] = [] + let index = remove(&container, &taken) + expectEqual( + taken.map { $0.payload }, Array(removed.prefix(takenCount)), + "\(label) did not hand out the removed items in order", + file: file, line: line) + if let index { + expectEqual( + container.distance(from: container.startIndex, to: index), + removed.lowerBound, + "\(label) returned an index that does not follow the removed items", + file: file, line: line) + } + expectEqual(tracker.instances, expected.count + taken.count, + "\(label) leaked or destroyed items", + file: file, line: line) + var actual: [Int] = [] + var position = container.startIndex + while position != container.endIndex { + actual.append(container[position].payload) + container.formIndex(after: &position) + } + expectEqual(actual, expected, "\(label) left the wrong contents", + file: file, line: line) + } +} + +@available(SwiftStdlib 6.4, *) +private func drain< + D: ContainerDrain> & ~Copyable & ~Escapable +>( + _ consumer: consuming D, + count: Int, + maxCount: Int = .max, + taking takenCount: Int = .max, + finalizing: Bool = true, + into taken: inout [LifetimeTracked], + file: StaticString, + line: UInt +) -> D.Index? { + var handedOut = 0 + while taken.count < takenCount, handedOut <= count { + expectEqual(consumer.count, count - handedOut, + "drain miscounted the items it has left", + file: file, line: line) + var span = consumer.drainNext(maxCount: maxCount) + if span.isEmpty { break } + expectLessThanOrEqual(span.count, maxCount, + "drainNext(maxCount:) returned too many items", + file: file, line: line) + handedOut += span.count + while taken.count < takenCount, !span.isEmpty { + taken.append(span.removeFirst()) + } + } + if taken.count < takenCount { + expectTrue(consumer.drainNext(maxCount: maxCount).isEmpty, + "drainNext(maxCount:) returned items after an empty span", + file: file, line: line) + } + guard finalizing else { return nil } + return consumer.finalize() +} +#endif From 204d1ae40c4c284c115292e0f885553a509bdfee Mon Sep 17 00:00:00 2001 From: Joseph Cursio Date: Fri, 30 Oct 2026 13:46:53 -0500 Subject: [PATCH 3/6] Check RigidArray with checkDrainableContainer Run the drainable container checker against RigidArray, over arrays of up to six items, full and with spare capacity. With #814's fix reverted, the test crashes on its first consumeLast(_:) call, with DrainableContainer.consumeLast(_:) and RigidArray._customConsumeLast(_:) calling each other until the stack overflows. Co-Authored-By: Claude Opus 5.5 --- Tests/BasicContainersTests/RigidArrayTests.swift | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Tests/BasicContainersTests/RigidArrayTests.swift b/Tests/BasicContainersTests/RigidArrayTests.swift index 0dd57f46..3f6b4326 100644 --- a/Tests/BasicContainersTests/RigidArrayTests.swift +++ b/Tests/BasicContainersTests/RigidArrayTests.swift @@ -88,6 +88,15 @@ class RigidArrayTests: CollectionTestCase { } #if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) + func test_validate_DrainableContainer() { + withSomeArrayLayouts("layout", ofCapacities: [0, 1, 3, 6]) { layout in + checkDrainableContainer(count: layout.count) { contents in + RigidArray(layout: layout) { contents[$0] } + } + } + } + @available(SwiftStdlib 6.4, *) func test_validate_MutableContainer() { withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in From fe90f11c44c52a4699f77c4f91a5ac46de521c12 Mon Sep 17 00:00:00 2001 From: Joseph Cursio Date: Fri, 30 Oct 2026 13:47:14 -0500 Subject: [PATCH 4/6] Check UniqueArray with checkDrainableContainer Run the drainable container checker against UniqueArray, over arrays of up to six items, full and with spare capacity. UniqueArray doesn't override the _customConsumeLast(_:) hook, so it passes with #814's fix reverted. Co-Authored-By: Claude Opus 5.5 --- Tests/BasicContainersTests/UniqueArrayTests.swift | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Tests/BasicContainersTests/UniqueArrayTests.swift b/Tests/BasicContainersTests/UniqueArrayTests.swift index d0ccf57f..1713f4da 100644 --- a/Tests/BasicContainersTests/UniqueArrayTests.swift +++ b/Tests/BasicContainersTests/UniqueArrayTests.swift @@ -88,6 +88,15 @@ class UniqueArrayTests: CollectionTestCase { } } + @available(SwiftStdlib 6.4, *) + func test_validate_DrainableContainer() { + withSomeArrayLayouts("layout", ofCapacities: [0, 1, 3, 6]) { layout in + checkDrainableContainer(count: layout.count) { contents in + UniqueArray(layout: layout) { contents[$0] } + } + } + } + @available(SwiftStdlib 6.4, *) func test_validate_MutableContainer() { withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in From b0a4a44eeb5629b7505f03a6f804879615f7c925 Mon Sep 17 00:00:00 2001 From: Joseph Cursio Date: Fri, 30 Oct 2026 13:47:38 -0500 Subject: [PATCH 5/6] Check RigidDeque with checkDrainableContainer Run the drainable container checker against RigidDeque over every storage layout, including wrapped ones, where a removed subrange can span both ends of the storage and its drain hands it out in two parts. RigidDeque doesn't override the _customConsumeLast(_:) hook, so it passes with #814's fix reverted. Co-Authored-By: Claude Opus 5.5 --- Tests/DequeTests/RigidDequeTests.swift | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Tests/DequeTests/RigidDequeTests.swift b/Tests/DequeTests/RigidDequeTests.swift index 02b40997..3393c5ab 100644 --- a/Tests/DequeTests/RigidDequeTests.swift +++ b/Tests/DequeTests/RigidDequeTests.swift @@ -145,6 +145,15 @@ final class RigidDequeTests: CollectionTestCase { } } + @available(SwiftStdlib 6.4, *) + func test_validate_DrainableContainer() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5]) { layout in + checkDrainableContainer(count: layout.count) { contents in + RigidDeque(layout: layout) { contents[$0] } + } + } + } + @available(SwiftStdlib 6.4, *) func test_validate_MutableContainer() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in From ffd6fe4a3f4ba28bf0acf2605709db097ba4240f Mon Sep 17 00:00:00 2001 From: Joseph Cursio Date: Fri, 30 Oct 2026 13:47:51 -0500 Subject: [PATCH 6/6] Check UniqueDeque with checkDrainableContainer Run the drainable container checker against UniqueDeque over every storage layout, including wrapped ones. UniqueDeque's own remove(at:), removeSubrange(_:) and consumeSubrange(_:consumingWith:) don't match the protocol's requirements, since the first takes its index by value and the others return nothing, so the checker's generic calls reach the protocol's default implementations of these, over a two-part storage. It passes with #814's fix reverted. Co-Authored-By: Claude Opus 5.5 --- Tests/DequeTests/UniqueDequeTests.swift | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Tests/DequeTests/UniqueDequeTests.swift b/Tests/DequeTests/UniqueDequeTests.swift index 872e1a4b..ec9b2cc7 100644 --- a/Tests/DequeTests/UniqueDequeTests.swift +++ b/Tests/DequeTests/UniqueDequeTests.swift @@ -128,6 +128,15 @@ final class UniqueDequeTests: CollectionTestCase { } } + @available(SwiftStdlib 6.4, *) + func test_validate_DrainableContainer() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5]) { layout in + checkDrainableContainer(count: layout.count) { contents in + UniqueDeque(layout: layout) { contents[$0] } + } + } + } + @available(SwiftStdlib 6.4, *) func test_validate_MutableContainer() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in