From b75bd4ef019eb766c84d8260a667739f77858115 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 22 Apr 2026 15:12:55 -0700 Subject: [PATCH] [BasicContainers] RigidSet.insert(maximumCount:from:): Fix spurious capacity overflow caused by incorrect accounting --- .../RigidSet/RigidSet+Insertions.swift | 2 +- .../BasicContainersTests/RigidSetTests.swift | 30 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/Sources/BasicContainers/RigidSet/RigidSet+Insertions.swift b/Sources/BasicContainers/RigidSet/RigidSet+Insertions.swift index edb42fb0..e7aea1df 100644 --- a/Sources/BasicContainers/RigidSet/RigidSet+Insertions.swift +++ b/Sources/BasicContainers/RigidSet/RigidSet+Insertions.swift @@ -198,10 +198,10 @@ extension RigidSet where Element: ~Copyable { while remainder > 0 { var span = drain.drainNext(maximumCount: remainder) guard !span.isEmpty else { break } + remainder &-= span.count while let next = span.popFirst() { self.insert(next) } - remainder &-= span.count } } #endif diff --git a/Tests/BasicContainersTests/RigidSetTests.swift b/Tests/BasicContainersTests/RigidSetTests.swift index 5385f51a..90de1c3c 100644 --- a/Tests/BasicContainersTests/RigidSetTests.swift +++ b/Tests/BasicContainersTests/RigidSetTests.swift @@ -428,6 +428,36 @@ class RigidSetTests: CollectionTestCase { } } } + + func test_insert_drain_maximumCount() { + withEvery("capacity", in: [5, 10, 100]) { capacity in + withEvery("drainLength", in: [0, 1, 2, 4, 10, capacity]) { drainLength in + withEvery("maxCount", in: [0, 1, 2, 3, 5]) { maxCount in + withEvery("chunkSize", in: [1, 2, 3, 10]) { chunkSize in + withLifetimeTracking { tracker in + var s = RigidSet>(capacity: capacity) + + var i = 0 + var drain = CustomDrain>( + underestimatedCount: 0, + chunkSize: chunkSize + ) { + guard i < drainLength else { return nil } + defer { i += 1 } + return tracker.instance(for: i) + } + s.insert(maximumCount: maxCount, from: &drain) + expectConsistentSet(s) + + let expectedCount = Swift.min(maxCount, drainLength) + expectEqual(s.count, expectedCount) + expectEqual(i, expectedCount) + } + } + } + } + } + } #endif func test_remove_one() {