From c314bdad78b63c0ea50cbeb2db345b2d609f0670 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 21 Oct 2026 17:27:51 -0700 Subject: [PATCH 1/5] =?UTF-8?q?Producer.skip(by:):=20Don=E2=80=99t=20skip?= =?UTF-8?q?=20fewer=20than=20`n`=20items=20unless=20we=20reach=20the=20end?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Protocols/Producer/Producer.swift | 20 ++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/Sources/ContainersPreview/Protocols/Producer/Producer.swift b/Sources/ContainersPreview/Protocols/Producer/Producer.swift index 1c564da8..f10f7f63 100644 --- a/Sources/ContainersPreview/Protocols/Producer/Producer.swift +++ b/Sources/ContainersPreview/Protocols/Producer/Producer.swift @@ -133,8 +133,8 @@ public protocol Producer: ~Copyable, ~Escapable { /// discarding them, except it may avoid the overhead of actually /// materializing the elements. /// - /// As soon as the producer has run out of items, all subsequent calls to - /// this method stop decrementing `n` and return false. + /// If the producer reaches its end midway through skipping, then `n` gets + /// decremented by the number of items successfully skipped before that. /// /// The default implementation of this method repeatedly calls /// `generate(into:)` with a small temporary buffer, immediately discarding @@ -239,18 +239,20 @@ extension Producer where Self: ~Copyable & ~Escapable, Element: ~Copyable { public mutating func skip(by n: inout Int) throws(Failure) { precondition(n > 0, "Cannot skip fewer than one item") let maxBufferSize = _producerBufferSize - return try withTemporaryAllocation( - of: Element.self, - capacity: Swift.min(maxBufferSize, n) - ) { buffer throws(Failure) in - repeat { + var done = false + while n > 0 && !done { + // Never generate more than the remaining count, so we don't skip too far. + try withTemporaryAllocation( + of: Element.self, + capacity: Swift.min(maxBufferSize, n) + ) { buffer throws(Failure) in defer { n &-= buffer.count buffer.removeAll() } try self.generate(into: &buffer) - if !buffer.isFull { return } - } while n > 0 + done = !buffer.isFull + } } } From fcca0e3e2b7da6980f6c46b7ad3d9e22cb3de7ff Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 21 Oct 2026 17:28:42 -0700 Subject: [PATCH 2/5] Producer.filter: Saturate generate(into:) target, and fix underestimatedCount --- .../Protocols/Producer/Producer+Filter.swift | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Sources/ContainersPreview/Protocols/Producer/Producer+Filter.swift b/Sources/ContainersPreview/Protocols/Producer/Producer+Filter.swift index fb9b528b..e085f04b 100644 --- a/Sources/ContainersPreview/Protocols/Producer/Producer+Filter.swift +++ b/Sources/ContainersPreview/Protocols/Producer/Producer+Filter.swift @@ -77,7 +77,8 @@ where { @inlinable public var underestimatedCount: Int { - _base.underestimatedCount + // We cannot know how many items the predicate will reject. + 0 } @inlinable @@ -96,14 +97,15 @@ where into target: inout OutputSpan ) throws(Failure) -> Int { let startCount = target.count + var reachedEnd = false repeat { let prevCount = target.count defer { target._remove(from: prevCount, where: { !_isIncluded($0) }) } try _base.generate(into: &target) - guard target.isFull else { break } - } while target.count == startCount + reachedEnd = !target.isFull + } while !reachedEnd && !target.isFull return target.count - startCount } From abddfb7ced085f3b065f575bc065628a8f11602e Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 21 Oct 2026 17:29:03 -0700 Subject: [PATCH 3/5] Producer.map: Saturate generate(into:) target --- .../Protocols/Producer/Producer+Map.swift | 23 +++++++++++-------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/Sources/ContainersPreview/Protocols/Producer/Producer+Map.swift b/Sources/ContainersPreview/Protocols/Producer/Producer+Map.swift index cadc7d02..3f2fdf80 100644 --- a/Sources/ContainersPreview/Protocols/Producer/Producer+Map.swift +++ b/Sources/ContainersPreview/Protocols/Producer/Producer+Map.swift @@ -93,18 +93,23 @@ extension ConsumingMapProducer: Producer where Base: ~Copyable & ~Escapable { public mutating func generate( into target: inout OutputSpan ) throws(Failure) -> Int { - let c = Swift.min(target.freeCapacity, _producerBufferSize) - return try withTemporaryAllocation( - of: Base.Element.self, capacity: c - ) { source throws(Failure) in - let result = try _base.generate(into: &source) - try source._consumeAll { src throws(Failure) in - while !src.isEmpty { - target.append(try _transform(src.removeFirst())) + let startCount = target.count + var done = false + while !target.isFull, !done { + let c = Swift.min(target.freeCapacity, _producerBufferSize) + try withTemporaryAllocation( + of: Base.Element.self, capacity: c + ) { source throws(Failure) in + try _base.generate(into: &source) + done = !source.isFull + try source._consumeAll { src throws(Failure) in + while !src.isEmpty { + target.append(try _transform(src.removeFirst())) + } } } - return result } + return target.count - startCount } @inlinable From 1e51781091b80c811d2cdbbe2d05ceab43056790 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 21 Oct 2026 17:29:42 -0700 Subject: [PATCH 4/5] UniqueSet.init(minimumCapacity:from:): Make sure we allocate storage for at least `minimumCapacity` items --- .../ContainersPreview/Conformances/UniqueSet+Container.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/ContainersPreview/Conformances/UniqueSet+Container.swift b/Sources/ContainersPreview/Conformances/UniqueSet+Container.swift index 84c272cb..01dbe2e4 100644 --- a/Sources/ContainersPreview/Conformances/UniqueSet+Container.swift +++ b/Sources/ContainersPreview/Conformances/UniqueSet+Container.swift @@ -64,7 +64,7 @@ extension UniqueSet where Element: ~Copyable { { let c = producer.underestimatedCount if let minimumCapacity { - self.init(minimumCapacity: Swift.min(minimumCapacity, c)) + self.init(minimumCapacity: Swift.max(minimumCapacity, c)) } else { self.init(minimumCapacity: c) } From 6f813c3497cc1d59d9980a31d38aa31781c5b480 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 21 Oct 2026 17:30:09 -0700 Subject: [PATCH 5/5] Update tests --- Tests/ContainersTests/ProducerTests.swift | 100 ++++++++++++++++++++++ Tests/DequeTests/UniqueDequeTests.swift | 2 +- 2 files changed, 101 insertions(+), 1 deletion(-) create mode 100644 Tests/ContainersTests/ProducerTests.swift diff --git a/Tests/ContainersTests/ProducerTests.swift b/Tests/ContainersTests/ProducerTests.swift new file mode 100644 index 00000000..24dac16b --- /dev/null +++ b/Tests/ContainersTests/ProducerTests.swift @@ -0,0 +1,100 @@ +//===----------------------------------------------------------------------===// +// +// 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 InternalCollectionsUtilities +import SpanPreview +#endif +import ContainersPreview + +#if compiler(>=6.4) && UnstableContainersPreview + +@available(SwiftStdlib 6.4, *) +final class ProducerTests: CollectionTestCase { + /// A producer over `0 ..< count`. + @_lifetime(immortal) + func range(_ count: Int) -> UnfoldProducer { + producer(state: 0) { (state: inout Int) -> Int? in + guard state < count else { return nil } + defer { state += 1 } + return state + } + } + + /// Generate into a span of the given capacity, returning the generated items + /// and the value returned by `generate(into:)`. + func generate & ~Copyable & ~Escapable>( + _ producer: inout P, capacity: Int + ) -> (returned: Int, items: [Int]) { + var items: [Int] = [] + let returned = withUnsafeTemporaryAllocation( + of: Int.self, capacity: capacity + ) { buffer in + var span = unsafe OutputSpan(buffer: buffer, initializedCount: 0) + let returned = producer.generate(into: &span) + span._consumeAll { src in + while let item = src.popFirst() { items.append(item) } + } + return returned + } + return (returned, items) + } + + func test_map_generate_fills_target() { + withEvery("capacity", in: [1, 7, 8, 9, 16, 33, 100, 150]) { capacity in + var p = range(100).map { $0 * 2 } + let (returned, items) = generate(&p, capacity: capacity) + let expected = Swift.min(capacity, 100) + expectEqual(returned, expected) + expectEqualElements(items, (0 ..< expected).map { $0 * 2 }) + } + } + + func test_filter_generate_fills_target() { + withEvery("capacity", in: [1, 7, 8, 9, 16, 33, 50, 80]) { capacity in + var p = range(100).filter { $0 % 2 == 0 } + let (returned, items) = generate(&p, capacity: capacity) + let expected = Swift.min(capacity, 50) + expectEqual(returned, expected) + expectEqualElements(items, (0 ..< expected).map { $0 * 2 }) + } + } + + func test_filter_underestimatedCount() { + let p = range(100).filter { $0 % 2 == 0 } + expectEqual(p.underestimatedCount, 0) + } + + func test_reduce_over_map_and_filter() { + expectEqual(range(100).map { $0 }.reduce(0, +), 4950) + expectEqual(range(100).filter { $0 % 2 == 0 }.reduce(0, +), 2450) + } + + func test_default_skip_by_does_not_overshoot() { + withEvery("n", in: [1, 5, 8, 10, 16, 40, 100, 150]) { n in + var p = range(100).filter { $0 % 2 == 0 } + var remaining = n + p.skip(by: &remaining) + let skipped = Swift.min(n, 50) + expectEqual(remaining, n - skipped) + expectEqual(p.next(), skipped < 50 ? skipped * 2 : nil) + } + } +} + +#endif diff --git a/Tests/DequeTests/UniqueDequeTests.swift b/Tests/DequeTests/UniqueDequeTests.swift index c721779e..65bde65e 100644 --- a/Tests/DequeTests/UniqueDequeTests.swift +++ b/Tests/DequeTests/UniqueDequeTests.swift @@ -243,7 +243,7 @@ final class UniqueDequeTests: CollectionTestCase { for item in existing { deque.append(item) } var items = tracker.instances(for: 0 ..< newCount) - var producer = CustomProducer, Never> { _ in + let producer = CustomProducer, Never> { _ in guard !items.isEmpty else { return nil } return items.removeFirst() }