diff --git a/Sources/BasicContainers/RigidSet/RigidSet+Insertions.swift b/Sources/BasicContainers/RigidSet/RigidSet+Insertions.swift index 3fd45557..76f3567b 100644 --- a/Sources/BasicContainers/RigidSet/RigidSet+Insertions.swift +++ b/Sources/BasicContainers/RigidSet/RigidSet+Insertions.swift @@ -155,6 +155,11 @@ extension RigidSet where Element: ~Copyable { } #else output.withUnsafeMutableBufferPointer { buffer, count in + if count < c { + remainder = 0 + } else { + remainder &-= count + } for i in 0 ..< count { self.insert(buffer.moveElement(from: i)) } diff --git a/Tests/BasicContainersTests/RigidSetTests.swift b/Tests/BasicContainersTests/RigidSetTests.swift index 768ca981..d134c11c 100644 --- a/Tests/BasicContainersTests/RigidSetTests.swift +++ b/Tests/BasicContainersTests/RigidSetTests.swift @@ -110,6 +110,45 @@ class RigidSetTests: CollectionTestCase { } } + func test_init_capacity_initializingWith() { + // Regression test for https://github.com/apple/swift-collections/issues/774: + // without the `UnstableContainersPreview` trait, `insert(addingCount:initializingWith:)` + // never terminated because the batch loop didn't update its `remainder` bookkeeping. + var calls = 0 + let fillTwo: (inout OutputSpan) -> Void = { span in + calls += 1 + span.append(1) + span.append(2) + } + + // Exact fill: the batch fills its whole span. + let a = RigidSet(capacity: 2, initializingWith: fillTwo) + expectEqual(a.count, 2) + expectEqual(calls, 1) + expectTrue(a.contains(1)) + expectTrue(a.contains(2)) + expectConsistentSet(a) + + // Short fill: the initializer stops before the span is full. + calls = 0 + let b = RigidSet(capacity: 4, initializingWith: fillTwo) + expectEqual(b.count, 2) + expectEqual(calls, 1) + expectConsistentSet(b) + + calls = 0 + var c = RigidSet(capacity: 8) + c.insert(addingCount: 5, initializingWith: fillTwo) + expectEqual(c.count, 2) + expectEqual(calls, 1) + expectConsistentSet(c) + + calls = 0 + let d = UniqueSet(minimumCapacity: 4, initializingWith: fillTwo) + expectEqual(d.count, 2) + expectEqual(calls, 1) + } + func test_insert_one_large() { withLifetimeTracking { tracker in var s = RigidSet>(capacity: 20)