diff --git a/Package.swift b/Package.swift index e61884ad..669453f2 100644 --- a/Package.swift +++ b/Package.swift @@ -219,6 +219,7 @@ let targets: [CustomTarget] = [ "InternalCollectionsUtilities", "ContainersPreview", "BasicContainers", + "DequeModule", "SpanPreview", ]), .target( diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Testing.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Testing.swift index 92135f1e..bb69f9b8 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Testing.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Testing.swift @@ -33,7 +33,7 @@ extension RigidDeque where Element: ~Copyable { } @available(SwiftStdlib 5.0, *) -extension RigidDeque { +extension RigidDeque where Element: ~Copyable { /// Constructs a deque instance of the specified contents and layout. Exposed /// as public to allow exhaustive input/output tests for `RigidDeque` members. /// @@ -43,15 +43,12 @@ extension RigidDeque { package init( _capacity capacity: Int, startSlot: Int, - copying contents: some Sequence + initializingWith initializer: (inout OutputSpan) -> Void ) { - let contents = Array(contents) - self.init(capacity: capacity) unsafe _handle._startSlot = _handle.slot(_handle.startSlot, offsetBy: startSlot) - self.append(copying: contents) + self.append(addingCount: capacity, initializingWith: initializer) assert(self.capacity == capacity) assert(self._startSlot == startSlot) - assert(self.count == contents.count) } } diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift index 55edce36..51d713ea 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift @@ -362,6 +362,7 @@ extension UniqueDeque /*where Element: Copyable*/ { /// invocations on the same deque. @inlinable @_alwaysEmitIntoClient + @discardableResult public mutating func prepend( copying items: some Collection ) -> Range { diff --git a/Tests/BasicContainersTests/RigidArrayTests.swift b/Tests/BasicContainersTests/RigidArrayTests.swift index 76eb681d..5c1e3ff1 100644 --- a/Tests/BasicContainersTests/RigidArrayTests.swift +++ b/Tests/BasicContainersTests/RigidArrayTests.swift @@ -1336,8 +1336,11 @@ class RigidArrayTests: CollectionTestCase { var a = tracker.rigidArray(layout: layout) let rigidAddition = StaccatoContainer( - contents: tracker.instances(for: addition), - spanCounts: [spanCount]) + count: addition.count, + spanCounts: [spanCount] + ) { + tracker.instance(for: addition[$0]) + } a.insert(copying: rigidAddition, at: i) expectRigidArrayContents( @@ -1571,8 +1574,11 @@ class RigidArrayTests: CollectionTestCase { var a = tracker.rigidArray(layout: layout) let trackedAddition = StaccatoContainer( - contents: RigidArray(copying: addition.map { tracker.instance(for: $0) }), - spanCounts: [spanCount]) + count: addition.count, + spanCounts: [spanCount] + ) { + tracker.instance(for: addition[$0]) + } a.replaceSubrange(range, copying: trackedAddition) expectRigidArrayContents( diff --git a/Tests/ContainersTests/MutableContainer_Update_Tests.swift b/Tests/ContainersTests/MutableContainer_Update_Tests.swift index a383e0ac..cb45b7f2 100644 --- a/Tests/ContainersTests/MutableContainer_Update_Tests.swift +++ b/Tests/ContainersTests/MutableContainer_Update_Tests.swift @@ -25,102 +25,6 @@ import DequeModule import ContainersPreview #if compiler(>=6.4) && UnstableContainersPreview -#if !COLLECTIONS_SINGLE_MODULE -// For testing piecewise contiguous MutableContainer operations. -// (FIXME: Use something like an extended StaccatoContainer instead.) -struct DequeLayout: Hashable, CustomStringConvertible { - let capacity: Int - let startSlot: Int - let count: Int - let startValue: Int - - init(capacity: Int, startSlot: Int, count: Int, startValue: Int = 0) { - self.capacity = capacity - self.startSlot = startSlot - self.count = count - self.startValue = startValue - } - - var freeCapacity: Int { capacity - count } - var valueRange: Range { startValue ..< startValue + count } - - var description: String { - var result = "DequeLayout(capacity: \(capacity), startSlot: \(startSlot), count: \(count)" - if count > 0 { - result += ", startValue: \(startValue)" - } - result += ")" - return result - } - - var isWrapped: Bool { - startSlot + count > capacity - } -} - -@available(SwiftStdlib 5.0, *) -internal struct RigidTestData: ~Copyable { - var deque: RigidDeque - var contents: [Element] - - init(_ deque: consuming RigidDeque, _ contents: [Element]) { - self.deque = deque - self.contents = contents - } - - mutating func take() -> RigidDeque { - exchange(&self.deque, with: .init()) - } - - consuming func consume() -> RigidDeque { - exchange(&self.deque, with: .init()) - } -} - -extension LifetimeTracker { - @available(SwiftStdlib 5.0, *) - func rigidDeque( - with layout: DequeLayout - ) -> RigidTestData> { - let contents = self.instances(for: layout.valueRange) - let deque = RigidDeque(layout: layout, contents: contents) - return RigidTestData(deque, contents) - } -} - -@available(SwiftStdlib 5.0, *) -extension RigidDeque where Element: ~Copyable { - init>(layout: DequeLayout, contents: C) { - precondition(contents.count == layout.count) - self.init( - _capacity: layout.capacity, - startSlot: layout.startSlot, - copying: contents) - } -} -#endif - -private func withEveryFullDeque( - _ label: String, - ofCapacities capacities: C, - startValue: Int = 0, - file: StaticString = #filePath, line: UInt = #line, - _ body: (DequeLayout) throws -> Void -) rethrows -> Void where C.Element == Int { - // Exhaustive tests for all deque layouts of various capacities - for capacity in capacities { - for startSlot in 0 ..< capacity { - let layout = DequeLayout( - capacity: capacity, - startSlot: startSlot, - count: capacity, - startValue: startValue) - let entry = TestContext.current.push("\(label): \(layout)", file: file, line: line) - defer { TestContext.current.pop(entry) } - try body(layout) - } - } -} @available(SwiftStdlib 6.4, *) final class MutableContainer_Update_Tests: CollectionTestCase { @@ -132,9 +36,9 @@ final class MutableContainer_Update_Tests: CollectionTestCase { let replacements1 = layout.count ..< (layout.count + subrange.count) expected.replaceSubrange(subrange, with: replacements1) - var actual = tracker.rigidDeque(with: layout) + var actual = RigidDeque(layout: layout) { tracker.instance(for: $0) } var i = layout.count - actual.deque.updateSubrange(subrange) { span in + actual.updateSubrange(subrange) { span in var items = UniqueArray(copying: tracker.instances( count: span.count, generator: { i + $0 })) i += span.count @@ -142,7 +46,7 @@ final class MutableContainer_Update_Tests: CollectionTestCase { span._updateAll(moving: &src) } } - expectIterablePayloads(actual.deque, equalTo: expected) + expectIterablePayloads(actual, equalTo: expected) } } } @@ -162,7 +66,7 @@ final class MutableContainer_Update_Tests: CollectionTestCase { start ..< end, with: replacements1.prefix(end - start)) - var actual = tracker.rigidDeque(with: layout) + var actual = RigidDeque(layout: layout) { tracker.instance(for: $0) } var replacements2 = CustomProducer, Never>( underestimatedCount: 0, ) { offset in @@ -171,9 +75,9 @@ final class MutableContainer_Update_Tests: CollectionTestCase { } var i = start - actual.deque.updateElements(after: &i, from: &replacements2) + actual.updateElements(after: &i, from: &replacements2) - expectIterablePayloads(actual.deque, equalTo: expected) + expectIterablePayloads(actual, equalTo: expected) expectEqual(i, end) } } @@ -194,7 +98,7 @@ final class MutableContainer_Update_Tests: CollectionTestCase { start ..< end, with: replacements1.prefix(end - start)) - var actual = tracker.rigidDeque(with: layout) + var actual = RigidDeque(layout: layout) { tracker.instance(for: $0) } var replacements2 = CustomCountedProducer, Never>( count: length, chunkSize: chunkSize @@ -203,9 +107,9 @@ final class MutableContainer_Update_Tests: CollectionTestCase { } var i = start - actual.deque.updateElements(after: &i, from: &replacements2) + actual.updateElements(after: &i, from: &replacements2) - expectIterablePayloads(actual.deque, equalTo: expected) + expectIterablePayloads(actual, equalTo: expected) expectEqual(i, end) } } @@ -223,7 +127,7 @@ final class MutableContainer_Update_Tests: CollectionTestCase { let replacements1 = targetLayout.count ..< (targetLayout.count + subrange.count) expected.replaceSubrange(subrange, with: replacements1) - var actual = tracker.rigidDeque(with: targetLayout).consume() + var actual = RigidDeque(layout: targetLayout) { tracker.instance(for: $0) } let replacements2 = CustomCountedProducer, Never>( count: subrange.count, chunkSize: chunkSize @@ -247,13 +151,14 @@ final class MutableContainer_Update_Tests: CollectionTestCase { startValue: targetLayout.count ) { sourceLayout in withLifetimeTracking { tracker in - var expected = Array(0 ..< targetLayout.count) - let replacements1 = targetLayout.count ..< (targetLayout.count + subrange.count) - expected.replaceSubrange(subrange, with: replacements1) + var expected = Array(targetLayout.valueRange) + expected.replaceSubrange(subrange, with: sourceLayout.valueRange) - var actual = tracker.rigidDeque(with: targetLayout).consume() - var replacements2 = tracker.rigidDeque(with: sourceLayout).consume() - actual.updateSubrange(subrange, from: replacements2.consumeAll()) + var actual = RigidDeque(layout: targetLayout) { tracker.instance(for: $0) } + var replacements = RigidDeque(layout: sourceLayout) { + tracker.instance(for: $0) + } + actual.updateSubrange(subrange, from: replacements.consumeAll()) expectIterablePayloads(actual, equalTo: expected) } @@ -277,7 +182,7 @@ final class MutableContainer_Update_Tests: CollectionTestCase { start ..< end, with: replacements1.prefix(end - start)) - var actual = tracker.rigidDeque(with: layout) + var actual = RigidDeque(layout: layout) { tracker.instance(for: $0) } var replacements2 = CustomBorrowingIterator, Never>( underestimatedCount: 0, chunkSize: chunkSize @@ -287,9 +192,9 @@ final class MutableContainer_Update_Tests: CollectionTestCase { } var i = start - actual.deque.updateElements(after: &i, copying: &replacements2) + actual.updateElements(after: &i, copying: &replacements2) - expectIterablePayloads(actual.deque, equalTo: expected) + expectIterablePayloads(actual, equalTo: expected) expectEqual(i, end) } } @@ -311,8 +216,10 @@ final class MutableContainer_Update_Tests: CollectionTestCase { let replacements1 = targetLayout.count ..< (targetLayout.count + subrange.count) expected.replaceSubrange(subrange, with: replacements1) - var actual = tracker.rigidDeque(with: targetLayout).consume() - let replacements2 = tracker.rigidDeque(with: sourceLayout).consume() + var actual = RigidDeque(layout: targetLayout) { tracker.instance(for: $0) } + let replacements2 = RigidDeque(layout: sourceLayout) { + tracker.instance(for: $0) + } actual.updateSubrange(subrange, copying: replacements2) expectIterablePayloads(actual, equalTo: expected) diff --git a/Tests/DequeTests/DequeInternals.swift b/Tests/DequeTests/DequeInternals.swift index 948e512b..be943e62 100644 --- a/Tests/DequeTests/DequeInternals.swift +++ b/Tests/DequeTests/DequeInternals.swift @@ -52,40 +52,6 @@ internal struct UniqueTestData: ~Copyable { } } -internal struct DequeLayout: Hashable, CustomStringConvertible { - let capacity: Int - let startSlot: Int - let count: Int - let startValue: Int - - init(capacity: Int, startSlot: Int, count: Int, startValue: Int = 0) { - self.capacity = capacity - self.startSlot = startSlot - self.count = count - self.startValue = startValue - } - - var freeCapacity: Int { capacity - count } - var valueRange: Range { startValue ..< startValue + count } - - var description: String { - var result = "DequeLayout(capacity: \(capacity), startSlot: \(startSlot), count: \(count)" - if count > 0 { - result += ", startValue: \(startValue)" - } - result += ")" - return result - } - - var isWrapped: Bool { - startSlot + count > capacity - } - - var wrapIndex: Int? { - isWrapped ? capacity - startSlot : nil - } -} - extension Deque { init(layout: DequeLayout, contents: C) where C.Element == Element { precondition(contents.count == layout.count) @@ -93,14 +59,6 @@ extension Deque { } } -@available(SwiftStdlib 5.0, *) -extension RigidDeque { - init(layout: DequeLayout, contents: C) where C.Element == Element { - precondition(contents.count == layout.count) - self.init(_capacity: layout.capacity, startSlot: layout.startSlot, copying: contents) - } -} - extension LifetimeTracker { func deque( with layout: DequeLayout @@ -115,7 +73,8 @@ extension LifetimeTracker { with layout: DequeLayout ) -> RigidTestData> { let contents = self.instances(for: layout.valueRange) - let deque = RigidDeque(layout: layout, contents: contents) + var it = contents.makeIterator() + let deque = RigidDeque(layout: layout) { _ in it.next()! } return RigidTestData(deque, contents) } @@ -124,31 +83,8 @@ extension LifetimeTracker { with layout: DequeLayout ) -> UniqueTestData> { let contents = self.instances(for: layout.valueRange) - let deque = RigidDeque(layout: layout, contents: contents) + var it = contents.makeIterator() + let deque = RigidDeque(layout: layout) { _ in it.next()! } return UniqueTestData(deque, contents) } } - -func withEveryDeque( - _ label: String, - ofCapacities capacities: C, - startValue: Int = 0, - file: StaticString = #filePath, line: UInt = #line, - _ body: (DequeLayout) throws -> Void -) rethrows -> Void where C.Element == Int { - // Exhaustive tests for all deque layouts of various capacities - for capacity in capacities { - for startSlot in 0 ..< capacity { - for count in 0 ... capacity { - let layout = DequeLayout( - capacity: capacity, - startSlot: startSlot, - count: count, - startValue: startValue) - let entry = TestContext.current.push("\(label): \(layout)", file: file, line: line) - defer { TestContext.current.pop(entry) } - try body(layout) - } - } - } -} diff --git a/Tests/DequeTests/RigidDequeTests.swift b/Tests/DequeTests/RigidDequeTests.swift index 45176298..51e7e00e 100644 --- a/Tests/DequeTests/RigidDequeTests.swift +++ b/Tests/DequeTests/RigidDequeTests.swift @@ -541,7 +541,7 @@ final class RigidDequeTests: CollectionTestCase { @available(SwiftStdlib 6.4, *) func test_nextSpan_after() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in - let d = RigidDeque(layout: layout, contents: layout.valueRange) + let d = RigidDeque(layout: layout) withEvery("i", in: 0 ... layout.count) { i in var expected = layout.count if let w = layout.wrapIndex, i < w { @@ -562,7 +562,7 @@ final class RigidDequeTests: CollectionTestCase { @available(SwiftStdlib 6.4, *) func test_nextSpan_after_maxCount() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in - let d = RigidDeque(layout: layout, contents: layout.valueRange) + let d = RigidDeque(layout: layout) withEvery("i", in: 0 ... layout.count) { i in withEvery( "maxCount", @@ -589,7 +589,7 @@ final class RigidDequeTests: CollectionTestCase { @available(SwiftStdlib 6.4, *) func test_nextSpan_after_maxCount_limitedBy() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in - let d = RigidDeque(layout: layout, contents: layout.valueRange) + let d = RigidDeque(layout: layout) withEvery("i", in: 0 ... layout.count) { i in withEvery( "maxCount", @@ -620,7 +620,7 @@ final class RigidDequeTests: CollectionTestCase { @available(SwiftStdlib 6.4, *) func test_spanBoundary_before() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in - let d = RigidDeque(layout: layout, contents: layout.valueRange) + let d = RigidDeque(layout: layout) withEvery("i", in: 0 ... layout.count) { i in let r = d.spanBoundary(before: i) expectGreaterThanOrEqual(r.distance, 0) @@ -639,7 +639,7 @@ final class RigidDequeTests: CollectionTestCase { @available(SwiftStdlib 6.4, *) func test_spanBoundary_before_maxDistance() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in - let d = RigidDeque(layout: layout, contents: layout.valueRange) + let d = RigidDeque(layout: layout) withEvery("i", in: 0 ... layout.count) { i in withEvery( "maxDistance", @@ -665,7 +665,7 @@ final class RigidDequeTests: CollectionTestCase { @available(SwiftStdlib 6.4, *) func test_spanBoundary_before_maxDistance_limitedBy() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in - let d = RigidDeque(layout: layout, contents: layout.valueRange) + let d = RigidDeque(layout: layout) withEvery("i", in: 0 ... layout.count) { i in withEvery( "maxDistance", @@ -976,7 +976,7 @@ final class RigidDequeTests: CollectionTestCase { #if compiler(>=6.4) && UnstableContainersPreview @available(SwiftStdlib 6.4, *) - func test_append_Producer() { + func test_append_Producer_full() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5]) { layout in withEvery("producerSize", in: 0 ..< layout.freeCapacity) { producerSize in withLifetimeTracking { tracker in @@ -1011,11 +1011,11 @@ final class RigidDequeTests: CollectionTestCase { var extras = tracker.instances(for: 0 ..< producerSize) - data.contents.insert(contentsOf: extras.reversed(), at: 0) + data.contents.insert(contentsOf: extras, at: 0) var producer = CustomProducer, TestError> { offset throws(TestError) in guard !extras.isEmpty else { throw TestError(23) } - return extras.removeLast() + return extras.removeFirst() } expectThrows { () throws(TestError) in try data.deque.prepend(addingCount: layout.freeCapacity, from: &producer) @@ -1042,11 +1042,11 @@ final class RigidDequeTests: CollectionTestCase { var extras = tracker.instances(for: 0 ..< producerSize) - data.contents.append(contentsOf: extras.reversed()) + data.contents.append(contentsOf: extras) var producer = CustomProducer, TestError> { offset throws(TestError) in guard !extras.isEmpty else { throw TestError(23) } - return extras.removeLast() + return extras.removeFirst() } expectThrows { () throws(TestError) in @@ -1205,51 +1205,59 @@ final class RigidDequeTests: CollectionTestCase { } } - func test_prepend_BridgedArray() { - // https://github.com/apple/swift-collections/issues/27 +#if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) + func test_prepend_copying_StaccatoContainer() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in - withEvery("c", in: 0 ..< layout.freeCapacity) { c in - var contents: [NSObject] = (0 ..< layout.count).map { _ in NSObject() } - var deque = RigidDeque(layout: layout, contents: contents) - guard c <= deque.freeCapacity else { return } - let extra: [NSObject] = (0 ..< c) - .map { _ in NSObject() } - .withUnsafeBufferPointer { buffer in - unsafe NSArray(objects: buffer.baseAddress, count: buffer.count) as! [NSObject] - } - contents.insert(contentsOf: extra, at: 0) - deque.prepend(copying: extra) - expectRigidDequeContents( - deque, - equivalentTo: contents, - by: ==, - printer: { "\($0)" }) - } - } - } + withEvery("count", in: 0 ... layout.freeCapacity) { count in + withEvery("spanCounts", in: [ + [1], + [1, 2, 3], + [3, 5, 7], + [Int.max], + ] as [[Int]]) { spanCounts in + var expected = Array(layout.valueRange) + expected.insert(contentsOf: layout.count ..< layout.count + count, at: 0) - func test_append_BridgedArray() { - // https://github.com/apple/swift-collections/issues/27 - withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in - withEvery("c", in: 0 ..< layout.freeCapacity) { c in - var contents: [NSObject] = (0 ..< layout.count).map { _ in NSObject() } - var deque = RigidDeque(layout: layout, contents: contents) - guard c <= deque.freeCapacity else { return } - let extra: [NSObject] = (0 ..< c) - .map { _ in NSObject() } - .withUnsafeBufferPointer { buffer in - unsafe NSArray(objects: buffer.baseAddress, count: buffer.count) as! [NSObject] + var actual = RigidDeque(layout: layout) + let additions = StaccatoContainer(count: count, spanCounts: spanCounts) { + layout.count + $0 } - contents.append(contentsOf: extra) - deque.append(copying: extra) - expectRigidDequeContents( - deque, - equivalentTo: contents, - by: ==, - printer: { "\($0)" }) + actual.prepend(copying: additions) + + expectRigidDequeContents(actual, equalTo: expected) + } } } } +#endif + +#if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) + func test_append_copying_StaccatoContainer() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withEvery("count", in: 0 ... layout.freeCapacity) { count in + withEvery("spanCounts", in: [ + [1], + [1, 2, 3], + [3, 5, 7], + [Int.max], + ] as [[Int]]) { spanCounts in + var expected = Array(layout.valueRange) + expected.append(contentsOf: layout.count ..< layout.count + count) + + var actual = RigidDeque(layout: layout) + let additions = StaccatoContainer(count: count, spanCounts: spanCounts) { + layout.count + $0 + } + actual.append(copying: additions) + + expectRigidDequeContents(actual, equalTo: expected) + } + } + } + } +#endif func test_insert() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in @@ -1752,7 +1760,7 @@ final class RigidDequeTests: CollectionTestCase { func test_nextMutableSpan_maxCount_limitedBy() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withEvery("maxCount", in: [1, 2, 3, 5, 100]) { maxCount in - var deque = RigidDeque(layout: layout, contents: layout.valueRange) + var deque = RigidDeque(layout: layout) var index = deque.startIndex var totalSeen = 0 while index < deque.endIndex { diff --git a/Tests/DequeTests/UniqueDequeTests.swift b/Tests/DequeTests/UniqueDequeTests.swift index 65bde65e..ebf67a22 100644 --- a/Tests/DequeTests/UniqueDequeTests.swift +++ b/Tests/DequeTests/UniqueDequeTests.swift @@ -270,4 +270,505 @@ final class UniqueDequeTests: CollectionTestCase { } expectEqualElements(actualCapacities.sorted(), expectedCapacities) } + + func test_prepend() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withLifetimeTracking { tracker in + var data = tracker.uniqueDeque(with: layout) + let extra = tracker.instance(for: layout.count) + data.contents.insert(extra, at: 0) + data.deque.prepend(extra) + expectUniqueDequeContents(data.deque, equalTo: data.contents) + } + } + } + + func test_append() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withLifetimeTracking { tracker in + var data = tracker.uniqueDeque(with: layout) + let extra = tracker.instance(for: layout.count) + data.contents.append(extra) + data.deque.append(extra) + expectUniqueDequeContents(data.deque, equalTo: data.contents) + } + } + } + + func test_prepend_initializingWith_full() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withEvery("prependCount", in: 0 ..< layout.freeCapacity) { prependCount in + withLifetimeTracking { tracker in + var data = tracker.uniqueDeque(with: layout) + + let extras = tracker.instances(for: layout.count ..< layout.count + prependCount) + + data.contents.insert(contentsOf: extras, at: 0) + + var i = 0 + data.deque.prepend(addingCount: prependCount) { target in + while !target.isFull { + target.append(extras[i]) + i += 1 + } + } + + expectUniqueDequeContents(data.deque, equalTo: data.contents) + } + } + } + } + + func test_append_initializingWith_full() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withEvery("prependCount", in: 0 ..< layout.freeCapacity) { prependCount in + withLifetimeTracking { tracker in + var data = tracker.uniqueDeque(with: layout) + + let extras = tracker.instances(for: layout.count ..< layout.count + prependCount) + + data.contents.append(contentsOf: extras) + + var i = 0 + data.deque.append(addingCount: prependCount) { target in + while !target.isFull { + target.append(extras[i]) + i += 1 + } + } + + expectUniqueDequeContents(data.deque, equalTo: data.contents) + } + } + } + } + + func test_prepend_initializingWith_partial() { + withEveryDeque("layout", ofCapacities: [1, 2, 3, 5, 10]) { layout in + withEvery("prependCount", in: 0 ..< layout.freeCapacity) { prependCount in + withLifetimeTracking { tracker in + var data = tracker.uniqueDeque(with: layout) + + let extras = tracker.instances(for: layout.count ..< layout.count + prependCount) + + data.contents.insert(contentsOf: extras, at: 0) + + var i = 0 + data.deque.prepend(addingCount: layout.freeCapacity) { target in + while !target.isFull, i < prependCount { + target.append(extras[i]) + i += 1 + } + } + expectEqual(i, extras.count) + expectUniqueDequeContents(data.deque, equalTo: data.contents) + } + } + } + } + + func test_append_initializingWith_partial() { + withEveryDeque("layout", ofCapacities: [1, 2, 3, 5, 10]) { layout in + withEvery("prependCount", in: 0 ..< layout.freeCapacity) { prependCount in + withLifetimeTracking { tracker in + var data = tracker.uniqueDeque(with: layout) + + let extras = tracker.instances(for: layout.count ..< layout.count + prependCount) + + data.contents.append(contentsOf: extras) + + var i = 0 + data.deque.append(addingCount: layout.freeCapacity) { target in + while !target.isFull, i < prependCount { + target.append(extras[i]) + i += 1 + } + } + expectEqual(i, extras.count) + expectUniqueDequeContents(data.deque, equalTo: data.contents) + } + } + } + } + + func test_prepend_initializingWith_failing() { + withEveryDeque("layout", ofCapacities: [1, 2, 3, 5, 10]) { layout in + if layout.freeCapacity == 0 { return } + withEvery("prependCount", in: 0 ..< layout.freeCapacity) { prependCount in + withLifetimeTracking { tracker in + var data = tracker.uniqueDeque(with: layout) + + let extras = tracker.instances(for: layout.count ..< layout.count + prependCount) + + data.contents.insert(contentsOf: extras, at: 0) + + expectThrows { () throws(TestError) in + var i = 0 + try data.deque.prepend( + addingCount: layout.freeCapacity + ) { target throws(TestError) in + while !target.isFull, i < prependCount { + target.append(extras[i]) + i += 1 + } + if i == prependCount { + throw TestError(42) + } + } + } + errorHandler: { error in + expectEqual(error.value, 42) + } + expectUniqueDequeContents(data.deque, equalTo: data.contents) + } + } + } + } + + + func test_append_initializingWith_failing() { + withEveryDeque("layout", ofCapacities: [1, 2, 3, 5, 10]) { layout in + if layout.freeCapacity == 0 { return } + withEvery("prependCount", in: 0 ..< layout.freeCapacity) { prependCount in + withLifetimeTracking { tracker in + var data = tracker.uniqueDeque(with: layout) + + let extras = tracker.instances(for: layout.count ..< layout.count + prependCount) + + data.contents.append(contentsOf: extras) + + expectThrows { () throws(TestError) in + var i = 0 + try data.deque.append( + addingCount: layout.freeCapacity + ) { target throws(TestError) in + while !target.isFull, i < prependCount { + target.append(extras[i]) + i += 1 + } + if i == prependCount { + throw TestError(42) + } + } + } + errorHandler: { error in + expectEqual(error.value, 42) + } + expectUniqueDequeContents(data.deque, equalTo: data.contents) + } + } + } + } + +#if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) + func test_prepend_Producer_full() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5]) { layout in + withEvery("producerSize", in: 0 ..< 6) { producerSize in + withLifetimeTracking { tracker in + var data = tracker.uniqueDeque(with: layout) + + var extras = tracker.instances(for: 0 ..< producerSize) + + data.contents.insert(contentsOf: extras, at: 0) + + var producer = CustomProducer, Never> { offset in + guard !extras.isEmpty else { return nil } + return extras.removeFirst() + } + + data.deque.prepend(addingCount: extras.count, from: &producer) + expectEqual(extras.count, 0) + expectUniqueDequeContents(data.deque, equalTo: data.contents) + } + } + } + } +#endif + +#if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) + func test_append_Producer_full() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5]) { layout in + withEvery("producerSize", in: 0 ..< 6) { producerSize in + withLifetimeTracking { tracker in + var data = tracker.uniqueDeque(with: layout) + + var extras = tracker.instances(for: 0 ..< producerSize) + + data.contents.append(contentsOf: extras) + + var producer = CustomProducer, Never> { offset in + guard !extras.isEmpty else { return nil } + return extras.removeFirst() + } + + data.deque.append(addingCount: extras.count, from: &producer) + expectEqual(extras.count, 0) + expectUniqueDequeContents(data.deque, equalTo: data.contents) + } + } + } + } +#endif + +#if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) + func test_prepend_Producer_failing() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5]) { layout in + guard layout.freeCapacity > 0 else { return } + withEvery("producerSize", in: 0 ..< 6) { producerSize in + withLifetimeTracking { tracker in + var data = tracker.uniqueDeque(with: layout) + + var extras = tracker.instances(for: 0 ..< producerSize) + + data.contents.insert(contentsOf: extras, at: 0) + + var producer = CustomProducer, TestError> { offset throws(TestError) in + guard !extras.isEmpty else { throw TestError(23) } + return extras.removeFirst() + } + expectThrows { () throws(TestError) in + try data.deque.prepend(addingCount: extras.count + 1, from: &producer) + } + errorHandler: { error in + expectEqual(error.value, 23) + } + expectEqual(extras.count, 0) + expectUniqueDequeContents(data.deque, equalTo: data.contents) + } + } + } + } +#endif + +#if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) + func test_append_Producer_failing() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5]) { layout in + guard layout.freeCapacity > 0 else { return } + withEvery("producerSize", in: 0 ..< 6) { producerSize in + withLifetimeTracking { tracker in + var data = tracker.uniqueDeque(with: layout) + + var extras = tracker.instances(for: 0 ..< producerSize) + + data.contents.append(contentsOf: extras) + + var producer = CustomProducer, TestError> { offset throws(TestError) in + guard !extras.isEmpty else { throw TestError(23) } + return extras.removeFirst() + } + + expectThrows { () throws(TestError) in + try data.deque.append(addingCount: extras.count + 1, from: &producer) + } + errorHandler: { error in + expectEqual(error.value, 23) + } + expectEqual(extras.count, 0) + expectUniqueDequeContents(data.deque, equalTo: data.contents) + } + } + } + } +#endif + + func test_prepend_MinimalSequence() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withEvery("c", in: 0 ..< layout.freeCapacity) { c in + withEvery("underestimatedCount", in: [UnderestimatedCountBehavior.precise, .half, .value(min(1, c))]) { underestimatedCount in + withLifetimeTracking { tracker in + var data = tracker.uniqueDeque(with: layout) + let extras = tracker.instances(for: layout.count ..< layout.count + c) + let sequence = MinimalSequence(elements: extras, underestimatedCount: underestimatedCount) + data.contents.insert(contentsOf: extras, at: 0) + data.deque.prepend(copying: sequence) + expectUniqueDequeContents(data.deque, equalTo: data.contents) + } + } + } + } + } + + func test_append_MinimalSequence() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withEvery("c", in: 0 ..< layout.freeCapacity) { c in + withEvery("underestimatedCount", in: [UnderestimatedCountBehavior.precise, .half, .value(min(1, c))]) { underestimatedCount in + withLifetimeTracking { tracker in + var data = tracker.uniqueDeque(with: layout) + let extras = tracker.instances(for: layout.count ..< layout.count + c) + let sequence = MinimalSequence(elements: extras, underestimatedCount: underestimatedCount) + data.contents.append(contentsOf: extras) + data.deque.append(copying: sequence) + expectUniqueDequeContents(data.deque, equalTo: data.contents) + } + } + } + } + } + + func test_prepend_MinimalCollection() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withEvery("c", in: 0 ..< layout.freeCapacity) { c in + withLifetimeTracking { tracker in + var data = tracker.uniqueDeque(with: layout) + let extra = tracker.instances(for: layout.count ..< layout.count + c) + let minimal = MinimalCollection(extra) + data.contents.insert(contentsOf: extra, at: 0) + data.deque.prepend(copying: minimal) + expectUniqueDequeContents(data.deque, equalTo: data.contents) + } + } + } + } + + func test_append_MinimalCollection() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withEvery("c", in: 0 ..< layout.freeCapacity) { c in + withLifetimeTracking { tracker in + var data = tracker.uniqueDeque(with: layout) + let extra = tracker.instances(for: layout.count ..< layout.count + c) + let minimal = MinimalCollection(extra) + data.contents.append(contentsOf: extra) + data.deque.append(copying: minimal) + expectUniqueDequeContents(data.deque, equalTo: data.contents) + } + } + } + } + + func test_prepend_ContiguousArray_asCollection() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withEvery("c", in: 0 ..< layout.freeCapacity) { c in + withLifetimeTracking { tracker in + var data = tracker.uniqueDeque(with: layout) + let extraRange = layout.count ..< layout.count + c + let extra = ContiguousArray(tracker.instances(for: extraRange)) + data.contents.insert(contentsOf: extra, at: 0) + data.deque.prepend(copying: extra) + expectUniqueDequeContents(data.deque, equalTo: data.contents) + } + } + } + } + + func test_append_ContiguousArray_asCollection() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withEvery("c", in: 0 ..< layout.freeCapacity) { c in + withLifetimeTracking { tracker in + var data = tracker.uniqueDeque(with: layout) + let extraRange = layout.count ..< layout.count + c + let extra = ContiguousArray(tracker.instances(for: extraRange)) + data.contents.append(contentsOf: extra) + data.deque.append(copying: extra) + expectUniqueDequeContents(data.deque, equalTo: data.contents) + } + } + } + } + + func test_prepend_ContiguousArray_asSequence() { + // This calls the Sequence-based `Deque.prepend` overload, even if + // `elements` happens to be of a Collection type. + func prependSequence( + contentsOf elements: S, + to deque: inout UniqueDeque + ) { + deque.prepend(copying: elements) + } + + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withEvery("c", in: 0 ..< layout.freeCapacity) { c in + withLifetimeTracking { tracker in + var data = tracker.uniqueDeque(with: layout) + let extraRange = layout.count ..< layout.count + c + let extra = ContiguousArray(tracker.instances(for: extraRange)) + data.contents.insert(contentsOf: extra, at: 0) + prependSequence(contentsOf: extra, to: &data.deque) + expectUniqueDequeContents(data.deque, equalTo: data.contents) + } + } + } + } + + func test_append_ContiguousArray_asSequence() { + // This calls the Sequence-based `Deque.append` overload, even if + // `elements` happens to be of a Collection type. + func appendSequence( + contentsOf elements: S, + to deque: inout UniqueDeque + ) { + deque.append(copying: elements) + } + + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withEvery("c", in: 0 ..< layout.freeCapacity) { c in + withLifetimeTracking { tracker in + var data = tracker.uniqueDeque(with: layout) + let extraRange = layout.count ..< layout.count + c + let extra = ContiguousArray(tracker.instances(for: extraRange)) + data.contents.append(contentsOf: extra) + appendSequence(contentsOf: extra, to: &data.deque) + expectUniqueDequeContents(data.deque, equalTo: data.contents) + } + } + } + } + +#if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) + func test_prepend_copying_StaccatoContainer() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withEvery("count", in: 0 ... 15) { count in + withEvery("spanCounts", in: [ + [1], + [1, 2, 3], + [3, 5, 7], + [Int.max], + ] as [[Int]]) { spanCounts in + var expected = Array(layout.valueRange) + expected.insert(contentsOf: layout.count ..< layout.count + count, at: 0) + + var actual = UniqueDeque(layout: layout) + let additions = StaccatoContainer(count: count, spanCounts: spanCounts) { + layout.count + $0 + } + actual.prepend(copying: additions) + + expectUniqueDequeContents(actual, equalTo: expected) + } + } + } + } +#endif + +#if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) + func test_append_copying_StaccatoContainer() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withEvery("count", in: 0 ... 15) { count in + withEvery("spanCounts", in: [ + [1], + [1, 2, 3], + [3, 5, 7], + [Int.max], + ] as [[Int]]) { spanCounts in + var expected = Array(layout.valueRange) + expected.append(contentsOf: layout.count ..< layout.count + count) + + var actual = UniqueDeque(layout: layout) + let additions = StaccatoContainer(count: count, spanCounts: spanCounts) { + layout.count + $0 + } + actual.append(copying: additions) + + expectUniqueDequeContents(actual, equalTo: expected) + } + } + } + } +#endif + } diff --git a/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift b/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift index 7ed7f793..24bc9f64 100644 --- a/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift +++ b/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift @@ -22,29 +22,40 @@ import ContainersPreview #if compiler(>=6.4) && UnstableContainersPreview /// A container type with user-defined contents and storage chunks. /// Useful for testing. -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) public struct StaccatoContainer: ~Copyable { - internal let _contents: RigidArray + internal let _contents: UniqueArray internal let _params: _StaccatoParameters - public init(contents: consuming RigidArray, spanCounts: [Int]) { - // FIXME: Make this take an arbitrary consumable container + public init( + count: Int, + spanCounts: [Int], + generator: (Int) -> Element + ) { + var contents = UniqueArray() + while contents.count < count { + contents.append(generator(contents.count)) + } self._contents = contents self._params = _StaccatoParameters( count: _contents.count, spanCounts: spanCounts) } -} -@available(SwiftStdlib 5.0, *) -extension StaccatoContainer { - public init(contents: Array, spanCounts: [Int]) { - self._contents = RigidArray(copying: contents) + public init< + Source: Producer & ~Copyable & ~Escapable + >( + spanCounts: [Int], + contents: consuming Source + ) throws(Source.Failure) + where Source.Element: ~Copyable, Element == Source.Element + { + self._contents = try UniqueArray(from: contents) self._params = _StaccatoParameters( count: _contents.count, spanCounts: spanCounts) } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) package struct _StaccatoParameters { internal let _count: Int internal let _spanCounts: [Int] @@ -76,7 +87,7 @@ package struct _StaccatoParameters { } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) public struct _StaccatoBorrowingIterator: BorrowingIteratorProtocol, ~Escapable { internal let _contents: Span internal let _params: _StaccatoParameters @@ -112,7 +123,7 @@ public struct _StaccatoBorrowingIterator: BorrowingIteratorP } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) public struct _StaccatoIndex: Comparable, Hashable{ var _offset: Int init(_offset: Int) { @@ -132,7 +143,7 @@ public struct _StaccatoIndex: Comparable, Hashable{ } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension StaccatoContainer: Iterable where Element: ~Copyable { public typealias BorrowingIterator = _StaccatoBorrowingIterator // FIXME rdar://150240032 @@ -143,7 +154,7 @@ extension StaccatoContainer: Iterable where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension StaccatoContainer: Container where Element: ~Copyable { public typealias Index = _StaccatoIndex diff --git a/Tests/_CollectionsTestSupport/Utilities/DequeLayout.swift b/Tests/_CollectionsTestSupport/Utilities/DequeLayout.swift new file mode 100644 index 00000000..82e37bfa --- /dev/null +++ b/Tests/_CollectionsTestSupport/Utilities/DequeLayout.swift @@ -0,0 +1,151 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2014 - 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 +// +//===----------------------------------------------------------------------===// + +#if COLLECTIONS_SINGLE_MODULE +import Collections +#else +import InternalCollectionsUtilities +import DequeModule +#endif + +public struct DequeLayout: Hashable, CustomStringConvertible { + public let capacity: Int + public let startSlot: Int + public let count: Int + public let startValue: Int + + public init(capacity: Int, startSlot: Int, count: Int, startValue: Int = 0) { + self.capacity = capacity + self.startSlot = startSlot + self.count = count + self.startValue = startValue + } + + public var freeCapacity: Int { capacity - count } + public var valueRange: Range { startValue ..< startValue + count } + + public var description: String { + var result = "DequeLayout(capacity: \(capacity), startSlot: \(startSlot), count: \(count)" + if count > 0 { + result += ", startValue: \(startValue)" + } + result += ")" + return result + } + + public var isWrapped: Bool { + startSlot + count > capacity + } + + public var wrapIndex: Int? { + isWrapped ? capacity - startSlot : nil + } +} + +public func withEveryDeque( + _ label: String, + ofCapacities capacities: C, + startValue: Int = 0, + file: StaticString = #filePath, line: UInt = #line, + _ body: (DequeLayout) throws -> Void +) rethrows -> Void where C.Element == Int { + // Exhaustive tests for all deque layouts of various capacities + for capacity in capacities { + for startSlot in 0 ..< capacity { + for count in 0 ... capacity { + let layout = DequeLayout( + capacity: capacity, + startSlot: startSlot, + count: count, + startValue: startValue) + let entry = TestContext.current.push("\(label): \(layout)", file: file, line: line) + defer { TestContext.current.pop(entry) } + try body(layout) + } + } + } +} + +public func withEveryFullDeque( + _ label: String, + ofCapacities capacities: C, + startValue: Int = 0, + file: StaticString = #filePath, line: UInt = #line, + _ body: (DequeLayout) throws -> Void +) rethrows -> Void where C.Element == Int { + // Exhaustive tests for all deque layouts of various capacities + for capacity in capacities { + for startSlot in 0 ..< capacity { + let layout = DequeLayout( + capacity: capacity, + startSlot: startSlot, + count: capacity, + startValue: startValue) + let entry = TestContext.current.push("\(label): \(layout)", file: file, line: line) + defer { TestContext.current.pop(entry) } + try body(layout) + } + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: ~Copyable { + @inlinable + public init( + layout: DequeLayout, + generator: (Int) -> Element + ) { + var offset = layout.startValue + self.init(_capacity: layout.capacity, startSlot: layout.startSlot) { target in + while !target.isFull, offset < layout.startValue + layout.count { + target.append(generator(offset)) + offset += 1 + } + } + precondition(self.count == layout.count) + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidDeque { + @inlinable + public init(layout: DequeLayout) { + var offset = layout.startValue + self.init(_capacity: layout.capacity, startSlot: layout.startSlot) { target in + while !target.isFull, offset < layout.startValue + layout.count { + target.append(offset) + offset += 1 + } + } + precondition(self.count == layout.count) + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque where Element: ~Copyable { + @inlinable + public init( + layout: DequeLayout, + generator: (Int) -> Element + ) { + self.init(consuming: RigidDeque(layout: layout, generator: generator)) + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque { + @inlinable + public init(layout: DequeLayout) { + self.init(consuming: RigidDeque(layout: layout)) + } +}