Merge pull request #777 from SwastikTripathi/fix/unique-deque-prepend-producer-order

[UniqueDeque] Fix prepend(from:) reversing batch order across producer passes
This commit is contained in:
Karoy Lorentey authored and GitHub committed 2026-10-21 16:33:30 -07:00
commit 6572a1b7f4
3 files changed
+35 -3

No files matched your search

@@ -124,13 +124,17 @@ extension UniqueDeque where Element: ~Copyable {
) throws(E) -> Range<Int>
where P.Element: ~Copyable
{
// FIXME: This is slower than it should be because it is moving elements
// unnecessarily. Forward to append then rotate instead; additionally,
// add a CountedProducer overload that avoids having to move items at all.
var done = false
var added = 0
while !done {
let c = Swift.max(producer.underestimatedCount, 1)
_ensureFreeCapacity(c)
_ = unsafe try _storage._handle.uncheckedPrepend(
addingCount: freeCapacity
_ = unsafe try _storage._handle.uncheckedInsert(
addingCount: freeCapacity,
at: added
) { target throws(E) in
let origCount = target.count
defer {
+1 -1
View File
@@ -1314,7 +1314,7 @@ extension _UnsafeDequeHandle where Element: ~Copyable {
@available(SwiftStdlib 5.0, *)
extension _UnsafeDequeHandle where Element: ~Copyable {
@_alwaysEmitIntoClient
internal mutating func uncheckedInsert<E: Error>(
package mutating func uncheckedInsert<E: Error>(
addingCount newItemCount: Int,
at offset: Int,
initializingWith body: (inout OutputSpan<Element>) throws(E) -> Void
+28
View File
@@ -230,6 +230,34 @@ final class UniqueDequeTests: CollectionTestCase {
}
}
#if compiler(>=6.4) && UnstableContainersPreview
@available(SwiftStdlib 6.4, *)
func test_prepend_Producer_preserves_order() {
// Regression test for https://github.com/apple/swift-collections/issues/763:
// prepend(from:) was inserting each batch at index 0, reversing batch order.
withEvery("existingCount", in: [0, 1, 3]) { existingCount in
withEvery("newCount", in: [0, 1, 7, 8, 9, 20]) { newCount in
withLifetimeTracking { tracker in
var deque = UniqueDeque<LifetimeTracked<Int>>()
let existing = tracker.instances(for: 1000 ..< 1000 + existingCount)
for item in existing { deque.append(item) }
var items = tracker.instances(for: 0 ..< newCount)
var producer = CustomProducer<LifetimeTracked<Int>, Never> { _ in
guard !items.isEmpty else { return nil }
return items.removeFirst()
}
deque.prepend(from: producer)
let expected = tracker.instances(for: 0 ..< newCount)
+ tracker.instances(for: 1000 ..< 1000 + existingCount)
expectUniqueDequeContents(deque, equalTo: expected)
}
}
}
}
#endif
func test_growth() {
let expectedCapacities = [
0, 1, 2, 3, 5, 8, 12, 18, 27, 41, 62, 93, 140, 210, 315