Merge pull request #789 from lorentey/saturate-producer-buffers

Saturate producer buffers
This commit is contained in:
Karoy Lorentey authored and GitHub committed 2026-10-21 18:42:14 -07:00
commit da4ca36d4a
6 files changed
+132 -23

No files matched your search

@@ -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)
}
@@ -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<Element>
) 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
}
@@ -93,18 +93,23 @@ extension ConsumingMapProducer: Producer where Base: ~Copyable & ~Escapable {
public mutating func generate(
into target: inout OutputSpan<Element>
) 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
@@ -133,8 +133,8 @@ public protocol Producer<Element, Failure>: ~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
}
}
}
+100
View File
@@ -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<Int, Never, Int> {
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<P: Producer<Int, Never> & ~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
+1 -1
View File
@@ -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<LifetimeTracked<Int>, Never> { _ in
let producer = CustomProducer<LifetimeTracked<Int>, Never> { _ in
guard !items.isEmpty else { return nil }
return items.removeFirst()
}