From a624614717ea15bd731465e65615a2ae60239e58 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 11 Oct 2022 13:38:10 -0700 Subject: [PATCH 01/31] [OrderedCollections] Document that sort is stable (as of SE-0372) --- .../OrderedDictionary/OrderedDictionary+Elements.swift | 9 ++++----- .../OrderedDictionary+Partial MutableCollection.swift | 9 ++++----- .../OrderedSet+Partial MutableCollection.swift | 9 ++++----- 3 files changed, 12 insertions(+), 15 deletions(-) diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift index 50116a81..018810ea 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift @@ -430,9 +430,8 @@ extension OrderedDictionary.Elements { /// and `c` are incomparable, then `a` and `c` are also incomparable. /// (Transitive incomparability) /// - /// The sorting algorithm is not guaranteed to be stable. A stable sort - /// preserves the relative order of elements for which - /// `areInIncreasingOrder` does not establish an order. + /// The sorting algorithm is guaranteed to be stable. A stable sort + /// preserves the relative order of elements that compare as equal. /// /// - Parameter areInIncreasingOrder: A predicate that returns `true` if its /// first argument should be ordered before its second argument; @@ -458,8 +457,8 @@ extension OrderedDictionary.Elements where Key: Comparable { /// sorted in ascending order. (`Value` doesn't need to conform to /// `Comparable` because the keys are guaranteed to be unique.) /// - /// The sorting algorithm is not guaranteed to be stable. A stable sort - /// preserves the relative order of elements that compare equal. + /// The sorting algorithm is guaranteed to be stable. A stable sort + /// preserves the relative order of elements that compare as equal. /// /// - Complexity: O(*n* log *n*), where *n* is the length of the collection. @inlinable diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial MutableCollection.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial MutableCollection.swift index c01e9686..0715e9b0 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial MutableCollection.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial MutableCollection.swift @@ -82,9 +82,8 @@ extension OrderedDictionary { /// and `c` are incomparable, then `a` and `c` are also incomparable. /// (Transitive incomparability) /// - /// The sorting algorithm is not guaranteed to be stable. A stable sort - /// preserves the relative order of elements for which - /// `areInIncreasingOrder` does not establish an order. + /// The sorting algorithm is guaranteed to be stable. A stable sort + /// preserves the relative order of elements that compare as equal. /// /// - Parameter areInIncreasingOrder: A predicate that returns `true` if its /// first argument should be ordered before its second argument; @@ -116,8 +115,8 @@ extension OrderedDictionary where Key: Comparable { /// sorted in ascending order. (`Value` doesn't need to conform to /// `Comparable` because the keys are guaranteed to be unique.) /// - /// The sorting algorithm is not guaranteed to be stable. A stable sort - /// preserves the relative order of elements that compare equal. + /// The sorting algorithm is guaranteed to be stable. A stable sort + /// preserves the relative order of elements that compare as equal. /// /// - Complexity: O(*n* log *n*), where *n* is the length of the collection. @inlinable diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial MutableCollection.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial MutableCollection.swift index 1103f0cd..2e37db2b 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial MutableCollection.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial MutableCollection.swift @@ -216,9 +216,8 @@ extension OrderedSet { /// and `c` are incomparable, then `a` and `c` are also incomparable. /// (Transitive incomparability) /// - /// The sorting algorithm is not guaranteed to be stable. A stable sort - /// preserves the relative order of elements for which - /// `areInIncreasingOrder` does not establish an order. + /// The sorting algorithm is guaranteed to be stable. A stable sort + /// preserves the relative order of elements that compare as equal. /// /// - Parameter areInIncreasingOrder: A predicate that returns `true` if its /// first argument should be ordered before its second argument; @@ -266,8 +265,8 @@ extension OrderedSet where Element: Comparable { /// print(students) /// // Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]" /// - /// The sorting algorithm is not guaranteed to be stable. A stable sort - /// preserves the relative order of elements that compare equal. + /// The sorting algorithm is guaranteed to be stable. A stable sort + /// preserves the relative order of elements that compare as equal. /// /// - Complexity: O(*n* log *n*), where *n* is the length of the collection. @inlinable From 4997e15320161195425bcc76e4a7405fbb71208d Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 11 Oct 2022 13:38:55 -0700 Subject: [PATCH 02/31] [Xcode] Update to latest package versions --- .../xcshareddata/swiftpm/Package.resolved | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Utils/swift-collections.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Utils/swift-collections.xcworkspace/xcshareddata/swiftpm/Package.resolved index dce13b01..018829f4 100644 --- a/Utils/swift-collections.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/Utils/swift-collections.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -6,8 +6,8 @@ "repositoryURL": "https://github.com/apple/swift-argument-parser", "state": { "branch": null, - "revision": "df9ee6676cd5b3bf5b330ec7568a5644f547201b", - "version": "1.1.3" + "revision": "9f39744e025c7d377987f30b03770805dcb0bcd1", + "version": "1.1.4" } }, { @@ -15,8 +15,8 @@ "repositoryURL": "https://github.com/apple/swift-system", "state": { "branch": null, - "revision": "39774ef16a6d91dee6f666b940e00ea202710cf7", - "version": "0.0.3" + "revision": "025bcb1165deab2e20d4eaba79967ce73013f496", + "version": "1.2.1" } } ] From 51604cd196265a1e4444cef0a7ac749e34f5e64e Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 12 Oct 2022 15:11:57 -0700 Subject: [PATCH 03/31] [OrderedCollections] Oops, restore custom wording for `areInIncreasingOrder` variants --- .../OrderedDictionary/OrderedDictionary+Elements.swift | 3 ++- .../OrderedDictionary+Partial MutableCollection.swift | 3 ++- .../OrderedSet/OrderedSet+Partial MutableCollection.swift | 3 ++- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift index 018810ea..d1667630 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift @@ -431,7 +431,8 @@ extension OrderedDictionary.Elements { /// (Transitive incomparability) /// /// The sorting algorithm is guaranteed to be stable. A stable sort - /// preserves the relative order of elements that compare as equal. + /// preserves the relative order of elements for which + /// `areInIncreasingOrder` does not establish an order. /// /// - Parameter areInIncreasingOrder: A predicate that returns `true` if its /// first argument should be ordered before its second argument; diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial MutableCollection.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial MutableCollection.swift index 0715e9b0..f43d6993 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial MutableCollection.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial MutableCollection.swift @@ -83,7 +83,8 @@ extension OrderedDictionary { /// (Transitive incomparability) /// /// The sorting algorithm is guaranteed to be stable. A stable sort - /// preserves the relative order of elements that compare as equal. + /// preserves the relative order of elements for which + /// `areInIncreasingOrder` does not establish an order. /// /// - Parameter areInIncreasingOrder: A predicate that returns `true` if its /// first argument should be ordered before its second argument; diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial MutableCollection.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial MutableCollection.swift index 2e37db2b..953b8a7a 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial MutableCollection.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial MutableCollection.swift @@ -217,7 +217,8 @@ extension OrderedSet { /// (Transitive incomparability) /// /// The sorting algorithm is guaranteed to be stable. A stable sort - /// preserves the relative order of elements that compare as equal. + /// preserves the relative order of elements for which + /// `areInIncreasingOrder` does not establish an order. /// /// - Parameter areInIncreasingOrder: A predicate that returns `true` if its /// first argument should be ordered before its second argument; From 5f70117c55b56c9ea82d4d33f00f75b58dfb1d36 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 12 Oct 2022 16:30:52 -0700 Subject: [PATCH 04/31] [Heap] Start using _CollectionsTestSupport for testing --- Package.swift | 2 +- Tests/HeapTests/HeapTests.swift | 451 ++++++++++++++++---------------- 2 files changed, 227 insertions(+), 226 deletions(-) diff --git a/Package.swift b/Package.swift index 24d62d31..3a51dc49 100644 --- a/Package.swift +++ b/Package.swift @@ -118,7 +118,7 @@ let package = Package( swiftSettings: settings), .testTarget( name: "HeapTests", - dependencies: ["HeapModule"], + dependencies: ["HeapModule", "_CollectionsTestSupport"], swiftSettings: settings), // OrderedSet, OrderedDictionary diff --git a/Tests/HeapTests/HeapTests.swift b/Tests/HeapTests/HeapTests.swift index 4f51b4c8..a39af8bc 100644 --- a/Tests/HeapTests/HeapTests.swift +++ b/Tests/HeapTests/HeapTests.swift @@ -10,6 +10,7 @@ //===----------------------------------------------------------------------===// import XCTest +import _CollectionsTestSupport import HeapModule extension Heap { @@ -35,35 +36,35 @@ extension Heap { } } -final class HeapTests: XCTestCase { +final class HeapTests: CollectionTestCase { func test_isEmpty() { var heap = Heap() - XCTAssertTrue(heap.isEmpty) + expectTrue(heap.isEmpty) heap.insert(42) - XCTAssertFalse(heap.isEmpty) + expectFalse(heap.isEmpty) let _ = heap.popMin() - XCTAssertTrue(heap.isEmpty) + expectTrue(heap.isEmpty) } func test_count() { var heap = Heap() - XCTAssertEqual(heap.count, 0) + expectEqual(heap.count, 0) heap.insert(20) - XCTAssertEqual(heap.count, 1) + expectEqual(heap.count, 1) heap.insert(40) - XCTAssertEqual(heap.count, 2) + expectEqual(heap.count, 2) _ = heap.popMin() - XCTAssertEqual(heap.count, 1) + expectEqual(heap.count, 1) } func test_unordered() { let heap = Heap((1...10)) - XCTAssertEqual(Set(heap.unordered), Set(1...10)) + expectEqual(Set(heap.unordered), Set(1...10)) } struct Task: Comparable { @@ -78,26 +79,26 @@ final class HeapTests: XCTestCase { func test_insert() { var heap = Heap() - XCTAssertEqual(heap.count, 0) + expectEqual(heap.count, 0) heap.insert(Task(name: "Hello, world", priority: 50)) - XCTAssertEqual(heap.count, 1) + expectEqual(heap.count, 1) } func test_insert_contentsOf() { var heap = Heap() heap.insert(contentsOf: (1...10).shuffled()) - XCTAssertEqual(heap.count, 10) - XCTAssertEqual(heap.popMax(), 10) - XCTAssertEqual(heap.popMin(), 1) + expectEqual(heap.count, 10) + expectEqual(heap.popMax(), 10) + expectEqual(heap.popMin(), 1) heap.insert(contentsOf: (21...50).shuffled()) - XCTAssertEqual(heap.count, 38) - XCTAssertEqual(heap.max(), 50) - XCTAssertEqual(heap.min(), 2) + expectEqual(heap.count, 38) + expectEqual(heap.max(), 50) + expectEqual(heap.min(), 2) heap.insert(contentsOf: [-10, -9, -8, -7, -6, -5].shuffled()) - XCTAssertEqual(heap.count, 44) - XCTAssertEqual(heap.min(), -10) + expectEqual(heap.count, 44) + expectEqual(heap.min(), -10) } func test_insert_contentsOf_withSequenceFunction() { @@ -107,333 +108,333 @@ final class HeapTests: XCTestCase { let evens = sequence(first: 0, next: addTwo(_:)).prefix(20) var heap = Heap(evens) - XCTAssertEqual(heap.count, 20) + expectEqual(heap.count, 20) heap.insert(contentsOf: sequence(first: 1, next: addTwo(_:)).prefix(20)) - XCTAssertEqual(heap.count, 40) + expectEqual(heap.count, 40) - var i = 0 - while let min = heap.popMin() { - XCTAssertEqual(min, i) - i += 1 + withEvery("i", in: 0 ..< 40) { i in + expectNotNil(heap.popMin()) { min in + expectEqual(min, i) + } } - XCTAssertEqual(i, 40) + expectNil(heap.popMin()) } func test_min() { var heap = Heap() - XCTAssertNil(heap.min()) + expectNil(heap.min()) heap.insert(5) - XCTAssertEqual(5, heap.min()) + expectEqual(5, heap.min()) heap.insert(12) - XCTAssertEqual(5, heap.min()) + expectEqual(5, heap.min()) heap.insert(2) - XCTAssertEqual(2, heap.min()) + expectEqual(2, heap.min()) heap.insert(1) - XCTAssertEqual(1, heap.min()) + expectEqual(1, heap.min()) } func test_max() { var heap = Heap() - XCTAssertNil(heap.max()) + expectNil(heap.max()) heap.insert(42) - XCTAssertEqual(42, heap.max()) + expectEqual(42, heap.max()) heap.insert(20) - XCTAssertEqual(42, heap.max()) + expectEqual(42, heap.max()) heap.insert(63) - XCTAssertEqual(63, heap.max()) + expectEqual(63, heap.max()) heap.insert(90) - XCTAssertEqual(90, heap.max()) + expectEqual(90, heap.max()) } func test_popMin() { var heap = Heap() - XCTAssertNil(heap.popMin()) + expectNil(heap.popMin()) heap.insert(7) - XCTAssertEqual(heap.popMin(), 7) + expectEqual(heap.popMin(), 7) heap.insert(12) heap.insert(9) - XCTAssertEqual(heap.popMin(), 9) + expectEqual(heap.popMin(), 9) heap.insert(13) heap.insert(1) heap.insert(4) - XCTAssertEqual(heap.popMin(), 1) + expectEqual(heap.popMin(), 1) for i in (1...20).shuffled() { heap.insert(i) } - XCTAssertEqual(heap.popMin(), 1) - XCTAssertEqual(heap.popMin(), 2) - XCTAssertEqual(heap.popMin(), 3) - XCTAssertEqual(heap.popMin(), 4) - XCTAssertEqual(heap.popMin(), 4) // One 4 was still in the heap from before - XCTAssertEqual(heap.popMin(), 5) - XCTAssertEqual(heap.popMin(), 6) - XCTAssertEqual(heap.popMin(), 7) - XCTAssertEqual(heap.popMin(), 8) - XCTAssertEqual(heap.popMin(), 9) - XCTAssertEqual(heap.popMin(), 10) - XCTAssertEqual(heap.popMin(), 11) - XCTAssertEqual(heap.popMin(), 12) - XCTAssertEqual(heap.popMin(), 12) // One 12 was still in the heap from before - XCTAssertEqual(heap.popMin(), 13) - XCTAssertEqual(heap.popMin(), 13) // One 13 was still in the heap from before - XCTAssertEqual(heap.popMin(), 14) - XCTAssertEqual(heap.popMin(), 15) - XCTAssertEqual(heap.popMin(), 16) - XCTAssertEqual(heap.popMin(), 17) - XCTAssertEqual(heap.popMin(), 18) - XCTAssertEqual(heap.popMin(), 19) - XCTAssertEqual(heap.popMin(), 20) + expectEqual(heap.popMin(), 1) + expectEqual(heap.popMin(), 2) + expectEqual(heap.popMin(), 3) + expectEqual(heap.popMin(), 4) + expectEqual(heap.popMin(), 4) // One 4 was still in the heap from before + expectEqual(heap.popMin(), 5) + expectEqual(heap.popMin(), 6) + expectEqual(heap.popMin(), 7) + expectEqual(heap.popMin(), 8) + expectEqual(heap.popMin(), 9) + expectEqual(heap.popMin(), 10) + expectEqual(heap.popMin(), 11) + expectEqual(heap.popMin(), 12) + expectEqual(heap.popMin(), 12) // One 12 was still in the heap from before + expectEqual(heap.popMin(), 13) + expectEqual(heap.popMin(), 13) // One 13 was still in the heap from before + expectEqual(heap.popMin(), 14) + expectEqual(heap.popMin(), 15) + expectEqual(heap.popMin(), 16) + expectEqual(heap.popMin(), 17) + expectEqual(heap.popMin(), 18) + expectEqual(heap.popMin(), 19) + expectEqual(heap.popMin(), 20) - XCTAssertNil(heap.popMin()) + expectNil(heap.popMin()) } func test_popMax() { var heap = Heap() - XCTAssertNil(heap.popMax()) + expectNil(heap.popMax()) heap.insert(7) - XCTAssertEqual(heap.popMax(), 7) + expectEqual(heap.popMax(), 7) heap.insert(12) heap.insert(9) - XCTAssertEqual(heap.popMax(), 12) + expectEqual(heap.popMax(), 12) heap.insert(13) heap.insert(1) heap.insert(4) - XCTAssertEqual(heap.popMax(), 13) + expectEqual(heap.popMax(), 13) for i in (1...20).shuffled() { heap.insert(i) } - XCTAssertEqual(heap.popMax(), 20) - XCTAssertEqual(heap.popMax(), 19) - XCTAssertEqual(heap.popMax(), 18) - XCTAssertEqual(heap.popMax(), 17) - XCTAssertEqual(heap.popMax(), 16) - XCTAssertEqual(heap.popMax(), 15) - XCTAssertEqual(heap.popMax(), 14) - XCTAssertEqual(heap.popMax(), 13) - XCTAssertEqual(heap.popMax(), 12) - XCTAssertEqual(heap.popMax(), 11) - XCTAssertEqual(heap.popMax(), 10) - XCTAssertEqual(heap.popMax(), 9) - XCTAssertEqual(heap.popMax(), 9) // One 9 was still in the heap from before - XCTAssertEqual(heap.popMax(), 8) - XCTAssertEqual(heap.popMax(), 7) - XCTAssertEqual(heap.popMax(), 6) - XCTAssertEqual(heap.popMax(), 5) - XCTAssertEqual(heap.popMax(), 4) - XCTAssertEqual(heap.popMax(), 4) // One 4 was still in the heap from before - XCTAssertEqual(heap.popMax(), 3) - XCTAssertEqual(heap.popMax(), 2) - XCTAssertEqual(heap.popMax(), 1) - XCTAssertEqual(heap.popMax(), 1) // One 1 was still in the heap from before + expectEqual(heap.popMax(), 20) + expectEqual(heap.popMax(), 19) + expectEqual(heap.popMax(), 18) + expectEqual(heap.popMax(), 17) + expectEqual(heap.popMax(), 16) + expectEqual(heap.popMax(), 15) + expectEqual(heap.popMax(), 14) + expectEqual(heap.popMax(), 13) + expectEqual(heap.popMax(), 12) + expectEqual(heap.popMax(), 11) + expectEqual(heap.popMax(), 10) + expectEqual(heap.popMax(), 9) + expectEqual(heap.popMax(), 9) // One 9 was still in the heap from before + expectEqual(heap.popMax(), 8) + expectEqual(heap.popMax(), 7) + expectEqual(heap.popMax(), 6) + expectEqual(heap.popMax(), 5) + expectEqual(heap.popMax(), 4) + expectEqual(heap.popMax(), 4) // One 4 was still in the heap from before + expectEqual(heap.popMax(), 3) + expectEqual(heap.popMax(), 2) + expectEqual(heap.popMax(), 1) + expectEqual(heap.popMax(), 1) // One 1 was still in the heap from before - XCTAssertNil(heap.popMax()) + expectNil(heap.popMax()) } func test_removeMin() { var heap = Heap((1...20).shuffled()) - XCTAssertEqual(heap.removeMin(), 1) - XCTAssertEqual(heap.removeMin(), 2) - XCTAssertEqual(heap.removeMin(), 3) - XCTAssertEqual(heap.removeMin(), 4) - XCTAssertEqual(heap.removeMin(), 5) - XCTAssertEqual(heap.removeMin(), 6) - XCTAssertEqual(heap.removeMin(), 7) - XCTAssertEqual(heap.removeMin(), 8) - XCTAssertEqual(heap.removeMin(), 9) - XCTAssertEqual(heap.removeMin(), 10) - XCTAssertEqual(heap.removeMin(), 11) - XCTAssertEqual(heap.removeMin(), 12) - XCTAssertEqual(heap.removeMin(), 13) - XCTAssertEqual(heap.removeMin(), 14) - XCTAssertEqual(heap.removeMin(), 15) - XCTAssertEqual(heap.removeMin(), 16) - XCTAssertEqual(heap.removeMin(), 17) - XCTAssertEqual(heap.removeMin(), 18) - XCTAssertEqual(heap.removeMin(), 19) - XCTAssertEqual(heap.removeMin(), 20) + expectEqual(heap.removeMin(), 1) + expectEqual(heap.removeMin(), 2) + expectEqual(heap.removeMin(), 3) + expectEqual(heap.removeMin(), 4) + expectEqual(heap.removeMin(), 5) + expectEqual(heap.removeMin(), 6) + expectEqual(heap.removeMin(), 7) + expectEqual(heap.removeMin(), 8) + expectEqual(heap.removeMin(), 9) + expectEqual(heap.removeMin(), 10) + expectEqual(heap.removeMin(), 11) + expectEqual(heap.removeMin(), 12) + expectEqual(heap.removeMin(), 13) + expectEqual(heap.removeMin(), 14) + expectEqual(heap.removeMin(), 15) + expectEqual(heap.removeMin(), 16) + expectEqual(heap.removeMin(), 17) + expectEqual(heap.removeMin(), 18) + expectEqual(heap.removeMin(), 19) + expectEqual(heap.removeMin(), 20) } func test_removeMax() { var heap = Heap((1...20).shuffled()) - XCTAssertEqual(heap.removeMax(), 20) - XCTAssertEqual(heap.removeMax(), 19) - XCTAssertEqual(heap.removeMax(), 18) - XCTAssertEqual(heap.removeMax(), 17) - XCTAssertEqual(heap.removeMax(), 16) - XCTAssertEqual(heap.removeMax(), 15) - XCTAssertEqual(heap.removeMax(), 14) - XCTAssertEqual(heap.removeMax(), 13) - XCTAssertEqual(heap.removeMax(), 12) - XCTAssertEqual(heap.removeMax(), 11) - XCTAssertEqual(heap.removeMax(), 10) - XCTAssertEqual(heap.removeMax(), 9) - XCTAssertEqual(heap.removeMax(), 8) - XCTAssertEqual(heap.removeMax(), 7) - XCTAssertEqual(heap.removeMax(), 6) - XCTAssertEqual(heap.removeMax(), 5) - XCTAssertEqual(heap.removeMax(), 4) - XCTAssertEqual(heap.removeMax(), 3) - XCTAssertEqual(heap.removeMax(), 2) - XCTAssertEqual(heap.removeMax(), 1) + expectEqual(heap.removeMax(), 20) + expectEqual(heap.removeMax(), 19) + expectEqual(heap.removeMax(), 18) + expectEqual(heap.removeMax(), 17) + expectEqual(heap.removeMax(), 16) + expectEqual(heap.removeMax(), 15) + expectEqual(heap.removeMax(), 14) + expectEqual(heap.removeMax(), 13) + expectEqual(heap.removeMax(), 12) + expectEqual(heap.removeMax(), 11) + expectEqual(heap.removeMax(), 10) + expectEqual(heap.removeMax(), 9) + expectEqual(heap.removeMax(), 8) + expectEqual(heap.removeMax(), 7) + expectEqual(heap.removeMax(), 6) + expectEqual(heap.removeMax(), 5) + expectEqual(heap.removeMax(), 4) + expectEqual(heap.removeMax(), 3) + expectEqual(heap.removeMax(), 2) + expectEqual(heap.removeMax(), 1) } func test_minimumReplacement() { var heap = Heap(stride(from: 0, through: 27, by: 3).shuffled()) - XCTAssertEqual( + expectEqual( heap.itemsInAscendingOrder(), [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]) - XCTAssertEqual(heap.min(), 0) + expectEqual(heap.min(), 0) // No change heap.replaceMin(with: 0) - XCTAssertEqual( + expectEqual( heap.itemsInAscendingOrder(), [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]) - XCTAssertEqual(heap.min(), 0) + expectEqual(heap.min(), 0) // Even smaller heap.replaceMin(with: -1) - XCTAssertEqual( + expectEqual( heap.itemsInAscendingOrder(), [-1, 3, 6, 9, 12, 15, 18, 21, 24, 27]) - XCTAssertEqual(heap.min(), -1) + expectEqual(heap.min(), -1) // Larger, but not enough to usurp heap.replaceMin(with: 2) - XCTAssertEqual( + expectEqual( heap.itemsInAscendingOrder(), [2, 3, 6, 9, 12, 15, 18, 21, 24, 27]) - XCTAssertEqual(heap.min(), 2) + expectEqual(heap.min(), 2) // Larger, moving another element to be the smallest heap.replaceMin(with: 5) - XCTAssertEqual( + expectEqual( heap.itemsInAscendingOrder(), [3, 5, 6, 9, 12, 15, 18, 21, 24, 27]) - XCTAssertEqual(heap.min(), 3) + expectEqual(heap.min(), 3) } func test_maximumReplacement() { var heap = Heap(stride(from: 0, through: 27, by: 3).shuffled()) - XCTAssertEqual( + expectEqual( heap.itemsInAscendingOrder(), [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]) - XCTAssertEqual(heap.max(), 27) + expectEqual(heap.max(), 27) // No change heap.replaceMax(with: 27) - XCTAssertEqual( + expectEqual( heap.itemsInAscendingOrder(), [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]) - XCTAssertEqual(heap.max(), 27) + expectEqual(heap.max(), 27) // Even larger heap.replaceMax(with: 28) - XCTAssertEqual( + expectEqual( heap.itemsInAscendingOrder(), [0, 3, 6, 9, 12, 15, 18, 21, 24, 28]) - XCTAssertEqual(heap.max(), 28) + expectEqual(heap.max(), 28) // Smaller, but not enough to usurp heap.replaceMax(with: 26) - XCTAssertEqual( + expectEqual( heap.itemsInAscendingOrder(), [0, 3, 6, 9, 12, 15, 18, 21, 24, 26]) - XCTAssertEqual(heap.max(), 26) + expectEqual(heap.max(), 26) // Smaller, moving another element to be the largest heap.replaceMax(with: 23) - XCTAssertEqual( + expectEqual( heap.itemsInAscendingOrder(), [0, 3, 6, 9, 12, 15, 18, 21, 23, 24]) - XCTAssertEqual(heap.max(), 24) + expectEqual(heap.max(), 24) // Check the finer details. As these peek into the stored structure, they // may need to be updated whenever the internal format changes. var heap2 = Heap(raw: [1]) - XCTAssertEqual(heap2.max(), 1) - XCTAssertEqual(Array(heap2.unordered), [1]) - XCTAssertEqual(heap2.replaceMax(with: 2), 1) - XCTAssertEqual(heap2.max(), 2) - XCTAssertEqual(Array(heap2.unordered), [2]) + expectEqual(heap2.max(), 1) + expectEqual(Array(heap2.unordered), [1]) + expectEqual(heap2.replaceMax(with: 2), 1) + expectEqual(heap2.max(), 2) + expectEqual(Array(heap2.unordered), [2]) heap2 = Heap(raw: [1, 2]) - XCTAssertEqual(heap2.max(), 2) - XCTAssertEqual(Array(heap2.unordered), [1, 2]) - XCTAssertEqual(heap2.replaceMax(with: 3), 2) - XCTAssertEqual(heap2.max(), 3) - XCTAssertEqual(Array(heap2.unordered), [1, 3]) - XCTAssertEqual(heap2.replaceMax(with: 0), 3) - XCTAssertEqual(heap2.max(), 1) - XCTAssertEqual(Array(heap2.unordered), [0, 1]) + expectEqual(heap2.max(), 2) + expectEqual(Array(heap2.unordered), [1, 2]) + expectEqual(heap2.replaceMax(with: 3), 2) + expectEqual(heap2.max(), 3) + expectEqual(Array(heap2.unordered), [1, 3]) + expectEqual(heap2.replaceMax(with: 0), 3) + expectEqual(heap2.max(), 1) + expectEqual(Array(heap2.unordered), [0, 1]) heap2 = Heap(raw: [5, 20, 31, 16, 8, 7, 18]) - XCTAssertEqual(heap2.max(), 31) - XCTAssertEqual(Array(heap2.unordered), [5, 20, 31, 16, 8, 7, 18]) - XCTAssertEqual(heap2.replaceMax(with: 29), 31) - XCTAssertEqual(Array(heap2.unordered), [5, 20, 29, 16, 8, 7, 18]) - XCTAssertEqual(heap2.max(), 29) - XCTAssertEqual(heap2.replaceMax(with: 19), 29) - XCTAssertEqual(Array(heap2.unordered), [5, 20, 19, 16, 8, 7, 18]) - XCTAssertEqual(heap2.max(), 20) - XCTAssertEqual(heap2.replaceMax(with: 15), 20) - XCTAssertEqual(Array(heap2.unordered), [5, 16, 19, 15, 8, 7, 18]) - XCTAssertEqual(heap2.max(), 19) - XCTAssertEqual(heap2.replaceMax(with: 4), 19) - XCTAssertEqual(Array(heap2.unordered), [4, 16, 18, 15, 8, 7, 5]) - XCTAssertEqual(heap2.max(), 18) + expectEqual(heap2.max(), 31) + expectEqual(Array(heap2.unordered), [5, 20, 31, 16, 8, 7, 18]) + expectEqual(heap2.replaceMax(with: 29), 31) + expectEqual(Array(heap2.unordered), [5, 20, 29, 16, 8, 7, 18]) + expectEqual(heap2.max(), 29) + expectEqual(heap2.replaceMax(with: 19), 29) + expectEqual(Array(heap2.unordered), [5, 20, 19, 16, 8, 7, 18]) + expectEqual(heap2.max(), 20) + expectEqual(heap2.replaceMax(with: 15), 20) + expectEqual(Array(heap2.unordered), [5, 16, 19, 15, 8, 7, 18]) + expectEqual(heap2.max(), 19) + expectEqual(heap2.replaceMax(with: 4), 19) + expectEqual(Array(heap2.unordered), [4, 16, 18, 15, 8, 7, 5]) + expectEqual(heap2.max(), 18) } // MARK: - func test_min_struct() { var heap = Heap() - XCTAssertNil(heap.min()) + expectNil(heap.min()) let firstTask = Task(name: "Do something", priority: 10) heap.insert(firstTask) - XCTAssertEqual(heap.min(), firstTask) + expectEqual(heap.min(), firstTask) let higherPriorityTask = Task(name: "Urgent", priority: 100) heap.insert(higherPriorityTask) - XCTAssertEqual(heap.min(), firstTask) + expectEqual(heap.min(), firstTask) let lowerPriorityTask = Task(name: "Get this done today", priority: 1) heap.insert(lowerPriorityTask) - XCTAssertEqual(heap.min(), lowerPriorityTask) + expectEqual(heap.min(), lowerPriorityTask) } func test_max_struct() { var heap = Heap() - XCTAssertNil(heap.max()) + expectNil(heap.max()) let firstTask = Task(name: "Do something", priority: 10) heap.insert(firstTask) - XCTAssertEqual(heap.max(), firstTask) + expectEqual(heap.max(), firstTask) let lowerPriorityTask = Task(name: "Get this done today", priority: 1) heap.insert(lowerPriorityTask) - XCTAssertEqual(heap.max(), firstTask) + expectEqual(heap.max(), firstTask) let higherPriorityTask = Task(name: "Urgent", priority: 100) heap.insert(higherPriorityTask) - XCTAssertEqual(heap.max(), higherPriorityTask) + expectEqual(heap.max(), higherPriorityTask) } func test_popMin_struct() { var heap = Heap() - XCTAssertNil(heap.popMin()) + expectNil(heap.popMin()) let lowPriorityTask = Task(name: "Do something when you have time", priority: 1) heap.insert(lowPriorityTask) @@ -444,15 +445,15 @@ final class HeapTests: XCTestCase { let urgentTask = Task(name: "Urgent", priority: 100) heap.insert(urgentTask) - XCTAssertEqual(heap.popMin(), lowPriorityTask) - XCTAssertEqual(heap.popMin(), highPriorityTask) - XCTAssertEqual(heap.popMin(), urgentTask) - XCTAssertNil(heap.popMin()) + expectEqual(heap.popMin(), lowPriorityTask) + expectEqual(heap.popMin(), highPriorityTask) + expectEqual(heap.popMin(), urgentTask) + expectNil(heap.popMin()) } func test_popMax_struct() { var heap = Heap() - XCTAssertNil(heap.popMax()) + expectNil(heap.popMax()) let lowPriorityTask = Task(name: "Do something when you have time", priority: 1) heap.insert(lowPriorityTask) @@ -463,53 +464,53 @@ final class HeapTests: XCTestCase { let urgentTask = Task(name: "Urgent", priority: 100) heap.insert(urgentTask) - XCTAssertEqual(heap.popMax(), urgentTask) - XCTAssertEqual(heap.popMax(), highPriorityTask) - XCTAssertEqual(heap.popMax(), lowPriorityTask) - XCTAssertNil(heap.popMax()) + expectEqual(heap.popMax(), urgentTask) + expectEqual(heap.popMax(), highPriorityTask) + expectEqual(heap.popMax(), lowPriorityTask) + expectNil(heap.popMax()) } // MARK: - func test_initializer_fromCollection() { var heap = Heap((1...20).shuffled()) - XCTAssertEqual(heap.max(), 20) + expectEqual(heap.max(), 20) - XCTAssertEqual(heap.popMin(), 1) - XCTAssertEqual(heap.popMax(), 20) - XCTAssertEqual(heap.popMin(), 2) - XCTAssertEqual(heap.popMax(), 19) - XCTAssertEqual(heap.popMin(), 3) - XCTAssertEqual(heap.popMax(), 18) - XCTAssertEqual(heap.popMin(), 4) - XCTAssertEqual(heap.popMax(), 17) - XCTAssertEqual(heap.popMin(), 5) - XCTAssertEqual(heap.popMax(), 16) - XCTAssertEqual(heap.popMin(), 6) - XCTAssertEqual(heap.popMax(), 15) - XCTAssertEqual(heap.popMin(), 7) - XCTAssertEqual(heap.popMax(), 14) - XCTAssertEqual(heap.popMin(), 8) - XCTAssertEqual(heap.popMax(), 13) - XCTAssertEqual(heap.popMin(), 9) - XCTAssertEqual(heap.popMax(), 12) - XCTAssertEqual(heap.popMin(), 10) - XCTAssertEqual(heap.popMax(), 11) + expectEqual(heap.popMin(), 1) + expectEqual(heap.popMax(), 20) + expectEqual(heap.popMin(), 2) + expectEqual(heap.popMax(), 19) + expectEqual(heap.popMin(), 3) + expectEqual(heap.popMax(), 18) + expectEqual(heap.popMin(), 4) + expectEqual(heap.popMax(), 17) + expectEqual(heap.popMin(), 5) + expectEqual(heap.popMax(), 16) + expectEqual(heap.popMin(), 6) + expectEqual(heap.popMax(), 15) + expectEqual(heap.popMin(), 7) + expectEqual(heap.popMax(), 14) + expectEqual(heap.popMin(), 8) + expectEqual(heap.popMax(), 13) + expectEqual(heap.popMin(), 9) + expectEqual(heap.popMax(), 12) + expectEqual(heap.popMin(), 10) + expectEqual(heap.popMax(), 11) } func test_initializer_fromSequence() { let heap = Heap((1...).prefix(20)) - XCTAssertEqual(heap.count, 20) + expectEqual(heap.count, 20) } func test_initializer_fromArrayLiteral() { var heap: Heap = [1, 3, 5, 7, 9] - XCTAssertEqual(heap.count, 5) + expectEqual(heap.count, 5) - XCTAssertEqual(heap.popMax(), 9) - XCTAssertEqual(heap.popMax(), 7) - XCTAssertEqual(heap.popMax(), 5) - XCTAssertEqual(heap.popMax(), 3) - XCTAssertEqual(heap.popMax(), 1) + expectEqual(heap.popMax(), 9) + expectEqual(heap.popMax(), 7) + expectEqual(heap.popMax(), 5) + expectEqual(heap.popMax(), 3) + expectEqual(heap.popMax(), 1) } } From fbebb69a1b12c8e63692bc18bef5e4291abc76ec Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 13 Oct 2022 14:50:18 -0700 Subject: [PATCH 05/31] [Heap] Doc updates --- Sources/HeapModule/Heap+UnsafeHandle.swift | 5 +++++ Sources/HeapModule/Heap.swift | 21 ++++++++------------- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/Sources/HeapModule/Heap+UnsafeHandle.swift b/Sources/HeapModule/Heap+UnsafeHandle.swift index d20f10c0..5d59f329 100644 --- a/Sources/HeapModule/Heap+UnsafeHandle.swift +++ b/Sources/HeapModule/Heap+UnsafeHandle.swift @@ -352,6 +352,11 @@ extension Heap._UnsafeHandle { extension Heap._UnsafeHandle { @inlinable internal func heapify() { + // This is Floyd's linear-time heap construction algorithm. + // (https://en.wikipedia.org/wiki/Heapsort#Floyd's_heap_construction). + // + // FIXME: See if a more cache friendly algorithm would be faster. + let limit = count / 2 // The first offset without a left child var level = _Node.level(forOffset: limit &- 1) while level >= 0 { diff --git a/Sources/HeapModule/Heap.swift b/Sources/HeapModule/Heap.swift index 310c7099..995c3208 100644 --- a/Sources/HeapModule/Heap.swift +++ b/Sources/HeapModule/Heap.swift @@ -70,7 +70,7 @@ extension Heap { /// Inserts the given element into the heap. /// - /// - Complexity: O(log `count`) + /// - Complexity: O(log(`count`)) element comparisons @inlinable public mutating func insert(_ element: Element) { _storage.append(element) @@ -110,7 +110,7 @@ extension Heap { /// Removes and returns the element with the lowest priority, if available. /// - /// - Complexity: O(log `count`) + /// - Complexity: O(log(`count`)) element comparisons @inlinable public mutating func popMin() -> Element? { guard _storage.count > 0 else { return nil } @@ -131,7 +131,7 @@ extension Heap { /// Removes and returns the element with the highest priority, if available. /// - /// - Complexity: O(log `count`) + /// - Complexity: O(log(`count`)) element comparisons @inlinable public mutating func popMax() -> Element? { guard _storage.count > 2 else { return _storage.popLast() } @@ -158,7 +158,7 @@ extension Heap { /// /// The heap *must not* be empty. /// - /// - Complexity: O(log `count`) + /// - Complexity: O(log(`count`)) element comparisons @inlinable public mutating func removeMin() -> Element { return popMin()! @@ -168,7 +168,7 @@ extension Heap { /// /// The heap *must not* be empty. /// - /// - Complexity: O(log `count`) + /// - Complexity: O(log(`count`)) element comparisons @inlinable public mutating func removeMax() -> Element { return popMax()! @@ -183,7 +183,7 @@ extension Heap { /// minimum value. /// - Returns: The original minimum value before the replacement. /// - /// - Complexity: O(log `count`) + /// - Complexity: O(log(`count`)) element comparisons @inlinable @discardableResult public mutating func replaceMin(with replacement: Element) -> Element { @@ -208,7 +208,7 @@ extension Heap { /// value. /// - Returns: The original maximum value before the replacement. /// - /// - Complexity: O(log `count`) + /// - Complexity: O(log(`count`)) element comparisons @inlinable @discardableResult public mutating func replaceMax(with replacement: Element) -> Element { @@ -239,14 +239,9 @@ extension Heap { extension Heap { /// Initializes a heap from a sequence. /// - /// - Complexity: O(*n*), where *n* is the length of `elements`. + /// - Complexity: O(*n*), where *n* is the number of items in `elements`. @inlinable public init(_ elements: S) where S.Element == Element { - // This is Floyd's linear-time heap construction algorithm. - // (https://en.wikipedia.org/wiki/Heapsort#Floyd's_heap_construction). - // - // FIXME: See if a more cache friendly algorithm would be faster. - _storage = ContiguousArray(elements) guard _storage.count > 1 else { return } From dc01b52a21972544a5a31cf7321dcde3578c623e Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 13 Oct 2022 14:51:04 -0700 Subject: [PATCH 06/31] [Heap] Fix stray character in COLLECTION_INTERNAL_CHECKS condition --- Sources/HeapModule/Heap+Invariants.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/HeapModule/Heap+Invariants.swift b/Sources/HeapModule/Heap+Invariants.swift index ab1d891a..d303a30e 100644 --- a/Sources/HeapModule/Heap+Invariants.swift +++ b/Sources/HeapModule/Heap+Invariants.swift @@ -16,7 +16,7 @@ extension Heap { _isCollectionsInternalCheckingEnabled } - #if COLLECTIONS_INTERNAL_CHECKSx + #if COLLECTIONS_INTERNAL_CHECKS /// Visits each item in the heap in depth-first order, verifying that the /// contents satisfy the min-max heap property. @inlinable From 098495b4ab3a51feaf7052f1193b753274d50bcc Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 13 Oct 2022 14:51:54 -0700 Subject: [PATCH 07/31] [Heap] Add more exhaustive tests for some critical paths --- Tests/HeapTests/HeapTests.swift | 49 +++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/Tests/HeapTests/HeapTests.swift b/Tests/HeapTests/HeapTests.swift index a39af8bc..45792c7e 100644 --- a/Tests/HeapTests/HeapTests.swift +++ b/Tests/HeapTests/HeapTests.swift @@ -84,6 +84,23 @@ final class HeapTests: CollectionTestCase { expectEqual(heap.count, 1) } + func test_insert_random() { + let c = 128 + withEvery("seed", in: 0 ..< 5_000) { seed in + var rng = RepeatableRandomNumberGenerator(seed: seed) + let input = (0 ..< c).shuffled(using: &rng) + var heap: Heap = [] + var i = 0 + withEvery("value", in: input) { value in + expectEqual(heap.count, i) + heap.insert(value) + i += 1 + expectEqual(heap.count, i) + } + expectEqualElements(heap.itemsInAscendingOrder(), 0 ..< c) + } + } + func test_insert_contentsOf() { var heap = Heap() heap.insert(contentsOf: (1...10).shuffled()) @@ -121,6 +138,17 @@ final class HeapTests: CollectionTestCase { expectNil(heap.popMin()) } + func test_insert_contentsOf_exhaustive() { + withEvery("c", in: 0 ..< 15) { c in + withEverySubset("a", of: 0 ..< c) { a in + let startInput = (0 ..< c).filter { !a.contains($0) } + var heap = Heap(startInput) + heap.insert(contentsOf: a.shuffled()) + expectEqualElements(heap.itemsInAscendingOrder(), 0 ..< c) + } + } + } + func test_min() { var heap = Heap() expectNil(heap.min()) @@ -513,4 +541,25 @@ final class HeapTests: CollectionTestCase { expectEqual(heap.popMax(), 3) expectEqual(heap.popMax(), 1) } + + func test_initializer_fromSequence_random() { + withEvery("c", in: 0 ... 128) { c in + withEvery( + "seed", in: 0 ..< Swift.min((c + 2) * (c + 1), 100) + ) { seed in + var rng = RepeatableRandomNumberGenerator(seed: seed) + let input = (0 ..< c).shuffled(using: &rng) + let heap = Heap(input) + if c > 0 { + expectEqual(heap.min(), 0) + expectEqual(heap.max(), c - 1) + expectEqualElements(heap.itemsInAscendingOrder(), 0 ..< c) + } else { + expectNil(heap.min()) + expectNil(heap.max()) + expectEqualElements(heap.itemsInAscendingOrder(), []) + } + } + } + } } From 2e9447fb1ccb5c9cd2ce04baa6ff693436f74466 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 13 Oct 2022 15:45:08 -0700 Subject: [PATCH 08/31] [_CollectionsTestSupport] Richer support for combinatorial testing --- .../AssertionContexts/Combinatorics.swift | 65 +++++++++++++++++++ .../CombinatoricsChecks.swift | 51 +++++++++++++++ .../Utilities.swift | 27 -------- 3 files changed, 116 insertions(+), 27 deletions(-) create mode 100644 Tests/CollectionsTestSupportTests/CombinatoricsChecks.swift diff --git a/Sources/_CollectionsTestSupport/AssertionContexts/Combinatorics.swift b/Sources/_CollectionsTestSupport/AssertionContexts/Combinatorics.swift index 6ada6e66..120c0b01 100644 --- a/Sources/_CollectionsTestSupport/AssertionContexts/Combinatorics.swift +++ b/Sources/_CollectionsTestSupport/AssertionContexts/Combinatorics.swift @@ -212,3 +212,68 @@ public func withHiddenCopies< checker(copy) return result } + +/// Run the supplied closure with all subsets `items` in a loop, +/// recording the current subset in the test trace stack. +/// +/// The subsets are generated so that they contain elements in the same order +/// as the original collection. +public func withEverySubset( + _ label: String, + of items: C, + body: ([C.Element]) -> Void +) { + var set: [C.Element] = [] + _withEverySubset(label, of: items, extending: &set, body: body) +} + +func _withEverySubset( + _ label: String, + of items: C, + extending set: inout [C.Element], + body: ([C.Element]) -> Void +) { + guard let item = items.first else { + let entry = TestContext.current.push("\(label): \(set)") + defer { TestContext.current.pop(entry) } + body(set) + return + } + _withEverySubset(label, of: items.dropFirst(), extending: &set, body: body) + set.append(item) + _withEverySubset(label, of: items.dropFirst(), extending: &set, body: body) + set.removeLast() +} + +public func withEveryPermutation( + _ label: String, + of items: C, + body: ([C.Element]) -> Void +) { + func send(_ items: [C.Element]) { + let entry = TestContext.current.push("\(label): \(items)") + body(items) + TestContext.current.pop(entry) + } + + // Heap's algorithm. + var items = Array(items) + send(items) + var i = 1 + var c = [Int](repeating: 0, count: items.count) + while i < items.count { + if c[i] < i { + if i.isMultiple(of: 2) { + items.swapAt(0, i) + } else { + items.swapAt(c[i], i) + } + send(items) + c[i] += 1 + i = 1 + } else { + c[i] = 0 + i += 1 + } + } +} diff --git a/Tests/CollectionsTestSupportTests/CombinatoricsChecks.swift b/Tests/CollectionsTestSupportTests/CombinatoricsChecks.swift new file mode 100644 index 00000000..3309fa0a --- /dev/null +++ b/Tests/CollectionsTestSupportTests/CombinatoricsChecks.swift @@ -0,0 +1,51 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2022 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 +// +//===----------------------------------------------------------------------===// + +import XCTest +import _CollectionsTestSupport + +class CombinatoricsTests: CollectionTestCase { + func testEverySubset_smoke() { + func collectSubsets(of set: [Int]) -> Set<[Int]> { + var result: Set<[Int]> = [] + withEverySubset("subset", of: set) { subset in + let r = result.insert(subset) + expectTrue(r.inserted) + } + return result + } + + expectEqual(collectSubsets(of: []), [[]]) + expectEqual(collectSubsets(of: [0]), [[], [0]]) + expectEqual(collectSubsets(of: [0, 1]), [[], [0], [1], [0, 1]]) + expectEqual( + collectSubsets(of: [0, 1, 2]), + [[], [0], [1], [2], [0, 1], [0, 2], [1, 2], [0, 1, 2]]) + } + + func testEveryPermutation_smoke() { + func collectPermutations(of items: [Int]) -> Set<[Int]> { + var result: Set<[Int]> = [] + withEveryPermutation("permutation", of: items) { permutation in + let r = result.insert(permutation) + expectTrue(r.inserted) + } + return result + } + + expectEqual(collectPermutations(of: []), [[]]) + expectEqual(collectPermutations(of: [0]), [[0]]) + expectEqual(collectPermutations(of: [0, 1]), [[0, 1], [1, 0]]) + expectEqual( + collectPermutations(of: [0, 1, 2]), + [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]]) + } +} diff --git a/Tests/PersistentCollectionsTests/Utilities.swift b/Tests/PersistentCollectionsTests/Utilities.swift index 676e1d3b..428ee13a 100644 --- a/Tests/PersistentCollectionsTests/Utilities.swift +++ b/Tests/PersistentCollectionsTests/Utilities.swift @@ -241,30 +241,3 @@ func mutate( ) rethrows -> R { try body(&value) } - -func withEverySubset( - _ label: String, - of items: C, - body: ([C.Element]) -> Void -) { - var set: [C.Element] = [] - _withEverySubset(label, of: items, extending: &set, body: body) -} - -func _withEverySubset( - _ label: String, - of items: C, - extending set: inout [C.Element], - body: ([C.Element]) -> Void -) { - guard let item = items.first else { - let entry = TestContext.current.push("\(label): \(set)") - defer { TestContext.current.pop(entry) } - body(set) - return - } - _withEverySubset(label, of: items.dropFirst(), extending: &set, body: body) - set.append(item) - _withEverySubset(label, of: items.dropFirst(), extending: &set, body: body) - set.removeLast() -} From fc8092d0441e0073831d6b170c74b6cca0da9bf5 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 14 Oct 2022 10:34:58 -0700 Subject: [PATCH 09/31] [Heap] Small preparation for improving insert(contentsOf:) --- Sources/HeapModule/Heap+UnsafeHandle.swift | 24 ++++++++++++++-------- Sources/HeapModule/_Node.swift | 2 +- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/Sources/HeapModule/Heap+UnsafeHandle.swift b/Sources/HeapModule/Heap+UnsafeHandle.swift index 5d59f329..601a5ec6 100644 --- a/Sources/HeapModule/Heap+UnsafeHandle.swift +++ b/Sources/HeapModule/Heap+UnsafeHandle.swift @@ -361,16 +361,22 @@ extension Heap._UnsafeHandle { var level = _Node.level(forOffset: limit &- 1) while level >= 0 { let nodes = _Node.allNodes(onLevel: level, limit: limit) - if _Node.isMinLevel(level) { - nodes?._forEach { node in - trickleDownMin(node) - } - } else { - nodes?._forEach { node in - trickleDownMax(node) - } - } + _heapify(level, nodes) level &-= 1 } } + + @inlinable + internal func _heapify(_ level: Int, _ nodes: ClosedRange<_Node>?) { + guard let nodes = nodes else { return } + if _Node.isMinLevel(level) { + nodes._forEach { node in + trickleDownMin(node) + } + } else { + nodes._forEach { node in + trickleDownMax(node) + } + } + } } diff --git a/Sources/HeapModule/_Node.swift b/Sources/HeapModule/_Node.swift index 02927814..a6763960 100644 --- a/Sources/HeapModule/_Node.swift +++ b/Sources/HeapModule/_Node.swift @@ -154,7 +154,7 @@ extension _Node { guard first.offset < limit else { return nil } var last = self.lastNode(onLevel: level) if last.offset >= limit { - last = _Node(offset: limit &- 1, level: level) + last.offset = limit &- 1 } return ClosedRange(uncheckedBounds: (first, last)) } From 39bdcca7c95d731da2d068a2612478d81c02585b Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Sun, 16 Oct 2022 17:06:32 -0700 Subject: [PATCH 10/31] Update README files - Fix issues reported by @benrimmington (thanks!) - Update wording on evolving Swift toolchain requirements - Update contributor guide on adding a new data structure to better reflect reality - Add an extra sentence on combinatorial tests --- Documentation/Internals/README.md | 50 +++++++++++++++---------------- README.md | 31 ++++++++++++------- 2 files changed, 45 insertions(+), 36 deletions(-) diff --git a/Documentation/Internals/README.md b/Documentation/Internals/README.md index a5594c39..e71a9cb0 100644 --- a/Documentation/Internals/README.md +++ b/Documentation/Internals/README.md @@ -10,13 +10,13 @@ For more information on our benchmarking tool, please see its dedicated package, ## Test Support Library -The package comes with a rich test support library in the [Sources/_CollectionsTestSupport](./Sources/_CollectionsTestSupport) directory. These were loosely adapted from the contents of the `StdlibUnittest*` modules in the [Swift compiler repository](https://github.com/apple/swift/tree/main/stdlib/private), with some custom additions. +The package comes with a rich test support library in the [Sources/_CollectionsTestSupport](../../Sources/_CollectionsTestSupport) directory. These were loosely adapted from the contents of the `StdlibUnittest*` modules in the [Swift compiler repository](https://github.com/apple/swift/tree/main/stdlib/private), with some custom additions. These components would likely be of interest to the wider Swift community, but they aren't yet stable enough (or documented enough) to publish them. Accordingly, these testing helpers are currently considered implementation details of this package, and are subject to change at whim. The test support library currently provides the following functionality: -- [`AssertionContexts`](./Sources/CollectionsTestSupport/AssertionContexts): Custom test assertions with support for keeping track of nested context information, including stopping execution when the current context matches a particular value. (Useful for debugging combinatorial tests.) +- [`AssertionContexts`](../../Sources/CollectionsTestSupport/AssertionContexts): Custom test assertions with support for keeping track of nested context information, including stopping execution when the current context matches a particular value. (Useful for debugging combinatorial tests.)
Click here for a short demonstration @@ -62,7 +62,7 @@ The test support library currently provides the following functionality:
-- [`Combinatorics`](./Sources/CollectionsTestSupport/AssertionContexts/Combinatorics.swift): Basic support for exhaustive combinatorial testing. This allows us to easily verify that a collection operation works correctly on all possible instances up to a certain size, including behavioral variations such as unique/shared storage. +- [`Combinatorics`](../../Sources/CollectionsTestSupport/AssertionContexts/Combinatorics.swift): Basic support for exhaustive combinatorial testing. This allows us to easily verify that a collection operation works correctly on all possible instances up to a certain size, including behavioral variations such as unique/shared storage. This file also contains a basic set of functions for executing the same test code for all subsets or all permutations of a given collection, with each iteration registered in the current test context, for easy reproduction of failed cases.
Click here for an example @@ -84,35 +84,35 @@ The test support library currently provides the following functionality: } } ``` - +
- -- [`ConformanceCheckers`](./Sources/CollectionsTestSupport/ConformanceCheckers): A set of generic, semi-automated protocol conformance tests for some Standard Library protocols. These can be used to easily validate the custom protocol conformances provided by this package. These checks aren't (can't be) complete -- but when used correctly, they are able to detect most accidental mistakes. + +- [`ConformanceCheckers`](../../Sources/CollectionsTestSupport/ConformanceCheckers): A set of generic, semi-automated protocol conformance tests for some Standard Library protocols. These can be used to easily validate the custom protocol conformances provided by this package. These checks aren't (can't be) complete -- but when used correctly, they are able to detect most accidental mistakes. We currently have conformance checkers for the following protocols: - - [`Sequence`](./Sources/CollectionsTestSupport/ConformanceCheckers/CheckSequence.swift) - - [`Collection`](./Sources/CollectionsTestSupport/ConformanceCheckers/CheckCollection.swift) - - [`BidirectionalCollection`](./Sources/CollectionsTestSupport/ConformanceCheckers/CheckBidirectionalCollection.swift) - - [`Equatable`](./Sources/CollectionsTestSupport/ConformanceCheckers/CheckEquatable.swift) - - [`Hashable`](./Sources/CollectionsTestSupport/ConformanceCheckers/CheckHashable.swift) - - [`Comparable`](./Sources/CollectionsTestSupport/ConformanceCheckers/CheckComparable.swift) + - [`Sequence`](../../Sources/CollectionsTestSupport/ConformanceCheckers/CheckSequence.swift) + - [`Collection`](../../Sources/CollectionsTestSupport/ConformanceCheckers/CheckCollection.swift) + - [`BidirectionalCollection`](../../Sources/CollectionsTestSupport/ConformanceCheckers/CheckBidirectionalCollection.swift) + - [`Equatable`](../../Sources/CollectionsTestSupport/ConformanceCheckers/CheckEquatable.swift) + - [`Hashable`](../../Sources/CollectionsTestSupport/ConformanceCheckers/CheckHashable.swift) + - [`Comparable`](../../Sources/CollectionsTestSupport/ConformanceCheckers/CheckComparable.swift) -- [`MinimalTypes`](./Sources/CollectionsTestSupport/MinimalTypes): Minimally conforming implementations for standard protocols. These types conform to various standard protocols by implementing the requirements in as narrow-minded way as possible -- sometimes going to extreme lengths to, say, implement collection index invalidation logic in the most unhelpful way possible. +- [`MinimalTypes`](../../Sources/CollectionsTestSupport/MinimalTypes): Minimally conforming implementations for standard protocols. These types conform to various standard protocols by implementing the requirements in as narrow-minded way as possible -- sometimes going to extreme lengths to, say, implement collection index invalidation logic in the most unhelpful way possible. - - [`MinimalSequence`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalSequence.swift) - - [`MinimalCollection`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalCollection.swift) - - [`MinimalBidirectionalCollection`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalBidirectionalCollection.swift) - - [`MinimalRandomAccessCollection`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalRandomAccessCollection.swift) - - [`MinimalMutableRandomAccessCollection`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalMutableRandomAccessCollection.swift) - - [`MinimalRangeReplaceableRandomAccessCollection`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalRangeReplaceableRandomAccessCollection.swift) - - [`MinimalMutableRangeReplaceableRandomAccessCollection`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalMutableRangeReplaceableRandomAccessCollection.swift) - - [`MinimalIterator`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalIterator.swift) - - [`MinimalIndex`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalIndex.swift) - - [`MinimalEncoder`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalEncoder.swift) - - [`MinimalDecoder`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalDecoder.swift) + - [`MinimalSequence`](../../Sources/CollectionsTestSupport/MinimalTypes/MinimalSequence.swift) + - [`MinimalCollection`](../../Sources/CollectionsTestSupport/MinimalTypes/MinimalCollection.swift) + - [`MinimalBidirectionalCollection`](../../Sources/CollectionsTestSupport/MinimalTypes/MinimalBidirectionalCollection.swift) + - [`MinimalRandomAccessCollection`](../../Sources/CollectionsTestSupport/MinimalTypes/MinimalRandomAccessCollection.swift) + - [`MinimalMutableRandomAccessCollection`](../../Sources/CollectionsTestSupport/MinimalTypes/MinimalMutableRandomAccessCollection.swift) + - [`MinimalRangeReplaceableRandomAccessCollection`](../../Sources/CollectionsTestSupport/MinimalTypes/MinimalRangeReplaceableRandomAccessCollection.swift) + - [`MinimalMutableRangeReplaceableRandomAccessCollection`](../../Sources/CollectionsTestSupport/MinimalTypes/MinimalMutableRangeReplaceableRandomAccessCollection.swift) + - [`MinimalIterator`](../../Sources/CollectionsTestSupport/MinimalTypes/MinimalIterator.swift) + - [`MinimalIndex`](../../Sources/CollectionsTestSupport/MinimalTypes/MinimalIndex.swift) + - [`MinimalEncoder`](../../Sources/CollectionsTestSupport/MinimalTypes/MinimalEncoder.swift) + - [`MinimalDecoder`](../../Sources/CollectionsTestSupport/MinimalTypes/MinimalDecoder.swift) -- [`Utilities`](./Sources/CollectionsTestSupport/Utilities): Utility types. Wrapper types for boxed values, a simple deterministic random number generator, and a lifetime tracker for catching simple memory management issues such as memory leaks. (The [Address Sanitizer][asan] can be used to catch more serious problems.) +- [`Utilities`](../../Sources/CollectionsTestSupport/Utilities): Utility types. Wrapper types for boxed values, a simple deterministic random number generator, and a lifetime tracker for catching simple memory management issues such as memory leaks. (The [Address Sanitizer][asan] can be used to catch more serious problems.) [asan]: https://developer.apple.com/documentation/xcode/diagnosing_memory_thread_and_crash_issues_early?language=objc diff --git a/README.md b/README.md index 19d51d57..51009808 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ Read more about the package, and the intent behind it, in the [announcement on s The package currently provides the following implementations: -- [`BitSet`][BitSet] and [`BitArray`][BitArray], dynamic bit vectors. +- [`BitSet`][BitSet] and [`BitArray`][BitArray], dynamic bit collections. - [`Deque`][Deque], a double-ended queue backed by a ring buffer. Deques are range-replaceable, mutable, random-access collections. @@ -71,14 +71,14 @@ Note that contents of the `Tests`, `Utils` and `Benchmarks` subdirectories aren' Future minor versions of the package may update these rules as needed. -We'd like this package to quickly embrace Swift language and toolchain improvements that are relevant to its mandate. Accordingly, from time to time, we expect that new versions of this package will require clients to upgrade to a more recent Swift toolchain release. (This allows the package to make use of new language/stdlib features, build on compiler bug fixes, and adopt new package manager functionality as soon as they are available.) Requiring a new Swift release will only need a minor version bump. +We'd like this package to quickly embrace Swift language and toolchain improvements that are relevant to its mandate. Accordingly, from time to time, new versions of this package require clients to upgrade to a more recent Swift toolchain release. (This allows the package to make use of new language/stdlib features, build on compiler bug fixes, and adopt new package manager functionality as soon as they are available.) Patch (i.e., bugfix) releases will not increase the required toolchain version, but any minor (i.e., new feature) release may do so. The following table maps existing package releases to their minimum required Swift toolchain release: -| Package version | Swift version | -|---|---|---| -| swift-collections 1.0.x | >= Swift 5.3 | -| swift-collections 1.1.x | >= Swift 5.5 | +| Package version | Swift version | Xcode release | +| ----------------------- | ------------- | ------------- | +| swift-collections 1.0.x | >= Swift 5.3 | >= Xcode 12 | +| swift-collections 1.1.x | >= Swift 5.5 | >= Xcode 13 | (Note: the package has no minimum deployment target, so while it does require clients to use a recent Swift toolchain to build it, the code itself is able to run on any OS release that supports running Swift code.) @@ -145,11 +145,20 @@ By submitting a pull request, you represent that you have the right to license y #### Proposing the addition of a new data structure -1. Start a topic on the [forum], explaining why you believe it would be important to implement the data structure. This way we can figure out if it would be right for the package, discuss implementation strategies, and plan to allocate capacity to help. -2. When maintainers agreed to your implementation plan, start work on it, and submit a PR with your implementation as soon as you have something that's ready to show! We'd love to get involved as early as you like. -3. Participate in the review discussion, and adapt the code accordingly. Sometimes we may need to go through several revisions! This is fine -- it makes the end result that much better. -3. When there is a consensus that the feature is ready, and the implementation is fully tested and documented, the PR will be merged by a maintainer. -4. Celebrate! You've achieved something great! +We intend this package to collect generally useful data structures -- the ones that ought to be within easy reach of every Swift engineer's basic toolbox. The implementations we ship need to be of the highest technical quality, polished to the same shine as anything that gets included in the Swift Standard Library. (The only real differences are that this package isn't under the formal Swift Evolution process, and its code isn't ABI stable.) + +Accordingly, adding a new data structure to this package is not an easy or quick process, and not all useful data structures are going to be a good fit. + +If you have an idea for a data structure that might make a good addition to this package, please start a topic on the [forum], explaining why you believe it would be important to implement it. This way we can figure out if it would be right for the package, discuss implementation strategies, and plan to allocate capacity to help. + +Not all data structures will reach a high enough level of usefulness to ship in this package -- those that have a more limited audience might work better as a standalone package. Of course, reasonable people might disagree on the importance of including any particular data structure; but at the end of the day, the decision whether to take an implementation is up to the maintainers of this package. + +If maintainers have agreed that your implementation would likely make a good addition, then it's time to start work on it. Submit a PR with your implementation as soon as you have something that's ready to show! We'd love to get involved as early as you like. Historically, the best additions resulted from close work between the contributor and a package maintainer. + +Participate in the review discussion, and adapt code accordingly. Sometimes we may need to go through several revisions over multiple months! This is fine -- it makes the end result that much better. When there is a consensus that the feature is ready, and the implementation is fully tested and documented, the PR will be merged by a maintainer. This is good time for a small celebration -- merging is a good indicator that the addition will ship at some point. + +Historically, PRs adding a new data structure have typically been merged to a new feature branch rather than directly to a release branch or `main`, and there was an extended amount of time between the initial merge and the tag that shipped the new feature. Nobody likes to wait, but getting a new data structure implementation from a state that was ready to merge to a state that's ready to ship is actually quite difficult work, and it takes maintainer time and effort that needs to be scheduled in advance. The closer an implementation is to the coding conventions and performance baseline of the Standard Library, the shorter this wait is likely to become, and the fewer changes there will be between merging and shipping. + ### Code of Conduct From 1490835b289653b145b91a16fe5522d928509efb Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 18 Oct 2022 20:44:46 -0700 Subject: [PATCH 11/31] [manifest] Exclude CMakeLists.txt; remove unnecessary path settings; reindent --- Package.swift | 31 ++++++++++++++++--------------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/Package.swift b/Package.swift index 3a51dc49..04c36b49 100644 --- a/Package.swift +++ b/Package.swift @@ -64,7 +64,6 @@ let package = Package( "OrderedCollections", "PersistentCollections", ], - path: "Sources/Collections", exclude: ["CMakeLists.txt"], swiftSettings: settings), @@ -86,13 +85,14 @@ let package = Package( .target( name: "_CollectionsUtilities", + exclude: ["CMakeLists.txt"], swiftSettings: settings), // BitSet, BitArray .target( name: "BitCollections", dependencies: ["_CollectionsUtilities"], - path: "Sources/BitCollections", + exclude: ["CMakeLists.txt"], swiftSettings: settings), .testTarget( name: "BitCollectionsTests", @@ -112,14 +112,14 @@ let package = Package( // Heap .target( - name: "HeapModule", - dependencies: ["_CollectionsUtilities"], - exclude: ["CMakeLists.txt"], - swiftSettings: settings), + name: "HeapModule", + dependencies: ["_CollectionsUtilities"], + exclude: ["CMakeLists.txt"], + swiftSettings: settings), .testTarget( - name: "HeapTests", - dependencies: ["HeapModule", "_CollectionsTestSupport"], - swiftSettings: settings), + name: "HeapTests", + dependencies: ["HeapModule", "_CollectionsTestSupport"], + swiftSettings: settings), // OrderedSet, OrderedDictionary .target( @@ -134,12 +134,13 @@ let package = Package( // PersistentSet, PersistentDictionary .target( - name: "PersistentCollections", - dependencies: ["_CollectionsUtilities"], - swiftSettings: settings), + name: "PersistentCollections", + dependencies: ["_CollectionsUtilities"], + exclude: ["CMakeLists.txt"], + swiftSettings: settings), .testTarget( - name: "PersistentCollectionsTests", - dependencies: ["PersistentCollections", "_CollectionsTestSupport"], - swiftSettings: settings), + name: "PersistentCollectionsTests", + dependencies: ["PersistentCollections", "_CollectionsTestSupport"], + swiftSettings: settings), ] ) From 03832459ac991b677e9b15a162bee330bf89fe87 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 18 Oct 2022 21:28:26 -0700 Subject: [PATCH 12/31] Update README files, harder this time --- Documentation/Internals/README.md | 44 +++++++++++++++---------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/Documentation/Internals/README.md b/Documentation/Internals/README.md index e71a9cb0..c8430661 100644 --- a/Documentation/Internals/README.md +++ b/Documentation/Internals/README.md @@ -16,7 +16,7 @@ These components would likely be of interest to the wider Swift community, but t The test support library currently provides the following functionality: -- [`AssertionContexts`](../../Sources/CollectionsTestSupport/AssertionContexts): Custom test assertions with support for keeping track of nested context information, including stopping execution when the current context matches a particular value. (Useful for debugging combinatorial tests.) +- [`AssertionContexts`](../../Sources/_CollectionsTestSupport/AssertionContexts): Custom test assertions with support for keeping track of nested context information, including stopping execution when the current context matches a particular value. (Useful for debugging combinatorial tests.)
Click here for a short demonstration @@ -62,7 +62,7 @@ The test support library currently provides the following functionality:
-- [`Combinatorics`](../../Sources/CollectionsTestSupport/AssertionContexts/Combinatorics.swift): Basic support for exhaustive combinatorial testing. This allows us to easily verify that a collection operation works correctly on all possible instances up to a certain size, including behavioral variations such as unique/shared storage. This file also contains a basic set of functions for executing the same test code for all subsets or all permutations of a given collection, with each iteration registered in the current test context, for easy reproduction of failed cases. +- [`Combinatorics`](../../Sources/_CollectionsTestSupport/AssertionContexts/Combinatorics.swift): Basic support for exhaustive combinatorial testing. This allows us to easily verify that a collection operation works correctly on all possible instances up to a certain size, including behavioral variations such as unique/shared storage. This file also contains a basic set of functions for executing the same test code for all subsets or all permutations of a given collection, with each iteration registered in the current test context, for easy reproduction of failed cases.
Click here for an example @@ -87,32 +87,32 @@ The test support library currently provides the following functionality:
-- [`ConformanceCheckers`](../../Sources/CollectionsTestSupport/ConformanceCheckers): A set of generic, semi-automated protocol conformance tests for some Standard Library protocols. These can be used to easily validate the custom protocol conformances provided by this package. These checks aren't (can't be) complete -- but when used correctly, they are able to detect most accidental mistakes. +- [`ConformanceCheckers`](../../Sources/_CollectionsTestSupport/ConformanceCheckers): A set of generic, semi-automated protocol conformance tests for some Standard Library protocols. These can be used to easily validate the custom protocol conformances provided by this package. These checks aren't (can't be) complete -- but when used correctly, they are able to detect most accidental mistakes. We currently have conformance checkers for the following protocols: - - [`Sequence`](../../Sources/CollectionsTestSupport/ConformanceCheckers/CheckSequence.swift) - - [`Collection`](../../Sources/CollectionsTestSupport/ConformanceCheckers/CheckCollection.swift) - - [`BidirectionalCollection`](../../Sources/CollectionsTestSupport/ConformanceCheckers/CheckBidirectionalCollection.swift) - - [`Equatable`](../../Sources/CollectionsTestSupport/ConformanceCheckers/CheckEquatable.swift) - - [`Hashable`](../../Sources/CollectionsTestSupport/ConformanceCheckers/CheckHashable.swift) - - [`Comparable`](../../Sources/CollectionsTestSupport/ConformanceCheckers/CheckComparable.swift) + - [`Sequence`](../../Sources/_CollectionsTestSupport/ConformanceCheckers/CheckSequence.swift) + - [`Collection`](../../Sources/_CollectionsTestSupport/ConformanceCheckers/CheckCollection.swift) + - [`BidirectionalCollection`](../../Sources/_CollectionsTestSupport/ConformanceCheckers/CheckBidirectionalCollection.swift) + - [`Equatable`](../../Sources/_CollectionsTestSupport/ConformanceCheckers/CheckEquatable.swift) + - [`Hashable`](../../Sources/_CollectionsTestSupport/ConformanceCheckers/CheckHashable.swift) + - [`Comparable`](../../Sources/_CollectionsTestSupport/ConformanceCheckers/CheckComparable.swift) -- [`MinimalTypes`](../../Sources/CollectionsTestSupport/MinimalTypes): Minimally conforming implementations for standard protocols. These types conform to various standard protocols by implementing the requirements in as narrow-minded way as possible -- sometimes going to extreme lengths to, say, implement collection index invalidation logic in the most unhelpful way possible. +- [`MinimalTypes`](../../Sources/_CollectionsTestSupport/MinimalTypes): Minimally conforming implementations for standard protocols. These types conform to various standard protocols by implementing the requirements in as narrow-minded way as possible -- sometimes going to extreme lengths to, say, implement collection index invalidation logic in the most unhelpful way possible. - - [`MinimalSequence`](../../Sources/CollectionsTestSupport/MinimalTypes/MinimalSequence.swift) - - [`MinimalCollection`](../../Sources/CollectionsTestSupport/MinimalTypes/MinimalCollection.swift) - - [`MinimalBidirectionalCollection`](../../Sources/CollectionsTestSupport/MinimalTypes/MinimalBidirectionalCollection.swift) - - [`MinimalRandomAccessCollection`](../../Sources/CollectionsTestSupport/MinimalTypes/MinimalRandomAccessCollection.swift) - - [`MinimalMutableRandomAccessCollection`](../../Sources/CollectionsTestSupport/MinimalTypes/MinimalMutableRandomAccessCollection.swift) - - [`MinimalRangeReplaceableRandomAccessCollection`](../../Sources/CollectionsTestSupport/MinimalTypes/MinimalRangeReplaceableRandomAccessCollection.swift) - - [`MinimalMutableRangeReplaceableRandomAccessCollection`](../../Sources/CollectionsTestSupport/MinimalTypes/MinimalMutableRangeReplaceableRandomAccessCollection.swift) - - [`MinimalIterator`](../../Sources/CollectionsTestSupport/MinimalTypes/MinimalIterator.swift) - - [`MinimalIndex`](../../Sources/CollectionsTestSupport/MinimalTypes/MinimalIndex.swift) - - [`MinimalEncoder`](../../Sources/CollectionsTestSupport/MinimalTypes/MinimalEncoder.swift) - - [`MinimalDecoder`](../../Sources/CollectionsTestSupport/MinimalTypes/MinimalDecoder.swift) + - [`MinimalSequence`](../../Sources/_CollectionsTestSupport/MinimalTypes/MinimalSequence.swift) + - [`MinimalCollection`](../../Sources/_CollectionsTestSupport/MinimalTypes/MinimalCollection.swift) + - [`MinimalBidirectionalCollection`](../../Sources/_CollectionsTestSupport/MinimalTypes/MinimalBidirectionalCollection.swift) + - [`MinimalRandomAccessCollection`](../../Sources/_CollectionsTestSupport/MinimalTypes/MinimalRandomAccessCollection.swift) + - [`MinimalMutableRandomAccessCollection`](../../Sources/_CollectionsTestSupport/MinimalTypes/MinimalMutableRandomAccessCollection.swift) + - [`MinimalRangeReplaceableRandomAccessCollection`](../../Sources/_CollectionsTestSupport/MinimalTypes/MinimalRangeReplaceableRandomAccessCollection.swift) + - [`MinimalMutableRangeReplaceableRandomAccessCollection`](../../Sources/_CollectionsTestSupport/MinimalTypes/MinimalMutableRangeReplaceableRandomAccessCollection.swift) + - [`MinimalIterator`](../../Sources/_CollectionsTestSupport/MinimalTypes/MinimalIterator.swift) + - [`MinimalIndex`](../../Sources/_CollectionsTestSupport/MinimalTypes/MinimalIndex.swift) + - [`MinimalEncoder`](../../Sources/_CollectionsTestSupport/MinimalTypes/MinimalEncoder.swift) + - [`MinimalDecoder`](../../Sources/_CollectionsTestSupport/MinimalTypes/MinimalDecoder.swift) -- [`Utilities`](../../Sources/CollectionsTestSupport/Utilities): Utility types. Wrapper types for boxed values, a simple deterministic random number generator, and a lifetime tracker for catching simple memory management issues such as memory leaks. (The [Address Sanitizer][asan] can be used to catch more serious problems.) +- [`Utilities`](../../Sources/_CollectionsTestSupport/Utilities): Utility types. Wrapper types for boxed values, a simple deterministic random number generator, and a lifetime tracker for catching simple memory management issues such as memory leaks. (The [Address Sanitizer][asan] can be used to catch more serious problems.) [asan]: https://developer.apple.com/documentation/xcode/diagnosing_memory_thread_and_crash_issues_early?language=objc From 02ea4e849230bc2326c83c5560822a228d83afab Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 18 Oct 2022 21:44:24 -0700 Subject: [PATCH 13/31] [_CollectionsTestSupport] Move StringConvertibleValue under Utilities --- .../{MinimalTypes => Utilities}/StringConvertibleValue.swift | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Sources/_CollectionsTestSupport/{MinimalTypes => Utilities}/StringConvertibleValue.swift (100%) diff --git a/Sources/_CollectionsTestSupport/MinimalTypes/StringConvertibleValue.swift b/Sources/_CollectionsTestSupport/Utilities/StringConvertibleValue.swift similarity index 100% rename from Sources/_CollectionsTestSupport/MinimalTypes/StringConvertibleValue.swift rename to Sources/_CollectionsTestSupport/Utilities/StringConvertibleValue.swift From 5b5651957b3f5219cd7d5ddd6e987d759ea103ec Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 18 Oct 2022 21:57:46 -0700 Subject: [PATCH 14/31] [PersistentSet] Doc updates --- .../PersistentSet+Debugging.swift | 6 ++ .../PersistentSet+Equatable.swift | 10 ++++ ...sistentSet+ExpressibleByArrayLiteral.swift | 21 ++++--- .../PersistentSet/PersistentSet+Filter.swift | 10 ++++ .../PersistentSet+Hashable.swift | 4 ++ ...ersistentSet+SetAlgebra Initializers.swift | 28 +++++++++ .../PersistentSet+SetAlgebra basics.swift | 57 +++++++++++++++++++ ...rsistentSet+SetAlgebra fluent basics.swift | 17 ++++++ .../PersistentSet+SetAlgebra isEqual.swift | 49 ++++++++++++++++ ...sistentSet+SetAlgebra isStrictSubset.swift | 1 + 10 files changed, 194 insertions(+), 9 deletions(-) diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+Debugging.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+Debugging.swift index 59363858..9c108c37 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+Debugging.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+Debugging.swift @@ -12,6 +12,12 @@ import _CollectionsUtilities extension PersistentSet { + /// True if consistency checking is enabled in the implementation of this + /// type, false otherwise. + /// + /// Documented performance promises are null and void when this property + /// returns true -- for example, operations that are documented to take + /// O(1) time might take O(*n*) time, or worse. public static var _isConsistencyCheckingEnabled: Bool { _isCollectionsInternalCheckingEnabled } diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+Equatable.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+Equatable.swift index c4c388c2..82614846 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+Equatable.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+Equatable.swift @@ -12,6 +12,16 @@ import _CollectionsUtilities extension PersistentSet: Equatable { + /// Returns a Boolean value indicating whether two values are equal. + /// + /// Two persistent sets are considered equal if they contain the same + /// elements, but not necessarily in the same order. + /// + /// - Note: This simply forwards to the ``isEqual(to:)-3m3in`` method. + /// That method has additional overloads that can be used to compare + /// persistent sets with additional types. + /// + /// - Complexity: O(`min(left.count, right.count)`) @inlinable @inline(__always) public static func == (left: Self, right: Self) -> Bool { left.isEqual(to: right) diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+ExpressibleByArrayLiteral.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+ExpressibleByArrayLiteral.swift index b5b45297..d2eb3a8b 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+ExpressibleByArrayLiteral.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+ExpressibleByArrayLiteral.swift @@ -12,19 +12,22 @@ extension PersistentSet: ExpressibleByArrayLiteral { /// Creates a new set from the contents of an array literal. /// - /// Duplicate elements in the literal are allowed, but the resulting ordered - /// set will only contain the first occurrence of each. + /// Duplicate elements in the literal are allowed, but the resulting + /// persistent set will only contain the first occurrence of each. /// /// Do not call this initializer directly. It is used by the compiler when - /// you use an array literal. Instead, create a new ordered set using an array - /// literal as its value by enclosing a comma-separated list of values in - /// square brackets. You can use an array literal anywhere an ordered set is - /// expected by the type context. + /// you use an array literal. Instead, create a new persistent set using an + /// array literal as its value by enclosing a comma-separated list of values + /// in square brackets. You can use an array literal anywhere a peristent set + /// is expected by the type context. /// - /// - Parameter elements: A variadic list of elements of the new ordered set. + /// Like the standard `Set`, persistent sets do not preserve the order of + /// elements inside the array literal. /// - /// - Complexity: O(`elements.count`) if `Element` implements - /// high-quality hashing. + /// - Parameter elements: A variadic list of elements of the new set. + /// + /// - Complexity: O(`elements.count`) if `Element` properly implements + /// hashing. public init(arrayLiteral elements: Element...) { self.init(elements) } diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+Filter.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+Filter.swift index 3c57db5c..888a4447 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+Filter.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+Filter.swift @@ -10,6 +10,16 @@ //===----------------------------------------------------------------------===// extension PersistentSet { + /// Returns a new persistent set containing the values pairs of the ordered + /// set that satisfy the given predicate. + /// + /// - Parameter isIncluded: A closure that takes a value as its + /// argument and returns a Boolean value indicating whether the value + /// should be included in the returned set. + /// + /// - Returns: A set of the values that `isIncluded` allows. + /// + /// - Complexity: O(`count`) @inlinable public func filter( _ isIncluded: (Element) throws -> Bool diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+Hashable.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+Hashable.swift index c9e3c0d1..42cbf623 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+Hashable.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+Hashable.swift @@ -10,6 +10,10 @@ //===----------------------------------------------------------------------===// extension PersistentSet: Hashable { + /// Hashes the essential components of this value by feeding them into the + /// given hasher. + /// + /// Complexity: O(`count`) @inlinable public func hash(into hasher: inout Hasher) { let copy = hasher diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra Initializers.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra Initializers.swift index 10ce9bce..26608494 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra Initializers.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra Initializers.swift @@ -10,11 +10,27 @@ //===----------------------------------------------------------------------===// extension PersistentSet { + /// Creates an empty set. + /// + /// This initializer is equivalent to initializing with an empty array + /// literal. + /// + /// - Complexity: O(1) @inlinable public init() { self.init(_new: ._empty()) } + /// Creates a new set from a finite sequence of items. + /// + /// - Parameter items: The elements to use as members of the new set. + /// The sequence is allowed to contain duplicate elements, but only + /// the first duplicate instance is preserved in the result. + /// + /// - Complexity: This operation is expected to perform O(*n*) + /// hashing and equality comparisons on average (where *n* + /// is the number of elements in the sequence), provided that + /// `Element` properly implements hashing. @inlinable public init(_ items: __owned S) where S.Element == Element { if S.self == Self.self { @@ -27,11 +43,23 @@ extension PersistentSet { } } + /// Creates a new set from a an existing set. This is functionally the same as + /// copying the value of `items` into a new variable. + /// + /// - Parameter items: The elements to use as members of the new set. + /// + /// - Complexity: O(1) @inlinable public init(_ items: __owned Self) { self = items } + /// Creates a new persistent set from the keys view of an existing persistent + /// dictionary. + /// + /// - Parameter items: The elements to use as members of the new set. + /// + /// - Complexity: O(*items.count*) @inlinable public init( _ item: __owned PersistentDictionary.Keys diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra basics.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra basics.swift index 06512108..99ece768 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra basics.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra basics.swift @@ -12,11 +12,39 @@ import _CollectionsUtilities extension PersistentSet: SetAlgebra { + /// Returns a Boolean value that indicates whether the given element exists + /// in the set. + /// + /// - Parameter element: An element to look for in the set. + /// + /// - Returns: `true` if `member` exists in the set; otherwise, `false`. + /// + /// - Complexity: This operation is expected to perform O(1) hashing and + /// comparison operations on average, provided that `Element` implements + /// high-quality hashing. @inlinable public func contains(_ item: Element) -> Bool { _root.containsKey(.top, item, _Hash(item)) } + /// Insert a new member to this set, if the set doesn't already contain it. + /// + /// - Parameter newMember: The element to insert into the set. + /// + /// - Returns: `(true, newMember)` if `newMember` was not contained in the + /// set. If an element equal to `newMember` was already contained in the + /// set, the method returns `(false, oldMember)`, where `oldMember` is the + /// element that was equal to `newMember`. In some cases, `oldMember` may + /// be distinguishable from `newMember` by identity comparison or some + /// other means. + /// + /// - Complexity: If `newMember` is not already a member of `self`, and if + /// `self` isn't uniquely held, then this operation is expected to copy + /// at most O(log(`count`)) existing members, as long as `Element` properly implements hashing. + /// + /// In addition to this, this operation is expected to perform O(1) + /// hashing/comparison operations on the `Element` type (with the same + /// caveat.) @discardableResult @inlinable public mutating func insert( @@ -41,6 +69,18 @@ extension PersistentSet: SetAlgebra { return r.inserted } + /// Removes the given element from the set. + /// + /// - Parameter member: The element of the set to remove. + /// + /// - Returns: The element equal to `member` if `member` is contained in the + /// set; otherwise, `nil`. In some cases, the returned element may be + /// distinguishable from `newMember` by identity comparison or some other + /// means. + /// + /// - Complexity: The operation is expected to perform amortized + /// O(1) hashing/comparison operations on the `Element` type, if it + /// properly implements hashing. @discardableResult @inlinable public mutating func remove(_ member: Element) -> Element? { @@ -49,6 +89,23 @@ extension PersistentSet: SetAlgebra { return _root.remove(.top, member, hash)?.key } + /// Inserts the given element into the set unconditionally. + /// + /// If an element equal to `newMember` is already contained in the set, + /// `newMember` replaces the existing element. + /// + /// If `newMember` was not already a member, it gets inserted. + /// + /// - Parameter newMember: An element to insert into the set. + /// + /// - Returns: The original member equal to `newMember` if the set already + /// contained such a member; otherwise, `nil`. In some cases, the returned + /// element may be distinguishable from `newMember` by identity comparison + /// or some other means. + /// + /// - Complexity: This operation is expected to perform O(1) + /// hashing/comparison operations on the element type, provided that + /// `Element` properly implements hashing. @discardableResult @inlinable public mutating func update(with newMember: __owned Element) -> Element? { diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra fluent basics.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra fluent basics.swift index 1e89ed28..9764db72 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra fluent basics.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra fluent basics.swift @@ -10,6 +10,23 @@ //===----------------------------------------------------------------------===// extension PersistentSet { + /// Return a new set that contains `newMember` in addition to all existing + /// elements in this set. + /// + /// If `self` already contains `newMember`, then this simply returns self. + /// + /// - Parameter newMember: The element to insert into the set. + /// + /// - Returns: A new set containing `newMember` and all existing members of + /// `self`. + /// + /// - Complexity: The operation is expected to copy at most O(log(`count`)) + /// existing members if `newMember` is not already a member of `self`, + /// as long as `Element` properly implements hashing. + /// + /// In addition to this, this operation is expected to perform O(1) + /// hashing/comparison operations on the `Element` type (with the same + /// caveat.) @inlinable public func inserting(_ newMember: __owned Element) -> Self { let hash = _Hash(newMember) diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isEqual.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isEqual.swift index a5c856ca..f9a6bf1f 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isEqual.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isEqual.swift @@ -11,11 +11,37 @@ // FIXME: These are non-standard extensions generalizing ==. extension PersistentSet { + /// Returns a Boolean value indicating whether persistent sets are equal. Two + /// persistent sets are considered equal if they contain the same elements, + /// but not necessarily in the same order. + /// + /// - Parameter other: Another set. + /// + /// - Returns: `true` if the set is equal to `other`; otherwise, `false`. + /// + /// - Complexity: Generally O(`count`), as long as`Element` properly + /// implements hashing. That said, the implementation is careful to take + /// every available shortcut to reduce complexity, e.g. by skipping + /// comparing elements in shared subtrees. @inlinable public func isEqual(to other: Self) -> Bool { _root.isEqual(to: other._root, by: { _, _ in true }) } + /// Returns a Boolean value indicating whether a persistent set compares equal + /// to the given keys view of a persistent dictionary. The two input + /// collections are considered equal if they contain the same elements, + /// but not necessarily in the same order. + /// + /// - Parameter other: The keys view of a persistent dictionary. + /// + /// - Returns: `true` if the set contains exactly the same members as `other`; + /// otherwise, `false`. + /// + /// - Complexity: Generally O(`count`), as long as`Element` properly + /// implements hashing. That said, the implementation is careful to take + /// every available shortcut to reduce complexity, e.g. by skipping + /// comparing elements in shared subtrees. @inlinable public func isEqual( to other: PersistentDictionary.Keys @@ -23,6 +49,29 @@ extension PersistentSet { _root.isEqual(to: other._base._root, by: { _, _ in true }) } + /// Returns a Boolean value indicating whether this persistent set contains + /// the same elements as the given `other` sequence, but not necessarily + /// in the same order. + /// + /// Duplicate items in `other` do not prevent it from comparing equal to + /// `self`. + /// + /// let this: PersistentSet = [0, 1, 5, 6] + /// let that = [5, 5, 0, 1, 1, 6, 5, 0, 1, 6, 6, 5] + /// + /// this.isEqual(to: that) // true + /// + /// - Parameter other: The keys view of a persistent dictionary. + /// + /// - Returns: `true` if the set contains exactly the same members as `other`; + /// otherwise, `false`. This function does not consider the order of + /// elements and it ignores duplicate items in `other`. + /// + /// - Complexity: Generally O(*n*), where *n* is the number of items in + /// `other`, as long as`Element` properly implements hashing. + /// That said, the implementation is careful to take + /// every available shortcut to reduce complexity, e.g. by skipping + /// comparing elements in shared subtrees. @inlinable public func isEqual(to other: S) -> Bool where S.Element == Element diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSubset.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSubset.swift index e5f36c0d..9b3b211c 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSubset.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSubset.swift @@ -100,6 +100,7 @@ extension PersistentSet { return other.contains(where: { _ in true }) } if let match = other._customContainsEquatableElement(first) { + // Fast path: the sequence has fast containment checks. guard match else { return false } while let item = it.next() { guard other.contains(item) else { return false } From 2b4ec22949acbfa99f9e22c390d850a650f3d298 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 18 Oct 2022 22:03:29 -0700 Subject: [PATCH 15/31] [OrderedSet] Small doc updates/fixes --- .../OrderedSet/OrderedSet+Initializers.swift | 8 +++++--- .../OrderedSet/OrderedSet+Partial SetAlgebra+Basics.swift | 2 +- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Initializers.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Initializers.swift index e4cf7e94..e9b68df6 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Initializers.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Initializers.swift @@ -49,11 +49,13 @@ extension OrderedSet { /// Creates a new set from a finite sequence of items. /// /// - Parameter elements: The elements to use as members of the new set. + /// The sequence is allowed to contain duplicate elements, but only + /// the first duplicate instance is preserved in the result. /// /// - Complexity: This operation is expected to perform O(*n*) - /// comparisons on average (where *n* is the number of elements - /// in the sequence), provided that `Element` implements - /// high-quality hashing. + /// hashing and equality comparisons on average (where *n* + /// is the number of elements in the sequence), provided that + /// `Element` properly implements hashing. @inlinable public init(_ elements: S) where S.Element == Element { if S.self == Self.self { diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra+Basics.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra+Basics.swift index cd303b02..ecc6f7b5 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra+Basics.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra+Basics.swift @@ -55,7 +55,7 @@ extension OrderedSet { /// /// - Returns: The element equal to `member` if `member` is contained in the /// set; otherwise, `nil`. In some cases, the returned element may be - /// distinguishable from `newMember` by identity comparison or some other + /// distinguishable from `member` by identity comparison or some other /// means. /// /// - Complexity: O(`count`). Removing an element from the middle of the From f76630db8ec3003bc0685648c60dc9ddb27ca20d Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 18 Oct 2022 22:13:19 -0700 Subject: [PATCH 16/31] [Internals] Add missing internal checking predicates & docs for all --- .../BitArray/BitArray+Invariants.swift | 12 ++++++++++++ .../BitCollections/BitSet/BitSet+Invariants.swift | 12 ++++++++++++ Sources/DequeModule/Deque+Testing.swift | 6 ++++++ Sources/HeapModule/Heap+Invariants.swift | 6 ++++++ .../OrderedDictionary+Invariants.swift | 12 ++++++++++++ .../OrderedSet/OrderedSet+Invariants.swift | 12 ++++++++++++ .../PersistentDictionary+Debugging.swift | 6 ++++++ Sources/_CollectionsUtilities/Debugging.swift | 6 ++++++ 8 files changed, 72 insertions(+) diff --git a/Sources/BitCollections/BitArray/BitArray+Invariants.swift b/Sources/BitCollections/BitArray/BitArray+Invariants.swift index 561e909f..d194ea0b 100644 --- a/Sources/BitCollections/BitArray/BitArray+Invariants.swift +++ b/Sources/BitCollections/BitArray/BitArray+Invariants.swift @@ -9,7 +9,19 @@ // //===----------------------------------------------------------------------===// +import _CollectionsUtilities + extension BitArray { + /// True if consistency checking is enabled in the implementation of this + /// type, false otherwise. + /// + /// Documented performance promises are null and void when this property + /// returns true -- for example, operations that are documented to take + /// O(1) time might take O(*n*) time, or worse. + public static var _isConsistencyCheckingEnabled: Bool { + _isCollectionsInternalCheckingEnabled + } + #if COLLECTIONS_INTERNAL_CHECKS @inline(never) @_effects(releasenone) diff --git a/Sources/BitCollections/BitSet/BitSet+Invariants.swift b/Sources/BitCollections/BitSet/BitSet+Invariants.swift index 1a7b4bf8..c11ecf2b 100644 --- a/Sources/BitCollections/BitSet/BitSet+Invariants.swift +++ b/Sources/BitCollections/BitSet/BitSet+Invariants.swift @@ -9,7 +9,19 @@ // //===----------------------------------------------------------------------===// +import _CollectionsUtilities + extension BitSet { + /// True if consistency checking is enabled in the implementation of this + /// type, false otherwise. + /// + /// Documented performance promises are null and void when this property + /// returns true -- for example, operations that are documented to take + /// O(1) time might take O(*n*) time, or worse. + public static var _isConsistencyCheckingEnabled: Bool { + _isCollectionsInternalCheckingEnabled + } + #if COLLECTIONS_INTERNAL_CHECKS @inline(never) @_effects(releasenone) diff --git a/Sources/DequeModule/Deque+Testing.swift b/Sources/DequeModule/Deque+Testing.swift index 2c1a0e0a..bbc1fbf9 100644 --- a/Sources/DequeModule/Deque+Testing.swift +++ b/Sources/DequeModule/Deque+Testing.swift @@ -15,6 +15,12 @@ import _CollectionsUtilities // testing. extension Deque { + /// True if consistency checking is enabled in the implementation of this + /// type, false otherwise. + /// + /// Documented performance promises are null and void when this property + /// returns true -- for example, operations that are documented to take + /// O(1) time might take O(*n*) time, or worse. public static var _isConsistencyCheckingEnabled: Bool { _isCollectionsInternalCheckingEnabled } diff --git a/Sources/HeapModule/Heap+Invariants.swift b/Sources/HeapModule/Heap+Invariants.swift index d303a30e..12e9192a 100644 --- a/Sources/HeapModule/Heap+Invariants.swift +++ b/Sources/HeapModule/Heap+Invariants.swift @@ -12,6 +12,12 @@ import _CollectionsUtilities extension Heap { + /// True if consistency checking is enabled in the implementation of this + /// type, false otherwise. + /// + /// Documented performance promises are null and void when this property + /// returns true -- for example, operations that are documented to take + /// O(1) time might take O(*n*) time, or worse. public static var _isConsistencyCheckingEnabled: Bool { _isCollectionsInternalCheckingEnabled } diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Invariants.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Invariants.swift index fa3d01fe..58964d22 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Invariants.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Invariants.swift @@ -9,7 +9,19 @@ // //===----------------------------------------------------------------------===// +import _CollectionsUtilities + extension OrderedDictionary { + /// True if consistency checking is enabled in the implementation of this + /// type, false otherwise. + /// + /// Documented performance promises are null and void when this property + /// returns true -- for example, operations that are documented to take + /// O(1) time might take O(*n*) time, or worse. + public static var _isConsistencyCheckingEnabled: Bool { + _isCollectionsInternalCheckingEnabled + } + #if COLLECTIONS_INTERNAL_CHECKS @inline(never) @_effects(releasenone) public func _checkInvariants() { diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Invariants.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Invariants.swift index 51c853b7..53de455e 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Invariants.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Invariants.swift @@ -9,7 +9,19 @@ // //===----------------------------------------------------------------------===// +import _CollectionsUtilities + extension OrderedSet { + /// True if consistency checking is enabled in the implementation of this + /// type, false otherwise. + /// + /// Documented performance promises are null and void when this property + /// returns true -- for example, operations that are documented to take + /// O(1) time might take O(*n*) time, or worse. + public static var _isConsistencyCheckingEnabled: Bool { + _isCollectionsInternalCheckingEnabled + } + #if COLLECTIONS_INTERNAL_CHECKS @inlinable @inline(never) @_effects(releasenone) diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Debugging.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Debugging.swift index ed5645fb..5ad90df9 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Debugging.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Debugging.swift @@ -12,6 +12,12 @@ import _CollectionsUtilities extension PersistentDictionary { + /// True if consistency checking is enabled in the implementation of this + /// type, false otherwise. + /// + /// Documented performance promises are null and void when this property + /// returns true -- for example, operations that are documented to take + /// O(1) time might take O(*n*) time, or worse. public static var _isConsistencyCheckingEnabled: Bool { _isCollectionsInternalCheckingEnabled } diff --git a/Sources/_CollectionsUtilities/Debugging.swift b/Sources/_CollectionsUtilities/Debugging.swift index 0006548e..90470b0d 100644 --- a/Sources/_CollectionsUtilities/Debugging.swift +++ b/Sources/_CollectionsUtilities/Debugging.swift @@ -9,6 +9,12 @@ // //===----------------------------------------------------------------------===// +/// True if consistency checking is enabled in the implementation of the +/// Swift Collections package, false otherwise. +/// +/// Documented performance promises are null and void when this property +/// returns true -- for example, operations that are documented to take +/// O(1) time might take O(*n*) time, or worse. @inlinable @inline(__always) public var _isCollectionsInternalCheckingEnabled: Bool { #if COLLECTIONS_INTERNAL_CHECKS From 51a1554f894dc7267bcb44bcd24d22f5a2868830 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 18 Oct 2022 23:16:47 -0700 Subject: [PATCH 17/31] Introduce _UniqueCollection & _SortedCollection These marker-like protocols will allow certain generic operations to get a performance boost if the passed-in value happens to be guaranteed to contain unique elements or to be sorted. Also, review API checker protocols for Sets and sorted collections and adjust things as needed. BitSet gains custom implementations for min() and max() as part of these improvements. --- Package.swift | 2 +- .../BitCollections/BitSet/BitSet+Extras.swift | 8 +--- .../BitSet+Sorted Collection APIs.swift | 47 +++++++++++++++++++ .../BitSet/BitSet.Counted.swift | 4 ++ .../OrderedSet+RandomAccessCollection.swift | 4 ++ .../OrderedSet/OrderedSet+SubSequence.swift | 4 ++ .../PersistentSet/PersistentSet+Extras.swift | 4 ++ .../Utilities/SetAPIChecker.swift | 18 ++++--- .../SortedCollectionAPIChecker.swift | 29 ++++++++++++ .../_SortedCollections.swift | 27 +++++++++++ .../_UniqueCollection.swift | 37 +++++++++++++++ Tests/BitCollectionsTests/BitSetTests.swift | 8 +++- 12 files changed, 177 insertions(+), 15 deletions(-) create mode 100644 Sources/BitCollections/BitSet/BitSet+Sorted Collection APIs.swift create mode 100644 Sources/_CollectionsTestSupport/Utilities/SortedCollectionAPIChecker.swift create mode 100644 Sources/_CollectionsUtilities/_SortedCollections.swift create mode 100644 Sources/_CollectionsUtilities/_UniqueCollection.swift diff --git a/Package.swift b/Package.swift index 04c36b49..d9ef179b 100644 --- a/Package.swift +++ b/Package.swift @@ -70,7 +70,7 @@ let package = Package( // Testing support module .target( name: "_CollectionsTestSupport", - dependencies: [], + dependencies: ["_CollectionsUtilities"], swiftSettings: settings, linkerSettings: [ .linkedFramework( diff --git a/Sources/BitCollections/BitSet/BitSet+Extras.swift b/Sources/BitCollections/BitSet/BitSet+Extras.swift index 2f40b7e3..a7ce8fca 100644 --- a/Sources/BitCollections/BitSet/BitSet+Extras.swift +++ b/Sources/BitCollections/BitSet/BitSet+Extras.swift @@ -11,6 +11,8 @@ import _CollectionsUtilities +extension BitSet: _UniqueCollection {} + extension BitSet { /// Creates a new empty bit set with enough storage capacity to store values /// up to the given maximum value without reallocating storage. @@ -163,12 +165,6 @@ extension BitSet { return Int(bitPattern: index._value) } - /// Returns the current set (already sorted). - /// - /// - Complexity: O(1) - public func sorted() -> BitSet { self } - - /// Returns a new bit set containing the elements of the set that satisfy the /// given predicate. /// diff --git a/Sources/BitCollections/BitSet/BitSet+Sorted Collection APIs.swift b/Sources/BitCollections/BitSet/BitSet+Sorted Collection APIs.swift new file mode 100644 index 00000000..191afcf7 --- /dev/null +++ b/Sources/BitCollections/BitSet/BitSet+Sorted Collection APIs.swift @@ -0,0 +1,47 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2022 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 +// +//===----------------------------------------------------------------------===// + +import _CollectionsUtilities + +extension BitSet: _SortedCollection { + /// Returns the current set (already sorted). + /// + /// - Complexity: O(1) + public func sorted() -> BitSet { self } + + /// Returns the minimum element in this set. + /// + /// Bit sets are sorted, so the minimum element is always at the first + /// position in the set. + /// + /// - Returns: The bit set's minimum element. If the sequence has no + /// elements, returns `nil`. + /// + /// - Complexity: O(1) + @warn_unqualified_access + public func min() -> Element? { + first + } + + /// Returns the maximum element in this set. + /// + /// Bit sets are sorted, so the maximum element is always at the last + /// position in the set. + /// + /// - Returns: The bit set's maximum element. If the sequence has no + /// elements, returns `nil`. + /// + /// - Complexity: O(1) + @warn_unqualified_access + public func max() -> Element? { + last + } +} diff --git a/Sources/BitCollections/BitSet/BitSet.Counted.swift b/Sources/BitCollections/BitSet/BitSet.Counted.swift index 19fffc57..0b23bcda 100644 --- a/Sources/BitCollections/BitSet/BitSet.Counted.swift +++ b/Sources/BitCollections/BitSet/BitSet.Counted.swift @@ -9,6 +9,8 @@ // //===----------------------------------------------------------------------===// +import _CollectionsUtilities + extension BitSet { public struct Counted { @usableFromInline @@ -42,6 +44,8 @@ extension BitSet.Counted { #endif // COLLECTIONS_INTERNAL_CHECKS } +extension BitSet.Counted: _UniqueCollection {} + extension BitSet.Counted { public init() { self.init(BitSet()) diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+RandomAccessCollection.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+RandomAccessCollection.swift index 7e5eed85..c8b5dc8b 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+RandomAccessCollection.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+RandomAccessCollection.swift @@ -9,6 +9,8 @@ // //===----------------------------------------------------------------------===// +import _CollectionsUtilities + extension OrderedSet: Sequence { /// The type that allows iteration over an ordered set's elements. public typealias Iterator = IndexingIterator @@ -298,3 +300,5 @@ extension OrderedSet: RandomAccessCollection { _elements._failEarlyRangeCheck(range, bounds: bounds) } } + +extension OrderedSet: _UniqueCollection {} diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+SubSequence.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+SubSequence.swift index 9a537a28..e77bd27e 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+SubSequence.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+SubSequence.swift @@ -9,6 +9,8 @@ // //===----------------------------------------------------------------------===// +import _CollectionsUtilities + extension OrderedSet { /// A collection that represents a contiguous slice of an ordered set. /// @@ -103,6 +105,8 @@ extension OrderedSet.SubSequence: Sequence { } } +extension OrderedSet.SubSequence: _UniqueCollection {} + extension OrderedSet.SubSequence: RandomAccessCollection { /// The index type for ordered sets, `Int`. /// diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+Extras.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+Extras.swift index ac185803..989dec21 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+Extras.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+Extras.swift @@ -9,6 +9,10 @@ // //===----------------------------------------------------------------------===// +import _CollectionsUtilities + +extension PersistentSet: _UniqueCollection {} + extension PersistentSet { @discardableResult public mutating func remove(at position: Index) -> Element { diff --git a/Sources/_CollectionsTestSupport/Utilities/SetAPIChecker.swift b/Sources/_CollectionsTestSupport/Utilities/SetAPIChecker.swift index 691245ac..fede96d9 100644 --- a/Sources/_CollectionsTestSupport/Utilities/SetAPIChecker.swift +++ b/Sources/_CollectionsTestSupport/Utilities/SetAPIChecker.swift @@ -66,13 +66,17 @@ public protocol SetAPIChecker { mutating func formSymmetricDifference(_ other: __owned S) where S.Element == Element - - #if false - // Non-standard extensions - func isEqual(to other: Self) -> Bool - public func isEqual(to other: S) -> Bool - where S.Element == Element - #endif } extension Set: SetAPIChecker {} + + +public protocol SetAPIExtras: SetAPIChecker { + // Non-standard extensions + + mutating func update(_ member: Element, at index: Index) -> Element + + func isEqual(to other: Self) -> Bool + func isEqual(to other: S) -> Bool + where S.Element == Element +} diff --git a/Sources/_CollectionsTestSupport/Utilities/SortedCollectionAPIChecker.swift b/Sources/_CollectionsTestSupport/Utilities/SortedCollectionAPIChecker.swift new file mode 100644 index 00000000..97cd75a4 --- /dev/null +++ b/Sources/_CollectionsTestSupport/Utilities/SortedCollectionAPIChecker.swift @@ -0,0 +1,29 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2022 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 +// +//===----------------------------------------------------------------------===// + +import _CollectionsUtilities + +/// This protocol simply lists Collection/Sequence extensions that ought to be +/// customized for sorted collections. +/// +/// Conforming to this protocol admittedly doesn't do much, as the default +/// implementations already exist for most of these requirements +/// (but they aren't doing the right thing). +public protocol SortedCollectionAPIChecker: Collection, _SortedCollection +where Element: Comparable { + // This one actually does not come with a default implementation. + func sorted() -> Self + + // These are also defined on `Sequence`, but the default implementation does + // a linear search, which isn't what we want. + func min() -> Element? + func max() -> Element? +} diff --git a/Sources/_CollectionsUtilities/_SortedCollections.swift b/Sources/_CollectionsUtilities/_SortedCollections.swift new file mode 100644 index 00000000..22ba8b8b --- /dev/null +++ b/Sources/_CollectionsUtilities/_SortedCollections.swift @@ -0,0 +1,27 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2022 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 +// +//===----------------------------------------------------------------------===// + +/// A Collection type that is guaranteed to contain elements in monotonically +/// increasing order. (Duplicates are still allowed unless the collection +/// also conforms to `_UniqueCollection`.) +/// +/// Types conforming to this protocol must also conform to `Collection`, +/// with an `Element` type that conforms to `Comparable`. +/// (However, this protocol does not specify these as explicit requirements, +/// to allow simple conformance tests such as `someValue is _SortedCollection` +/// to be possible.) +/// +/// For any two valid indices `i` and `j` for a conforming collection `c` +/// (both below the end index), it must hold true that if `i < j`, then +/// `c[i] <= c[j]`. +public protocol _SortedCollection {} + +extension Slice: _SortedCollection where Base: _SortedCollection {} diff --git a/Sources/_CollectionsUtilities/_UniqueCollection.swift b/Sources/_CollectionsUtilities/_UniqueCollection.swift new file mode 100644 index 00000000..577b2f28 --- /dev/null +++ b/Sources/_CollectionsUtilities/_UniqueCollection.swift @@ -0,0 +1,37 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2022 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 +// +//===----------------------------------------------------------------------===// + +/// A Collection type that is guaranteed not to contain any duplicate elements. +/// +/// Types conforming to this protocol must also conform to `Collection`, +/// with an `Element` type that conforms to `Equatable`. +/// (However, this protocol does not specify these as explicit requirements, +/// to allow simple conformance tests such as `someValue is _SortedCollection` +/// to be possible.) +/// +/// For any two valid indices `i` and `j` in a conforming collection `c` +/// (both below the end index), it must hold true that if `i != j` then +/// `c[i] != c[j]`. +/// +/// Types that conform to this protocol should also implement the following +/// underscored requirements in a way that they never return nil values: +/// +/// - `Sequence._customContainsEquatableElement` +/// - `Collection._customIndexOfEquatableElement` +/// - `Collection._customLastIndexOfEquatableElement` +/// +/// The idea with these is that presumably a collection that can guarantee +/// element uniqueness has a way to quickly find existing elements. +public protocol _UniqueCollection {} + +extension Set: _UniqueCollection {} +extension Dictionary.Keys: _UniqueCollection {} +extension Slice: _UniqueCollection where Base: _UniqueCollection {} diff --git a/Tests/BitCollectionsTests/BitSetTests.swift b/Tests/BitCollectionsTests/BitSetTests.swift index 4cd7659a..c80b8f39 100644 --- a/Tests/BitCollectionsTests/BitSetTests.swift +++ b/Tests/BitCollectionsTests/BitSetTests.swift @@ -13,7 +13,13 @@ import XCTest import _CollectionsTestSupport import BitCollections -extension BitSet: SetAPIChecker {} +extension BitSet: SetAPIExtras { + public mutating func update(_ member: Int, at index: Index) -> Int { + fatalError("Not this one though") + } +} + +extension BitSet: SortedCollectionAPIChecker {} final class BitSetTest: CollectionTestCase { func test_empty_initializer() { From 86d429604ccb954396ecb8f1acd028cf056c4ff6 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 18 Oct 2022 23:48:07 -0700 Subject: [PATCH 18/31] [BitSet] Doc updates --- .../BitSet/BitSet+SetAlgebra basics.swift | 31 +++++++++++++++++-- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra basics.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra basics.swift index 2c4adb30..41237e13 100644 --- a/Sources/BitCollections/BitSet/BitSet+SetAlgebra basics.swift +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra basics.swift @@ -10,6 +10,14 @@ //===----------------------------------------------------------------------===// extension BitSet { + /// Returns a Boolean value that indicates whether the given element exists + /// in the set. + /// + /// - Parameter element: An element to look for in the set. + /// + /// - Returns: `true` if `member` exists in the set; otherwise, `false`. + /// + /// - Complexity: O(1) @usableFromInline internal func _contains(_ member: UInt) -> Bool { _read { $0.contains(member) } @@ -30,10 +38,27 @@ extension BitSet { } extension BitSet { + /// Insert the given element in the set if it is not already present. + /// + /// If an element equal to `newMember` is already contained in the set, this + /// method has no effect. + /// + /// If `newMember` was not already a member, it gets inserted into the set. + /// + /// - Parameter newMember: An element to insert into the set. + /// + /// - Returns: True if `newMember` was not contained in the + /// set, false otherwise. + /// + /// - Complexity: O(1) if the set is a unique value (with no other copies), + /// and the inserted value is not greater than the largest value currently + /// contained in the set (named *max*). Otherwise the complexity is + /// O(max(`newMember`, *max*)). @discardableResult - public mutating func _insert(_ i: UInt) -> Bool { - _ensureCapacity(forValue: i) - return _update { $0.insert(i) } + @usableFromInline + internal mutating func _insert(_ newMember: UInt) -> Bool { + _ensureCapacity(forValue: newMember) + return _update { $0.insert(newMember) } } /// Inserts the given element in the set if it is not already present. From 291623d391a88527107c0a92986fe1cd755e4e8f Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 19 Oct 2022 00:33:58 -0700 Subject: [PATCH 19/31] [BitSet] Implement isEqual(to:) family of functions --- Package.swift | 4 +- .../BitSet/BitSet+Equatable.swift | 9 +- .../BitSet/BitSet+SetAlgebra isEqual.swift | 105 ++++++++++++++++++ .../BitSet/BitSet.Counted.swift | 2 +- .../BitSet/BitSet._UnsafeHandle.swift | 29 +++++ Tests/BitCollectionsTests/BitSetTests.swift | 92 +++++++++++++++ 6 files changed, 237 insertions(+), 4 deletions(-) create mode 100644 Sources/BitCollections/BitSet/BitSet+SetAlgebra isEqual.swift diff --git a/Package.swift b/Package.swift index d9ef179b..54292671 100644 --- a/Package.swift +++ b/Package.swift @@ -96,7 +96,9 @@ let package = Package( swiftSettings: settings), .testTarget( name: "BitCollectionsTests", - dependencies: ["BitCollections", "_CollectionsTestSupport"], + dependencies: [ + "BitCollections", "_CollectionsTestSupport", "OrderedCollections" + ], swiftSettings: settings), // Deque diff --git a/Sources/BitCollections/BitSet/BitSet+Equatable.swift b/Sources/BitCollections/BitSet/BitSet+Equatable.swift index d4323b24..ce81333f 100644 --- a/Sources/BitCollections/BitSet/BitSet+Equatable.swift +++ b/Sources/BitCollections/BitSet/BitSet+Equatable.swift @@ -13,8 +13,13 @@ extension BitSet: Equatable { /// Returns a Boolean value indicating whether two values are equal. Two /// bit sets are considered equal if they contain the same elements. /// - /// - Complexity: O(*max*), where *max* is value of the largest member of either set. + /// - Note: This simply forwards to the ``isEqual(to:)-5zfpo`` method. + /// That method has additional overloads that can be used to compare + /// bit sets with additional types. + /// + /// - Complexity: O(*max*), where *max* is value of the largest member of + /// either set. public static func ==(left: Self, right: Self) -> Bool { - left._storage == right._storage + left.isEqual(to: right) } } diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isEqual.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isEqual.swift new file mode 100644 index 00000000..04e58099 --- /dev/null +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isEqual.swift @@ -0,0 +1,105 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2022 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 +// +//===----------------------------------------------------------------------===// + +import _CollectionsUtilities + +// FIXME: These are non-standard extensions generalizing ==. +extension BitSet { + /// Returns a Boolean value indicating whether two bit sets are equal. Two + /// bit sets are considered equal if they contain the same elements. + /// + /// - Complexity: O(*max*), where *max* is value of the largest member of + /// either set. + public func isEqual(to other: Self) -> Bool { + self._storage == other._storage + } + + /// Returns a Boolean value indicating whether a bit set is equal to a range + /// of integers, i.e., whether they contain the same values. + /// + /// - Complexity: O(min(*max*, `other.upperBound`), where *max* is the largest + /// member of `self`. + public func isEqual(to other: Range) -> Bool { + guard let other = other._toUInt() else { return false } + return _read { $0.isEqual(to: other) } + } + + /// Returns a Boolean value indicating whether a bit set is equal to a counted + /// bit set, i.e., whether they contain the same values. + /// + /// - Complexity: O(*max*), where *max* is + public func isEqual(to other: BitSet.Counted) -> Bool { + self.isEqual(to: other._bits) + } + + /// Returns a Boolean value indicating whether this bit set contains the same + /// elements as the given `other` sequence. + /// + /// Duplicate items in `other` do not prevent it from comparing equal to + /// `self`. + /// + /// let bits: BitSet = [0, 1, 5, 6] + /// let other = [5, 5, 0, 1, 1, 6, 5, 0, 1, 6, 6, 5] + /// + /// bits.isEqual(to: other) // true + /// + /// - Complexity: O(*n*), where *n* is the number of items in `other`. + public func isEqual(to other: S) -> Bool where S.Element == Int { + if S.self == Self.self { + return isEqual(to: other as! Self) + } + if S.self == BitSet.Counted.self { + return isEqual(to: other as! BitSet.Counted) + } + if S.self == Range.self { + return isEqual(to: other as! Range) + } + + if self.isEmpty { + return other.allSatisfy { _ in false } + } + + if other is _UniqueCollection { + // We don't need to create a temporary set. + guard other.underestimatedCount <= self.count else { return false } + var seen = 0 + for item in other { + guard let item = UInt(exactly: item) else { return false } + guard self._contains(item) else { return false} + seen &+= 1 + } + precondition( + seen <= self.count, + // Otherwise other.underestimatedCount != other.count + "Invalid Collection '\(S.self)' (bad underestimatedCount)") + return seen == self.count + } + + var seen: BitSet? = BitSet(reservingCapacity: self.max()!) + var it = other.makeIterator() + while let item = it.next() { + guard let item = UInt(exactly: item) else { return false } + guard self._contains(item) else { return false} + seen!._insert(item) // Ignore dupes + if seen!.count == self.count { + // We've seen them all. Stop further accounting. + seen = nil + break + } + } + guard seen == nil else { return false } + while let item = it.next() { + guard let item = UInt(exactly: item) else { return false } + guard self._contains(item) else { return false} + } + return true + } +} diff --git a/Sources/BitCollections/BitSet/BitSet.Counted.swift b/Sources/BitCollections/BitSet/BitSet.Counted.swift index 0b23bcda..7129d20c 100644 --- a/Sources/BitCollections/BitSet/BitSet.Counted.swift +++ b/Sources/BitCollections/BitSet/BitSet.Counted.swift @@ -99,7 +99,7 @@ extension BitSet { self = bits._bits } - var counted: BitSet.Counted { + public var counted: BitSet.Counted { get { BitSet.Counted(_bits: self, count: self.count) } diff --git a/Sources/BitCollections/BitSet/BitSet._UnsafeHandle.swift b/Sources/BitCollections/BitSet/BitSet._UnsafeHandle.swift index 68414b7f..a73a72a4 100644 --- a/Sources/BitCollections/BitSet/BitSet._UnsafeHandle.swift +++ b/Sources/BitCollections/BitSet/BitSet._UnsafeHandle.swift @@ -623,4 +623,33 @@ extension BitSet._UnsafeHandle { let uw = _Word(upTo: upper.bit) return _words[upper.word].intersection(uw) == uw } + + internal func isEqual(to range: Range) -> Bool { + if range.isEmpty { return self.isEmpty } + let r = range.clamped(to: 0 ..< UInt(capacity)) + guard r == range else { return false } + + let lower = Index(range.lowerBound) + let upper = Index(range.upperBound) + + guard upper.word == wordCount &- 1 else { return false } + + for w in 0 ..< lower.word { + guard _words[w].isEmpty else { return false } + } + + if lower.word == upper.word { + let w = _Word(from: lower.bit, to: upper.bit) + return _words[lower.word] == w + } + let lw = _Word(upTo: lower.bit).complement() + guard _words[lower.word] == lw else { return false } + + for w in lower.word + 1 ..< upper.word { + guard _words[w].isFull else { return false } + } + + let uw = _Word(upTo: upper.bit) + return _words[upper.word] == uw + } } diff --git a/Tests/BitCollectionsTests/BitSetTests.swift b/Tests/BitCollectionsTests/BitSetTests.swift index c80b8f39..fef99b55 100644 --- a/Tests/BitCollectionsTests/BitSetTests.swift +++ b/Tests/BitCollectionsTests/BitSetTests.swift @@ -12,6 +12,7 @@ import XCTest import _CollectionsTestSupport import BitCollections +import OrderedCollections extension BitSet: SetAPIExtras { public mutating func update(_ member: Int, at index: Index) -> Int { @@ -982,6 +983,97 @@ final class BitSetTest: CollectionTestCase { } } + func test_isEqual_to_integer_range() { + let a = BitSet(200 ..< 400) + expectTrue(a.isEqual(to: 200 ..< 400)) + expectFalse(a.isEqual(to: 201 ..< 401)) + expectFalse(a.isEqual(to: -1 ..< 200)) + expectFalse(a.isEqual(to: 0 ..< 0)) + expectFalse(a.isEqual(to: 0 ..< 1000)) + expectFalse(a.isEqual(to: 0 ..< 250)) + expectFalse(a.isEqual(to: 270 ..< 400)) + + var b = a + b.remove(300) + expectFalse(b.isEqual(to: 200 ..< 400)) + + let c = BitSet(130 ..< 160) + expectTrue(c.isEqual(to: 130 ..< 160)) + } + + func test_isEqual_to_counted_BitSet() { + let a = BitSet(200 ..< 400) + expectTrue(a.isEqual(to: a.counted)) + } + + func test_isEqual_to_Sequence() { + func check( + _ bits: BitSet, + _ items: S + ) -> Bool where S.Element == Int { + bits.isEqual(to: items) + } + + let bits: BitSet = [3, 6, 8, 11] + expectTrue(check(bits, bits)) + expectTrue(check(bits, bits.counted)) + expectFalse(check(bits, 0 ..< 10)) + + expectFalse(check(bits, [3, 6, 8] as OrderedSet)) + expectTrue(check(bits, [3, 6, 8, 11] as OrderedSet)) + expectFalse(check(bits, [3, 6, 8, 11, 2] as OrderedSet)) + expectFalse(check(bits, [3, 6, 8, 20] as OrderedSet)) + expectFalse(check(bits, [3, 6, 8, -1] as OrderedSet)) + + expectTrue(check([], [] as BitSet)) + expectTrue(check([], [] as BitSet.Counted)) + expectTrue(check([], [] as Set)) + expectTrue(check([], MinimalSequence(elements: []))) + + expectFalse(check([], [1] as BitSet)) + expectFalse(check([], [1] as BitSet.Counted)) + expectFalse(check([], [1] as Set)) + expectFalse( + check([], + MinimalSequence(elements: [1], underestimatedCount: .value(0)))) + + let x1 = MinimalSequence( + elements: [3, 6, 8, 11], + underestimatedCount: .value(0)) + expectTrue(check(bits, x1)) + + let x2 = MinimalSequence( + elements: [3, 6, -1], + underestimatedCount: .value(0)) + expectFalse(check(bits, x2)) + + let x3 = MinimalSequence( + elements: [3, 6, 0], + underestimatedCount: .value(0)) + expectFalse(check(bits, x3)) + + let x4 = MinimalSequence( + elements: [3, 6, 8], + underestimatedCount: .value(0)) + expectFalse(check(bits, x4)) + + let x5 = MinimalSequence( + elements: [3, 6, 8, 11, 3, 6, 8, 11], + underestimatedCount: .value(0)) + expectTrue(check(bits, x5)) // Dupes are okay! + + let x6 = MinimalSequence( + elements: [3, 6, 8, 11, -1], + underestimatedCount: .value(0)) + expectFalse(check(bits, x6)) + + let x7 = MinimalSequence( + elements: [3, 6, 8, 11, 100], + underestimatedCount: .value(0)) + expectFalse(check(bits, x7)) + } + + func test_isSubset() { withEvery("step", in: [1, 5, 16, 23, 24, UInt.bitWidth]) { step in From 001df8e3253e10b41cdb926286c7ca742db768c4 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 19 Oct 2022 01:10:09 -0700 Subject: [PATCH 20/31] [BitSet] Review, test, fix, and document set relation predicates - Update documentation - Improve performance where possible - Add missing test coverage where needed --- .../BitSet/BitSet+SetAlgebra isDisjoint.swift | 53 ++++++++----- .../BitSet+SetAlgebra isStrictSubset.swift | 65 +++++++++------- .../BitSet+SetAlgebra isStrictSuperset.swift | 75 +++++++++++-------- .../BitSet/BitSet+SetAlgebra isSubset.swift | 72 +++++++++++------- .../BitSet/BitSet+SetAlgebra isSuperset.swift | 74 ++++++++++-------- Tests/BitCollectionsTests/BitSetTests.swift | 50 +++++++++++-- 6 files changed, 251 insertions(+), 138 deletions(-) diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isDisjoint.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isDisjoint.swift index 0fd93d97..b92486dc 100644 --- a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isDisjoint.swift +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isDisjoint.swift @@ -36,6 +36,39 @@ extension BitSet { } } + /// Returns a Boolean value that indicates whether a bit set has no members + /// in common with the given counted bit set. + /// + /// let a: BitSet = [1, 2, 3, 4] + /// let b: BitSet.Counted = [5, 6] + /// a.isDisjoint(with: b) // true + /// + /// - Parameter other: A counted bit set. + /// + /// - Returns: `true` if `self` has no elements in common with `other`; + /// otherwise, `false`. + /// + /// - Complexity: O(*max*), where *max* is the largest item in either input. + public func isDisjoint(with other: BitSet.Counted) -> Bool { + self.isDisjoint(with: other._bits) + } + + /// Returns a Boolean value that indicates whether the set has no members in + /// common with the given range of integers. + /// + /// let a: BitSet = [1, 2, 3, 4] + /// a.isDisjoint(with: -10 ..< 0) // true + /// + /// - Parameter other: A range of arbitrary integers. + /// + /// - Returns: `true` if `self` has no elements in common with `other`; + /// otherwise, `false`. + /// + /// - Complexity: O(*max*), where *max* is the largest item in `self`. + public func isDisjoint(with other: Range) -> Bool { + _read { $0.isDisjoint(with: other._clampedToUInt()) } + } + /// Returns a Boolean value that indicates whether the set has no members in /// common with the given sequence of integers. /// @@ -68,24 +101,4 @@ extension BitSet { } return true } - - public func isDisjoint(with other: BitSet.Counted) -> Bool { - self.isDisjoint(with: other._bits) - } - - /// Returns a Boolean value that indicates whether the set has no members in - /// common with the given range of integers. - /// - /// let a: BitSet = [1, 2, 3, 4] - /// a.isDisjoint(with: -10 ..< 0) // true - /// - /// - Parameter other: A range of arbitrary integers. - /// - /// - Returns: `true` if `self` has no elements in common with `other`; - /// otherwise, `false`. - /// - /// - Complexity: O(*max*), where *max* is the largest item in `self`. - public func isDisjoint(with other: Range) -> Bool { - _read { $0.isDisjoint(with: other._clampedToUInt()) } - } } diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSubset.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSubset.swift index 9838f442..576ada89 100644 --- a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSubset.swift +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSubset.swift @@ -50,6 +50,45 @@ extension BitSet { } } + /// Returns a Boolean value that indicates whether this bit set is a strict + /// subset of the given set. + /// + /// Set *A* is a strict subset of another set *B* if every member of *A* is + /// also a member of *B* and *B* contains at least one element that is not a + /// member of *A*. + /// + /// - Parameter other: A counted bit set. + /// + /// - Returns: `true` if the set is a strict subset of `other`; + /// otherwise, `false`. + /// + /// - Complexity: O(*max*), where *max* is the largest item in `self`. + public func isStrictSubset(of other: BitSet.Counted) -> Bool { + isStrictSubset(of: other._bits) + } + + /// Returns a Boolean value that indicates whether this set is a strict + /// subset of the given set. + /// + /// Set *A* is a strict subset of another set *B* if every member of *A* is + /// also a member of *B* and *B* contains at least one element that is not a + /// member of *A*. + /// + /// let b: BitSet = [0, 1, 2] + /// let c: BitSet = [2, 3, 4] + /// b.isStrictSubset(of: -10 ..< 4) // true + /// c.isStrictSubset(of: -10 ..< 4) // false + /// + /// - Parameter other: An arbitrary range of integers. + /// + /// - Returns: `true` if the set is a strict subset of `other`; + /// otherwise, `false`. + /// + /// - Complexity: O(*max*), where *max* is the largest item in `self`. + public func isStrictSubset(of other: Range) -> Bool { + isSubset(of: other) && !isSuperset(of: other) + } + /// Returns a Boolean value that indicates whether this bit set is a strict /// subset of the values in a given sequence of integers. /// @@ -115,30 +154,4 @@ extension BitSet { return false } } - - public func isStrictSubset(of other: BitSet.Counted) -> Bool { - isStrictSubset(of: other._bits) - } - - /// Returns a Boolean value that indicates whether this set is a strict - /// subset of the given set. - /// - /// Set *A* is a strict subset of another set *B* if every member of *A* is - /// also a member of *B* and *B* contains at least one element that is not a - /// member of *A*. - /// - /// let b: BitSet = [0, 1, 2] - /// let c: BitSet = [2, 3, 4] - /// b.isStrictSubset(of: -10 ..< 4) // true - /// c.isStrictSubset(of: -10 ..< 4) // false - /// - /// - Parameter other: An arbitrary range of integers. - /// - /// - Returns: `true` if the set is a strict subset of `other`; - /// otherwise, `false`. - /// - /// - Complexity: O(*max*), where *max* is the largest item in `self`. - public func isStrictSubset(of other: Range) -> Bool { - isSubset(of: other) && !isSuperset(of: other) - } } diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSuperset.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSuperset.swift index aa9c95a9..f6ab0e6a 100644 --- a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSuperset.swift +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSuperset.swift @@ -33,6 +33,48 @@ extension BitSet { other.isStrictSubset(of: self) } + /// Returns a Boolean value that indicates whether this set is a strict + /// superset of another set. + /// + /// Set *A* is a strict superset of another set *B* if every member of *B* is + /// also a member of *A* and *A* contains at least one element that is *not* + /// a member of *B*. + /// + /// - Parameter other: A counted bit set. + /// + /// - Returns: `true` if the set is a superset of `other`; otherwise, `false`. + /// + /// - Complexity: O(*max*), where *max* is the largest item in `other`. + public func isStrictSuperset(of other: BitSet.Counted) -> Bool { + other._bits.isStrictSubset(of: self) + } + + /// Returns a Boolean value that indicates whether this set is a superset of + /// a given range of integers. + /// + /// Set *A* is a superset of another set *B* if every member of *B* is also a + /// member of *A*. + /// + /// let a: BitSet = [0, 1, 2, 3, 4, 10] + /// a.isSuperset(of: 0 ..< 4) // true + /// a.isSuperset(of: -10 ..< 4) // false + /// + /// - Parameter other: An arbitrary range of integers. + /// + /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. + /// + /// - Complexity: O(`range.count`) + public func isStrictSuperset(of other: Range) -> Bool { + if other.isEmpty { return !isEmpty } + if isEmpty { return false } + if self[members: .. Bool { - other._bits.isStrictSubset(of: self) - } - - /// Returns a Boolean value that indicates whether this set is a superset of - /// a given range of integers. - /// - /// Set *A* is a superset of another set *B* if every member of *B* is also a - /// member of *A*. - /// - /// let a: BitSet = [0, 1, 2, 3, 4, 10] - /// a.isSuperset(of: 0 ..< 4) // true - /// a.isSuperset(of: -10 ..< 4) // false - /// - /// - Parameter other: An arbitrary range of integers. - /// - /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. - /// - /// - Complexity: O(`range.count`) - public func isStrictSuperset(of other: Range) -> Bool { - if other.isEmpty { return !isEmpty } - if isEmpty { return false } - if self[members: .. Bool { + self.isSubset(of: other._bits) + } + + /// Returns a Boolean value that indicates whether this set is a subset of + /// the given range of integers. + /// + /// Set *A* is a subset of another set *B* if every member of *A* is also a + /// member of *B*. + /// + /// let b: BitSet = [0, 1, 2] + /// let c: BitSet = [2, 3, 4] + /// b.isSubset(of: -10 ..< 4) // true + /// c.isSubset(of: -10 ..< 4) // false + /// + /// - Parameter other: An arbitrary range of integers. + /// + /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. + /// + /// - Complexity: O(*max*), where *max* is the largest item in `self`. + public func isSubset(of other: Range) -> Bool { + _read { $0.isSubset(of: other._clampedToUInt()) } + } + /// Returns a Boolean value that indicates whether this set is a subset of /// the values in a given sequence of integers. /// @@ -77,7 +112,18 @@ extension BitSet { if S.self == Range.self { return self.isSubset(of: other as! Range) } - if _storage.isEmpty { return true } + + var it = self.makeIterator() + guard let first = it.next() else { return true } + if let match = other._customContainsEquatableElement(first) { + // Fast path: the sequence has fast containment checks. + guard match else { return false } + while let item = it.next() { + guard other.contains(item) else { return false } + } + return true + } + var t = self for i in other { guard let i = UInt(exactly: i) else { continue } @@ -86,28 +132,4 @@ extension BitSet { assert(!t.isEmpty) return false } - - public func isSubset(of other: BitSet.Counted) -> Bool { - self.isSubset(of: other._bits) - } - - /// Returns a Boolean value that indicates whether this set is a subset of - /// the given range of integers. - /// - /// Set *A* is a subset of another set *B* if every member of *A* is also a - /// member of *B*. - /// - /// let b: BitSet = [0, 1, 2] - /// let c: BitSet = [2, 3, 4] - /// b.isSubset(of: -10 ..< 4) // true - /// c.isSubset(of: -10 ..< 4) // false - /// - /// - Parameter other: An arbitrary range of integers. - /// - /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. - /// - /// - Complexity: O(*max*), where *max* is the largest item in `self`. - public func isSubset(of other: Range) -> Bool { - _read { $0.isSubset(of: other._clampedToUInt()) } - } } diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isSuperset.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isSuperset.swift index 4b286a1c..cc85e2b2 100644 --- a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isSuperset.swift +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isSuperset.swift @@ -33,43 +33,16 @@ extension BitSet { } /// Returns a Boolean value that indicates whether this set is a superset of - /// the values in a given sequence of integers. + /// the given set. /// /// Set *A* is a superset of another set *B* if every member of *B* is also a /// member of *A*. /// - /// let a = [1, 2, 3] - /// let b: BitSet = [0, 1, 2, 3, 4] - /// let c: BitSet = [0, 1, 2] - /// b.isSuperset(of: a) // true - /// c.isSuperset(of: a) // false + /// - Parameter other: A counted bit set. /// - /// - Parameter other: A sequence of arbitrary integers. + /// - Returns: `true` if the set is a superset of `other`; otherwise, `false`. /// - /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. - /// - /// - Complexity: The same as the complexity of iterating over all elements - /// in `other`. - @inlinable - public func isSuperset(of other: S) -> Bool - where S.Element == Int - { - if S.self == BitSet.self { - return self.isSuperset(of: other as! BitSet) - } - if S.self == BitSet.Counted.self { - return self.isSuperset(of: other as! BitSet.Counted) - } - if S.self == Range.self { - return self.isSuperset(of: other as! Range) - } - for i in other { - guard let i = UInt(exactly: i) else { return false } - if !_contains(i) { return false } - } - return true - } - + /// - Complexity: O(*max*), where *max* is the largest item in `other`. public func isSuperset(of other: BitSet.Counted) -> Bool { isSuperset(of: other._bits) } @@ -94,4 +67,43 @@ extension BitSet { guard let r = other._toUInt() else { return false } return _read { $0.isSuperset(of: r) } } + + /// Returns a Boolean value that indicates whether this set is a superset of + /// the values in a given sequence of integers. + /// + /// Set *A* is a superset of another set *B* if every member of *B* is also a + /// member of *A*. + /// + /// let a = [1, 2, 3] + /// let b: BitSet = [0, 1, 2, 3, 4] + /// let c: BitSet = [0, 1, 2] + /// b.isSuperset(of: a) // true + /// c.isSuperset(of: a) // false + /// + /// - Parameter other: A sequence of arbitrary integers, some of whose members + /// may appear more than once. (Duplicate items are ignored.) + /// + /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. + /// + /// - Complexity: The same as the complexity of iterating over all elements + /// in `other`. + @inlinable + public func isSuperset(of other: S) -> Bool + where S.Element == Int + { + if S.self == BitSet.self { + return self.isSuperset(of: other as! BitSet) + } + if S.self == BitSet.Counted.self { + return self.isSuperset(of: other as! BitSet.Counted) + } + if S.self == Range.self { + return self.isSuperset(of: other as! Range) + } + for i in other { + guard let i = UInt(exactly: i) else { return false } + if !_contains(i) { return false } + } + return true + } } diff --git a/Tests/BitCollectionsTests/BitSetTests.swift b/Tests/BitCollectionsTests/BitSetTests.swift index fef99b55..dc6599af 100644 --- a/Tests/BitCollectionsTests/BitSetTests.swift +++ b/Tests/BitCollectionsTests/BitSetTests.swift @@ -1112,9 +1112,18 @@ final class BitSetTest: CollectionTestCase { if test.range.lowerBound >= 0 { expectEqual(set.isSubset(of: BitSet(test.range)), expected) expectEqual(forceSequence(BitSet(test.range)), expected) + + expectEqual( + set.isSubset(of: BitSet.Counted(test.range)), expected) + expectEqual( + forceSequence(BitSet.Counted(test.range)), expected) } - expectEqual(set.isSubset(of: Array(test.range)), expected) + let a = Array(test.range) + + expectEqual(set.isSubset(of: a), expected) + expectEqual(set.isSubset(of: a + a), expected) + expectEqual(set.isSubset(of: Set(test.range)), expected) expectEqual(set.isSubset(of: test.range), expected) expectEqual(forceSequence(test.range), expected) @@ -1161,9 +1170,17 @@ final class BitSetTest: CollectionTestCase { if test.range.lowerBound >= 0 { expectEqual(set.isStrictSubset(of: BitSet(test.range)), expected) expectEqual(forceSequence(BitSet(test.range)), expected) + + expectEqual( + set.isStrictSubset(of: BitSet.Counted(test.range)), expected) + expectEqual( + forceSequence(BitSet.Counted(test.range)), expected) } - expectEqual(set.isStrictSubset(of: Array(test.range)), expected) + let a = Array(test.range) + + expectEqual(set.isStrictSubset(of: a), expected) + expectEqual(set.isStrictSubset(of: a + a), expected) expectEqual(set.isStrictSubset(of: test.range), expected) expectEqual(forceSequence(test.range), expected) @@ -1210,9 +1227,17 @@ final class BitSetTest: CollectionTestCase { if test.range.lowerBound >= 0 { expectEqual(set.isSuperset(of: BitSet(test.range)), expected) expectEqual(forceSequence(BitSet(test.range)), expected) + + expectEqual( + set.isSuperset(of: BitSet.Counted(test.range)), expected) + expectEqual( + forceSequence(BitSet.Counted(test.range)), expected) } - expectEqual(set.isSuperset(of: Array(test.range)), expected) + let a = Array(test.range) + + expectEqual(set.isSuperset(of: a), expected) + expectEqual(set.isSuperset(of: a + a), expected) expectEqual(set.isSuperset(of: test.range), expected) expectEqual(forceSequence(test.range), expected) @@ -1259,9 +1284,17 @@ final class BitSetTest: CollectionTestCase { if test.range.lowerBound >= 0 { expectEqual(set.isStrictSuperset(of: BitSet(test.range)), expected) expectEqual(forceSequence(BitSet(test.range)), expected) + + expectEqual( + set.isStrictSuperset(of: BitSet.Counted(test.range)), expected) + expectEqual( + forceSequence(BitSet.Counted(test.range)), expected) } - expectEqual(set.isStrictSuperset(of: Array(test.range)), expected) + let a = Array(test.range) + + expectEqual(set.isStrictSuperset(of: a), expected) + expectEqual(set.isStrictSuperset(of: a + a), expected) expectEqual(set.isStrictSuperset(of: test.range), expected) expectEqual(forceSequence(test.range), expected) @@ -1310,9 +1343,16 @@ final class BitSetTest: CollectionTestCase { if test.range.lowerBound >= 0 { expectEqual(set.isDisjoint(with: BitSet(test.range)), expected) expectEqual(forceSequence(BitSet(test.range)), expected) + + expectEqual( + set.isDisjoint(with: BitSet.Counted(test.range)), expected) + expectEqual( + forceSequence(BitSet.Counted(test.range)), expected) } - expectEqual(set.isDisjoint(with: Array(test.range)), expected) + let a = Array(test.range) + expectEqual(set.isDisjoint(with: a), expected) + expectEqual(set.isDisjoint(with: a + a), expected) expectEqual(set.isDisjoint(with: test.range), expected) expectEqual(forceSequence(test.range), expected) From f843bd40bff204dd9ee0621eac669198c44a22de Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 19 Oct 2022 01:36:44 -0700 Subject: [PATCH 21/31] [PersistentSet] Add update(_:at:) --- .../PersistentSet/PersistentSet+Extras.swift | 32 +++++++++++++++++++ .../PersistentSet Tests.swift | 21 +++++++++++- 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+Extras.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+Extras.swift index 989dec21..a5539c89 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+Extras.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+Extras.swift @@ -20,4 +20,36 @@ extension PersistentSet { _invalidateIndices() return _root.remove(.top, at: position._path).key } + + /// Replace the member at the given index with a new value that compares equal + /// to it. + /// + /// This is useful when equal elements can be distinguished by identity + /// comparison or some other means. Updating a member through this method + /// does not require any hashing operations. + /// + /// Calling this method invalidates all existing indices. + /// + /// - Parameter item: The new value that should replace the original element. + /// `item` must compare equal to the original value. + /// + /// - Parameter index: The index of the element to be replaced. + /// + /// - Returns: The original element that was replaced. + /// + /// - Complexity: Amortized O(1). + public mutating func update(_ member: Element, at index: Index) -> Element { + precondition(_isValid(index), "Invalid index") + precondition(index._path.isOnItem, "Can't get element at endIndex") + _invalidateIndices() + return _UnsafeHandle.update(index._path.node) { + let p = $0.itemPtr(at: index._path.currentItemSlot) + var old = member + precondition( + member == p.pointee.key, + "The replacement item must compare equal to the original") + swap(&p.pointee.key, &old) + return old + } + } } diff --git a/Tests/PersistentCollectionsTests/PersistentSet Tests.swift b/Tests/PersistentCollectionsTests/PersistentSet Tests.swift index 380504f6..459c9715 100644 --- a/Tests/PersistentCollectionsTests/PersistentSet Tests.swift +++ b/Tests/PersistentCollectionsTests/PersistentSet Tests.swift @@ -12,7 +12,7 @@ import _CollectionsTestSupport import PersistentCollections -extension PersistentSet: SetAPIChecker {} +extension PersistentSet: SetAPIExtras {} class PersistentSetTests: CollectionTestCase { func test_init_empty() { @@ -476,4 +476,23 @@ class PersistentSetTests: CollectionTestCase { } } } + + func test_update_at() { + withEverySubset("a", of: testItems) { a in + withEvery("offset", in: 0 ..< a.count) { offset in + withEvery("isShared", in: [false, true]) { isShared in + withLifetimeTracking { tracker in + var x = PersistentSet(tracker.instances(for: a)) + let i = x.firstIndex { $0.payload == a[offset] }! + let replacement = tracker.instance(for: a[offset]) + withHiddenCopies(if: isShared, of: &x) { x in + let old = x.update(replacement, at: i) + expectEqual(old, replacement) + expectNotIdentical(old, replacement) + } + } + } + } + } + } } From 8ce8a6bc86a291b5aa8ccb861b298767ba6f0066 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 19 Oct 2022 13:59:43 -0700 Subject: [PATCH 22/31] [PersistentSet] Review, test, fix, and document set relation predicates --- .../PersistentSet+SetAlgebra isDisjoint.swift | 3 +- .../PersistentSet+SetAlgebra isEqual.swift | 41 ++++++++++++++--- ...sistentSet+SetAlgebra isStrictSubset.swift | 44 +++++++++++-------- ...stentSet+SetAlgebra isStrictSuperset.swift | 2 +- .../PersistentSet+SetAlgebra isSubset.swift | 2 +- .../PersistentSet+SetAlgebra isSuperset.swift | 6 +-- .../PersistentSet Tests.swift | 21 ++++++++- 7 files changed, 87 insertions(+), 32 deletions(-) diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isDisjoint.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isDisjoint.swift index e6c40ca7..6f70f20e 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isDisjoint.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isDisjoint.swift @@ -57,7 +57,7 @@ extension PersistentSet { /// let b: PersistentSet = [5, 6] /// a.isDisjoint(with: b) // true /// - /// - Parameter other: A sequence of elements, some of whose elements may + /// - Parameter other: A finite sequence of elements, some of which may /// appear more than once. /// /// - Returns: `true` if `self` has no elements in common with `other`; @@ -69,6 +69,7 @@ extension PersistentSet { public func isDisjoint(with other: S) -> Bool where S.Element == Element { + guard !self.isEmpty else { return true } if S.self == Self.self { return isDisjoint(with: other as! Self) } diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isEqual.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isEqual.swift index f9a6bf1f..4bd0d739 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isEqual.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isEqual.swift @@ -9,6 +9,8 @@ // //===----------------------------------------------------------------------===// +import _CollectionsUtilities + // FIXME: These are non-standard extensions generalizing ==. extension PersistentSet { /// Returns a Boolean value indicating whether persistent sets are equal. Two @@ -80,15 +82,42 @@ extension PersistentSet { return isEqual(to: other as! Self) } - guard other.underestimatedCount <= self.count else { return false } + if self.isEmpty { + return other.allSatisfy { _ in false } + } + + if other is _UniqueCollection { + // We don't need to create a temporary set. + guard other.underestimatedCount <= self.count else { return false } + var seen = 0 + for item in other { + guard self.contains(item) else { return false } + seen &+= 1 + } + precondition( + seen <= self.count, + // Otherwise other.underestimatedCount != other.count + "Invalid Collection '\(S.self)' (bad underestimatedCount)") + return seen == self.count + } + // FIXME: Would making this a BitSet of seen positions be better? - var seen: _Node = ._empty() - for item in other { + var seen: _Node? = ._empty() + var it = other.makeIterator() + while let item = it.next() { let hash = _Hash(item) guard self._root.containsKey(.top, item, hash) else { return false } - guard seen.insert(.top, (item, ()), hash).inserted - else { return false } + _ = seen!.insert(.top, (item, ()), hash) // Ignore dupes + if seen!.count == self.count { + // We've seen them all. Stop further accounting. + seen = nil + break + } } - return seen.count == self.count + guard seen == nil else { return false } + while let item = it.next() { + guard self.contains(item) else { return false } + } + return true } } diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSubset.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSubset.swift index 9b3b211c..c545278e 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSubset.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSubset.swift @@ -95,38 +95,46 @@ extension PersistentSet { return isStrictSubset(of: other as! Self) } - var it = self.makeIterator() - guard let first = it.next() else { - return other.contains(where: { _ in true }) - } - if let match = other._customContainsEquatableElement(first) { - // Fast path: the sequence has fast containment checks. - guard match else { return false } - while let item = it.next() { - guard other.contains(item) else { return false } + do { + var it = self.makeIterator() + guard let first = it.next() else { + return other.contains(where: { _ in true }) + } + if let match = other._customContainsEquatableElement(first) { + // Fast path: the sequence has fast containment checks. + guard match else { return false } + while let item = it.next() { + guard other.contains(item) else { return false } + } + return !other.allSatisfy { self.contains($0) } } - return !other.allSatisfy { self.contains($0) } } // FIXME: Would making this a BitSet of seen positions be better? - var seen: _Node? = ._empty() + var seen: _Node = ._empty() + var doneCollecting = false var isStrict = false - for item in other { + var it = other.makeIterator() + while let item = it.next() { let hash = _Hash(item) - if self._root.containsKey(.top, item, hash), - seen?.insert(.top, (item, ()), hash).inserted == true - { - if seen?.count == self.count { + if self._root.containsKey(.top, item, hash) { + if + !doneCollecting, + seen.insert(.top, (item, ()), hash).inserted, + seen.count == self.count + { if isStrict { return true } // Stop collecting seen items -- we just need to decide // strictness now. - seen = nil + seen = ._empty() + doneCollecting = true } } else { isStrict = true - if seen == nil { return true } + if doneCollecting { return true } } } + return false } } diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSuperset.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSuperset.swift index 3bc9d2ee..5616be58 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSuperset.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSuperset.swift @@ -78,7 +78,7 @@ extension PersistentSet { /// a.isStrictSuperset(of: b.unordered) // true /// /// - Parameter other: A sequence of elements, some of whose elements may - /// appear more than once. + /// appear more than once. (Duplicate items are ignored.) /// /// - Returns: `true` if `self` is a strict subset of `other`; otherwise, /// `false`. diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isSubset.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isSubset.swift index 81aad599..e3af14d9 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isSubset.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isSubset.swift @@ -102,7 +102,7 @@ extension PersistentSet { var seen: _Node = ._empty() for item in other { let hash = _Hash(item) - guard contains(item) else { continue } + guard _root.containsKey(.top, item, hash) else { continue } guard seen.insert(.top, (item, ()), hash).inserted else { continue } if seen.count == self.count { return true diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isSuperset.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isSuperset.swift index 304b81c5..58dee925 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isSuperset.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isSuperset.swift @@ -53,9 +53,9 @@ extension PersistentSet { /// e.g. by skipping over parts of the input trees. @inlinable public func isSuperset( - of other: PersistentDictionary + of other: PersistentDictionary.Keys ) -> Bool { - other._root.isSubset(.top, of: self._root) + other._base._root.isSubset(.top, of: self._root) } /// Returns a Boolean value that indicates whether this set is a superset of @@ -69,7 +69,7 @@ extension PersistentSet { /// a.isSuperset(of: b) // true /// /// - Parameter other: A sequence of elements, some of whose elements may - /// appear more than once. + /// appear more than once. (Duplicate items are ignored.) /// /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. /// diff --git a/Tests/PersistentCollectionsTests/PersistentSet Tests.swift b/Tests/PersistentCollectionsTests/PersistentSet Tests.swift index 459c9715..796893b0 100644 --- a/Tests/PersistentCollectionsTests/PersistentSet Tests.swift +++ b/Tests/PersistentCollectionsTests/PersistentSet Tests.swift @@ -205,6 +205,7 @@ class PersistentSetTests: CollectionTestCase { withEverySubset("b", of: testItems) { b in let y = PersistentSet(b) let v = Set(b) + let z = PersistentDictionary(uniqueKeysWithValues: b.map { ($0, $0) }) let reference = (u == v) @@ -217,9 +218,11 @@ class PersistentSetTests: CollectionTestCase { } expectEqual(x.isEqual(to: y), reference) + expectEqual(x.isEqual(to: z.keys), reference) expectEqual(checkSequence(x, y), reference) expectEqual(x.isEqual(to: v), reference) expectEqual(x.isEqual(to: b), reference) + expectEqual(x.isEqual(to: b + b), reference) } } } @@ -232,6 +235,7 @@ class PersistentSetTests: CollectionTestCase { withEverySubset("b", of: testItems) { b in let y = PersistentSet(b) let v = Set(b) + let z = PersistentDictionary(uniqueKeysWithValues: b.map { ($0, $0) }) let reference = u.isSubset(of: v) @@ -244,9 +248,11 @@ class PersistentSetTests: CollectionTestCase { } expectEqual(x.isSubset(of: y), reference) + expectEqual(x.isSubset(of: z.keys), reference) expectEqual(checkSequence(x, y), reference) expectEqual(x.isSubset(of: v), reference) expectEqual(x.isSubset(of: b), reference) + expectEqual(x.isSubset(of: b + b), reference) } } } @@ -259,6 +265,7 @@ class PersistentSetTests: CollectionTestCase { withEverySubset("b", of: testItems) { b in let y = PersistentSet(b) let v = Set(b) + let z = PersistentDictionary(uniqueKeysWithValues: b.map { ($0, $0) }) let reference = u.isSuperset(of: v) @@ -271,14 +278,16 @@ class PersistentSetTests: CollectionTestCase { } expectEqual(x.isSuperset(of: y), reference) + expectEqual(x.isSuperset(of: z.keys), reference) expectEqual(checkSequence(x, y), reference) expectEqual(x.isSuperset(of: v), reference) expectEqual(x.isSuperset(of: b), reference) + expectEqual(x.isSuperset(of: b + b), reference) } } } - func test_isStrictsubset_exhaustive() { + func test_isStrictSubset_exhaustive() { withEverySubset("a", of: testItems) { a in let x = PersistentSet(a) let u = Set(a) @@ -286,6 +295,7 @@ class PersistentSetTests: CollectionTestCase { withEverySubset("b", of: testItems) { b in let y = PersistentSet(b) let v = Set(b) + let z = PersistentDictionary(uniqueKeysWithValues: b.map { ($0, $0) }) let reference = u.isStrictSubset(of: v) @@ -298,9 +308,11 @@ class PersistentSetTests: CollectionTestCase { } expectEqual(x.isStrictSubset(of: y), reference) + expectEqual(x.isStrictSubset(of: z.keys), reference) expectEqual(checkSequence(x, y), reference) expectEqual(x.isStrictSubset(of: v), reference) expectEqual(x.isStrictSubset(of: b), reference) + expectEqual(x.isStrictSubset(of: b + b), reference) } } } @@ -313,6 +325,7 @@ class PersistentSetTests: CollectionTestCase { withEverySubset("b", of: testItems) { b in let y = PersistentSet(b) let v = Set(b) + let z = PersistentDictionary(uniqueKeysWithValues: b.map { ($0, $0) }) let reference = u.isStrictSuperset(of: v) @@ -325,9 +338,11 @@ class PersistentSetTests: CollectionTestCase { } expectEqual(x.isStrictSuperset(of: y), reference) + expectEqual(x.isStrictSuperset(of: z.keys), reference) expectEqual(checkSequence(x, y), reference) expectEqual(x.isStrictSuperset(of: v), reference) expectEqual(x.isStrictSuperset(of: b), reference) + expectEqual(x.isStrictSuperset(of: b + b), reference) } } } @@ -340,7 +355,7 @@ class PersistentSetTests: CollectionTestCase { withEverySubset("b", of: testItems) { b in let y = PersistentSet(b) let v = Set(b) - + let z = PersistentDictionary(uniqueKeysWithValues: b.map { ($0, $0) }) let reference = u.isDisjoint(with: v) func checkSequence( @@ -352,9 +367,11 @@ class PersistentSetTests: CollectionTestCase { } expectEqual(x.isDisjoint(with: y), reference) + expectEqual(x.isDisjoint(with: z.keys), reference) expectEqual(checkSequence(x, y), reference) expectEqual(x.isDisjoint(with: v), reference) expectEqual(x.isDisjoint(with: b), reference) + expectEqual(x.isDisjoint(with: b + b), reference) } } } From 5dfd51238c683fe67162db69db2e774546f4dcec Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 19 Oct 2022 15:10:07 -0700 Subject: [PATCH 23/31] [OrderedSet] Review, test, fix, and document set relation predicates --- .../OrderedSet/OrderedSet+Equatable.swift | 5 + ...rderedSet+Partial SetAlgebra isEqual.swift | 80 ++++++ ...redSet+Partial SetAlgebra+Predicates.swift | 86 ++++++- .../OrderedSet.UnorderedView Tests.swift | 3 + .../OrderedSet/OrderedSetTests.swift | 237 +++++++++--------- 5 files changed, 293 insertions(+), 118 deletions(-) create mode 100644 Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isEqual.swift diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Equatable.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Equatable.swift index 1190cd6e..2c6dee53 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Equatable.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Equatable.swift @@ -15,6 +15,11 @@ extension OrderedSet: Equatable { /// Two ordered sets are considered equal if they contain the same /// elements in the same order. /// + /// - Note: This operator implements different behavior than the + /// `isEqual(to:)` method -- the latter implements an unordered + /// comparison, to match the behavior of members like `isSubset(of:)`, + /// `isStrictSuperset(of:)` etc. + /// /// - Complexity: O(`min(left.count, right.count)`) @inlinable public static func ==(left: Self, right: Self) -> Bool { diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isEqual.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isEqual.swift new file mode 100644 index 00000000..8f63fe72 --- /dev/null +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isEqual.swift @@ -0,0 +1,80 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2022 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 +// +//===----------------------------------------------------------------------===// + +import _CollectionsUtilities + +extension OrderedSet { + /// Returns a Boolean value indicating whether two set values contain the + /// same elements, but not necessarily in the same order. + /// + /// - Note: This member implements different behavior than the `==(_:_:)` + /// operator -- the latter implements an ordered comparison, matching + /// the stricter concept of equality expected of an ordered collection + /// type. + /// + /// - Complexity: O(`min(left.count, right.count)`), as long as`Element` + /// properly implements hashing. + public func isEqual(to other: Self) -> Bool { + self.unordered == other.unordered + } + + /// Returns a Boolean value indicating whether two set values contain the + /// same elements, but not necessarily in the same order. + /// + /// - Complexity: O(`min(left.count, right.count)`), as long as`Element` + /// properly implements hashing. + public func isEqual(to other: UnorderedView) -> Bool { + self.unordered == other + } + + /// Returns a Boolean value indicating whether an ordered set contains the + /// same values as a given sequence, but not necessarily in the same + /// order. + /// + /// Duplicate items in `other` do not prevent it from comparing equal to + /// `self`. + /// + /// - Complexity: O(*n*), where *n* is the number of items in + /// `other`, as long as`Element` properly implements hashing. + public func isEqual(to other: S) -> Bool + where S.Element == Element { + if S.self == Self.self { + return isEqual(to: other as! Self) + } + + if self.isEmpty { + return other.allSatisfy { _ in false } + } + + if other is _UniqueCollection { + // We don't need to create a temporary set. + guard other.underestimatedCount <= self.count else { return false } + var seen = 0 + for item in other { + guard self.contains(item) else { return false } + seen &+= 1 + } + precondition( + seen <= self.count, + // Otherwise other.underestimatedCount != other.count + "Invalid Collection '\(S.self)' (bad underestimatedCount)") + return seen == self.count + } + + return _UnsafeBitset.withTemporaryBitset(capacity: count) { seen in + for item in other { + guard let index = _find(item).index else { return false } + _ = seen.insert(index) // Ignore dupes + } + return seen.count == count + } + } +} diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra+Predicates.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra+Predicates.swift index e975a0b4..c5f67ba7 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra+Predicates.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra+Predicates.swift @@ -9,6 +9,8 @@ // //===----------------------------------------------------------------------===// +import _CollectionsUtilities + // `OrderedSet` does not directly conform to `SetAlgebra` because its definition // of equality conflicts with `SetAlgebra` requirements. However, it still // implements most `SetAlgebra` requirements (except `insert`, which is replaced @@ -115,6 +117,22 @@ extension OrderedSet { of other: S ) -> Bool where S.Element == Element { guard !isEmpty else { return true } + + if S.self == Self.self { + return isSubset(of: other as! Self) + } + + var it = self.makeIterator() + let first = it.next()! + if let match = other._customContainsEquatableElement(first) { + // Fast path: the sequence has fast containment checks. + guard match else { return false } + while let item = it.next() { + guard other.contains(item) else { return false } + } + return true + } + return _UnsafeBitset.withTemporaryBitset(capacity: count) { seen in // Mark elements in `self` that we've seen in `other`. for item in other { @@ -175,6 +193,22 @@ extension OrderedSet { isSuperset(of: other._base) } + /// Returns a Boolean value that indicates whether this set is a superset of + /// the given set. + /// + /// Set *A* is a superset of another set *B* if every member of *B* is also a + /// member of *A*, ignoring the order they appear in the two sets. + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: Set = [4, 2, 1] + /// a.isSuperset(of: b) // true + /// + /// - Parameter other: Another set. + /// + /// - Returns: `true` if the set is a superset of `other`; otherwise, `false`. + /// + /// - Complexity: Expected to be O(`other.count`) on average, if `Element` + /// implements high-quality hashing. @inlinable public func isSuperset(of other: Set) -> Bool { guard self.count >= other.count else { return false } @@ -191,7 +225,8 @@ extension OrderedSet { /// let b: Array = [4, 2, 1] /// a.isSuperset(of: b) // true /// - /// - Parameter other: A finite sequence of elements. + /// - Parameter other: A finite sequence of elements, some of whose members + /// may appear more than once. (Duplicate items are ignored.) /// /// - Returns: `true` if the set is a superset of `other`; otherwise, `false`. /// @@ -208,6 +243,9 @@ extension OrderedSet { internal func _isSuperset( of other: S ) -> Bool where S.Element == Element { + if S.self == Self.self { + return self.isSuperset(of: other as! Self) + } for item in other { guard self.contains(item) else { return false } } @@ -311,7 +349,27 @@ extension OrderedSet { public func isStrictSubset( of other: S ) -> Bool where S.Element == Element { - _UnsafeBitset.withTemporaryBitset(capacity: count) { seen in + if S.self == Self.self { + return self.isStrictSubset(of: other as! Self) + } + if S.self == Set.self { + return self.isStrictSubset(of: other as! Set) + } + + var it = self.makeIterator() + guard let first = it.next() else { + return other.contains(where: { _ in true }) + } + if let match = other._customContainsEquatableElement(first) { + // Fast path: the sequence has fast containment checks. + guard match else { return false } + while let item = it.next() { + guard other.contains(item) else { return false } + } + return !other.allSatisfy { self.contains($0) } + } + + return _UnsafeBitset.withTemporaryBitset(capacity: count) { seen in // Mark elements in `self` that we've seen in `other`. var isKnownStrict = false for item in other { @@ -414,7 +472,8 @@ extension OrderedSet { /// let b: Array = [4, 2, 1] /// a.isStrictSuperset(of: b) // true /// - /// - Parameter other: A finite sequence of elements. + /// - Parameter other: A finite sequence of elements, some of whose members + /// may appear more than once. (Duplicate items are ignored.) /// /// - Returns: `true` if `self` is a strict superset of `other`; otherwise, /// `false`. @@ -426,7 +485,26 @@ extension OrderedSet { public func isStrictSuperset( of other: S ) -> Bool where S.Element == Element { - _UnsafeBitset.withTemporaryBitset(capacity: count) { seen in + if S.self == Self.self { + return self.isStrictSuperset(of: other as! Self) + } + if S.self == Set.self { + return self.isStrictSuperset(of: other as! Set) + } + + var it = self.makeIterator() + guard let first = it.next() else { return false } + if let match = other._customContainsEquatableElement(first) { + // Fast path: the sequence has fast containment checks. + guard other.allSatisfy({ self.contains($0) }) else { return false } + guard match else { return true } + while let item = it.next() { + guard other.contains(item) else { return true } + } + return false + } + + return _UnsafeBitset.withTemporaryBitset(capacity: count) { seen in // Mark elements in `self` that we've seen in `other`. for item in other { guard let index = _find(item).index else { diff --git a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSet.UnorderedView Tests.swift b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSet.UnorderedView Tests.swift index b9021ca6..4d166253 100644 --- a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSet.UnorderedView Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSet.UnorderedView Tests.swift @@ -13,6 +13,9 @@ import XCTest @_spi(Testing) import OrderedCollections import _CollectionsTestSupport +// Note: This cannot really work unless `UnorderedView` becomes a Collection. +// extension OrderedSet.UnorderedView: SetAPIChecker {} + class OrderedSetUnorderedViewTests: CollectionTestCase { func test_unordered_insert() { withEvery("count", in: 0 ..< 20) { count in diff --git a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift index a0f09547..fbec54fa 100644 --- a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift +++ b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift @@ -13,7 +13,7 @@ import XCTest @_spi(Testing) import OrderedCollections import _CollectionsTestSupport -extension OrderedSet: SetAPIChecker {} +extension OrderedSet: SetAPIExtras {} class OrderedSetTests: CollectionTestCase { func test_init_uncheckedUniqueElements_concrete() { @@ -1198,167 +1198,176 @@ class OrderedSetTests: CollectionTestCase { } } - func test_isSubset_Self() { + func test_isEqual() { + withEvery("unit", in: [1, 3, 7, 10, 20, 50]) { unit in + SampleRanges(unit: unit).withEveryPair { r1, r2 in + let expected = Set(r1) == Set(r2) + let a = OrderedSet(r1) + let b = OrderedSet(r2) + let c = Set(r2) + let d = Array(r2) + + func checkSequence( + _ set: OrderedSet, + _ other: S + ) -> Bool where S.Element == Int { + set.isEqual(to: other) + } + + expectEqual(a.isEqual(to: b), expected) + expectEqual(a.isEqual(to: b.unordered), expected) + expectEqual(a.isEqual(to: c), expected) + + expectEqual(checkSequence(a, b), expected) + expectEqual(checkSequence(a, c), expected) + expectEqual(a.isEqual(to: d), expected) + expectEqual(a.isEqual(to: d + d), expected) + expectEqual(a.isEqual(to: r2), expected) + } + } + } + + func test_isSubset() { withEvery("unit", in: [1, 3, 7, 10, 20, 50]) { unit in SampleRanges(unit: unit).withEveryPair { r1, r2 in let expected = Set(r1).isSubset(of: r2) let a = OrderedSet(r1) let b = OrderedSet(r2) + let c = Set(r2) + let d = Array(r2) + + func checkSequence( + _ set: OrderedSet, + _ other: S + ) -> Bool where S.Element == Int { + set.isSubset(of: other) + } + expectEqual(a.isSubset(of: b), expected) + expectEqual(a.isSubset(of: b.unordered), expected) + expectEqual(a.isSubset(of: c), expected) + + expectEqual(checkSequence(a, b), expected) + expectEqual(checkSequence(a, c), expected) + expectEqual(a.isSubset(of: d), expected) + expectEqual(a.isSubset(of: d + d), expected) + expectEqual(a.isSubset(of: r2), expected) } } } - func test_isSubset_Set() { - withEvery("unit", in: [1, 3, 7, 10, 20, 50]) { unit in - SampleRanges(unit: unit).withEveryPair { r1, r2 in - let expected = Set(r1).isSubset(of: r2) - let a = OrderedSet(r1) - let b = Set(r2) - expectEqual(a.isSubset(of: b), expected) - } - } - } - - func test_isSubset_generic() { - withEvery("unit", in: [1, 3, 7, 10, 20, 50]) { unit in - SampleRanges(unit: unit).withEveryPair { r1, r2 in - let expected = Set(r1).isSubset(of: r2) - let a = OrderedSet(r1) - let b = r2 - expectEqual(a.isSubset(of: b), expected) - } - } - } - - func test_isSuperset_Self() { + func test_isSuperset() { withEvery("unit", in: [1, 3, 7, 10, 20, 50]) { unit in SampleRanges(unit: unit).withEveryPair { r1, r2 in let expected = Set(r1).isSuperset(of: r2) let a = OrderedSet(r1) let b = OrderedSet(r2) + let c = Set(r2) + let d = Array(r2) + + func checkSequence( + _ set: OrderedSet, + _ other: S + ) -> Bool where S.Element == Int { + set.isSuperset(of: other) + } + expectEqual(a.isSuperset(of: b), expected) + expectEqual(a.isSuperset(of: b.unordered), expected) + expectEqual(a.isSuperset(of: c), expected) + + expectEqual(checkSequence(a, b), expected) + expectEqual(checkSequence(a, c), expected) + expectEqual(a.isSuperset(of: d), expected) + expectEqual(a.isSuperset(of: d + d), expected) + expectEqual(a.isSuperset(of: r2), expected) } } } - func test_isSuperset_Set() { - withEvery("unit", in: [1, 3, 7, 10, 20, 50]) { unit in - SampleRanges(unit: unit).withEveryPair { r1, r2 in - let expected = Set(r1).isSuperset(of: r2) - let a = OrderedSet(r1) - let b = Set(r2) - expectEqual(a.isSuperset(of: b), expected) - } - } - } - - func test_isSuperset_generic() { - withEvery("unit", in: [1, 3, 7, 10, 20, 50]) { unit in - SampleRanges(unit: unit).withEveryPair { r1, r2 in - let expected = Set(r1).isSuperset(of: r2) - let a = OrderedSet(r1) - let b = r2 - expectEqual(a.isSuperset(of: b), expected) - } - } - } - - func test_isStrictSubset_Self() { + func test_isStrictSubset() { withEvery("unit", in: [1, 3, 7, 10, 20, 50]) { unit in SampleRanges(unit: unit).withEveryPair { r1, r2 in let expected = Set(r1).isStrictSubset(of: r2) let a = OrderedSet(r1) let b = OrderedSet(r2) + let c = Set(r2) + let d = Array(r2) + + func checkSequence( + _ set: OrderedSet, + _ other: S + ) -> Bool where S.Element == Int { + set.isStrictSubset(of: other) + } + expectEqual(a.isStrictSubset(of: b), expected) + expectEqual(a.isStrictSubset(of: b.unordered), expected) + expectEqual(a.isStrictSubset(of: c), expected) + + expectEqual(checkSequence(a, b), expected) + expectEqual(checkSequence(a, c), expected) + expectEqual(a.isStrictSubset(of: d), expected) + expectEqual(a.isStrictSubset(of: d + d), expected) + expectEqual(a.isStrictSubset(of: r2), expected) } } } - func test_isStrictSubset_Set() { - withEvery("unit", in: [1, 3, 7, 10, 20, 50]) { unit in - SampleRanges(unit: unit).withEveryPair { r1, r2 in - let expected = Set(r1).isStrictSubset(of: r2) - let a = OrderedSet(r1) - let b = Set(r2) - expectEqual(a.isStrictSubset(of: b), expected) - } - } - } - - func test_isStrictSubset_generic() { - withEvery("unit", in: [1, 3, 7, 10, 20, 50]) { unit in - SampleRanges(unit: unit).withEveryPair { r1, r2 in - let expected = Set(r1).isStrictSubset(of: r2) - let a = OrderedSet(r1) - let b = r2 - expectEqual(a.isStrictSubset(of: b), expected) - } - } - } - - func test_isStrictSuperset_Self() { + func test_isStrictSuperset() { withEvery("unit", in: [1, 3, 7, 10, 20, 50]) { unit in SampleRanges(unit: unit).withEveryPair { r1, r2 in let expected = Set(r1).isStrictSuperset(of: r2) let a = OrderedSet(r1) let b = OrderedSet(r2) + let c = Set(r2) + let d = Array(r2) + + func checkSequence( + _ set: OrderedSet, + _ other: S + ) -> Bool where S.Element == Int { + set.isStrictSuperset(of: other) + } + expectEqual(a.isStrictSuperset(of: b), expected) + expectEqual(a.isStrictSuperset(of: b.unordered), expected) + expectEqual(a.isStrictSuperset(of: c), expected) + + expectEqual(checkSequence(a, b), expected) + expectEqual(checkSequence(a, c), expected) + expectEqual(a.isStrictSuperset(of: d), expected) + expectEqual(a.isStrictSuperset(of: d + d), expected) + expectEqual(a.isStrictSuperset(of: r2), expected) } } } - func test_isStrictSuperset_Set() { - withEvery("unit", in: [1, 3, 7, 10, 20, 50]) { unit in - SampleRanges(unit: unit).withEveryPair { r1, r2 in - let expected = Set(r1).isStrictSuperset(of: r2) - let a = OrderedSet(r1) - let b = Set(r2) - expectEqual(a.isStrictSuperset(of: b), expected) - } - } - } - - func test_isStrictSuperset_generic() { - withEvery("unit", in: [1, 3, 7, 10, 20, 50]) { unit in - SampleRanges(unit: unit).withEveryPair { r1, r2 in - let expected = Set(r1).isStrictSuperset(of: r2) - let a = OrderedSet(r1) - let b = r2 - expectEqual(a.isStrictSuperset(of: b), expected) - } - } - } - - func test_isDisjoint_Self() { + func test_isDisjoint() { withEvery("unit", in: [1, 3, 7, 10, 20, 50]) { unit in SampleRanges(unit: unit).withEveryPair { r1, r2 in let expected = Set(r1).isDisjoint(with: r2) let a = OrderedSet(r1) let b = OrderedSet(r2) - expectEqual(a.isDisjoint(with: b), expected) - } - } - } + let c = Set(r2) + let d = Array(r2) - func test_isDisjoint_Set() { - withEvery("unit", in: [1, 3, 7, 10, 20, 50]) { unit in - SampleRanges(unit: unit).withEveryPair { r1, r2 in - let expected = Set(r1).isDisjoint(with: r2) - let a = OrderedSet(r1) - let b = Set(r2) - expectEqual(a.isDisjoint(with: b), expected) - } - } - } + func checkSequence( + _ set: OrderedSet, + _ other: S + ) -> Bool where S.Element == Int { + set.isDisjoint(with: other) + } - func test_isDisjoint_generic() { - withEvery("unit", in: [1, 3, 7, 10, 20, 50]) { unit in - SampleRanges(unit: unit).withEveryPair { r1, r2 in - let expected = Set(r1).isDisjoint(with: r2) - let a = OrderedSet(r1) - let b = r2 expectEqual(a.isDisjoint(with: b), expected) + expectEqual(a.isDisjoint(with: b.unordered), expected) + expectEqual(a.isDisjoint(with: c), expected) + + expectEqual(checkSequence(a, b), expected) + expectEqual(checkSequence(a, c), expected) + expectEqual(a.isDisjoint(with: d), expected) + expectEqual(a.isDisjoint(with: d + d), expected) + expectEqual(a.isDisjoint(with: r2), expected) } } } From 734730d72460e7bd536e8021d4aa711cb3aa75b2 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 19 Oct 2022 15:19:46 -0700 Subject: [PATCH 24/31] [OrderedSet] Split SetAlgebra predicates into individual files This is to match the layout of all the other SetAlgebra implementations in this package. --- ...redSet+Partial SetAlgebra isDisjoint.swift | 128 ++++ ...et+Partial SetAlgebra isStrictSubset.swift | 154 +++++ ...+Partial SetAlgebra isStrictSuperset.swift | 152 +++++ ...deredSet+Partial SetAlgebra isSubset.swift | 147 ++++ ...redSet+Partial SetAlgebra isSuperset.swift | 124 ++++ ...redSet+Partial SetAlgebra+Predicates.swift | 629 ------------------ 6 files changed, 705 insertions(+), 629 deletions(-) create mode 100644 Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isDisjoint.swift create mode 100644 Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isStrictSubset.swift create mode 100644 Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isStrictSuperset.swift create mode 100644 Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isSubset.swift create mode 100644 Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isSuperset.swift delete mode 100644 Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra+Predicates.swift diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isDisjoint.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isDisjoint.swift new file mode 100644 index 00000000..8c2f1340 --- /dev/null +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isDisjoint.swift @@ -0,0 +1,128 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021-2022 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 +// +//===----------------------------------------------------------------------===// + +import _CollectionsUtilities + +// `OrderedSet` does not directly conform to `SetAlgebra` because its definition +// of equality conflicts with `SetAlgebra` requirements. However, it still +// implements most `SetAlgebra` requirements (except `insert`, which is replaced +// by `append`). +// +// `OrderedSet` also provides an `unordered` view that explicitly conforms to +// `SetAlgebra`. That view implements `Equatable` by ignoring element order, +// so it can satisfy `SetAlgebra` requirements. + +extension OrderedSet { + /// Returns a Boolean value that indicates whether the set has no members in + /// common with the given set. + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: OrderedSet = [5, 6] + /// a.isDisjoint(with: b) // true + /// + /// - Parameter other: Another set. + /// + /// - Returns: `true` if `self` has no elements in common with `other`; + /// otherwise, `false`. + /// + /// - Complexity: Expected to be O(min(`self.count`, `other.count`)) on + /// average, if `Element` implements high-quality hashing. + @inlinable + public func isDisjoint(with other: Self) -> Bool { + guard !self.isEmpty && !other.isEmpty else { return true } + if self.count <= other.count { + for item in self { + if other.contains(item) { return false } + } + } else { + for item in other { + if self.contains(item) { return false } + } + } + return true + } + + // Generalizations + + /// Returns a Boolean value that indicates whether the set has no members in + /// common with the given set. + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: OrderedSet = [5, 6] + /// a.isDisjoint(with: b.unordered) // true + /// + /// - Parameter other: Another set. + /// + /// - Returns: `true` if `self` has no elements in common with `other`; + /// otherwise, `false`. + /// + /// - Complexity: Expected to be O(min(`self.count`, `other.count`)) on + /// average, if `Element` implements high-quality hashing. + @inlinable + @inline(__always) + public func isDisjoint(with other: UnorderedView) -> Bool { + isDisjoint(with: other._base) + } + + /// Returns a Boolean value that indicates whether the set has no members in + /// common with the given set. + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: Set = [5, 6] + /// a.isDisjoint(with: b) // true + /// + /// - Parameter other: Another set. + /// + /// - Returns: `true` if `self` has no elements in common with `other`; + /// otherwise, `false`. + /// + /// - Complexity: Expected to be O(min(`self.count`, `other.count`)) on + /// average, if `Element` implements high-quality hashing. + @inlinable + public func isDisjoint(with other: Set) -> Bool { + guard !self.isEmpty && !other.isEmpty else { return true } + if self.count <= other.count { + for item in self { + if other.contains(item) { return false } + } + } else { + for item in other { + if self.contains(item) { return false } + } + } + return true + } + + /// Returns a Boolean value that indicates whether the set has no members in + /// common with the given sequence. + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: Array = [5, 6] + /// a.isDisjoint(with: b) // true + /// + /// - Parameter other: A finite sequence of elements. + /// + /// - Returns: `true` if `self` has no elements in common with `other`; + /// otherwise, `false`. + /// + /// - Complexity: Expected to be O(*n*) on average, where *n* is the number of + /// elements in `other`, if `Element` implements high-quality hashing. + @inlinable + public func isDisjoint( + with other: S + ) -> Bool where S.Element == Element { + guard !self.isEmpty else { return true } + for item in other { + if self.contains(item) { return false } + } + return true + } +} diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isStrictSubset.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isStrictSubset.swift new file mode 100644 index 00000000..b73ba5f6 --- /dev/null +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isStrictSubset.swift @@ -0,0 +1,154 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021-2022 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 +// +//===----------------------------------------------------------------------===// + +// `OrderedSet` does not directly conform to `SetAlgebra` because its definition +// of equality conflicts with `SetAlgebra` requirements. However, it still +// implements most `SetAlgebra` requirements (except `insert`, which is replaced +// by `append`). +// +// `OrderedSet` also provides an `unordered` view that explicitly conforms to +// `SetAlgebra`. That view implements `Equatable` by ignoring element order, +// so it can satisfy `SetAlgebra` requirements. + +extension OrderedSet { + /// Returns a Boolean value that indicates whether the set is a strict subset + /// of the given set. + /// + /// Set *A* is a strict subset of another set *B* if every member of *A* is + /// also a member of *B* and *B* contains at least one element that is not a + /// member of *A*. (Ignoring the order the elements appear in the sets.) + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: OrderedSet = [4, 2, 1] + /// b.isStrictSubset(of: a) // true + /// + /// - Parameter other: Another set. + /// + /// - Returns: `true` if `self` is a strict subset of `other`; otherwise, + /// `false`. + /// + /// - Complexity: Expected to be O(`self.count`) on average, if `Element` + /// implements high-quality hashing. + @inlinable + public func isStrictSubset(of other: Self) -> Bool { + self.count < other.count && self.isSubset(of: other) + } + + // Generalizations + + /// Returns a Boolean value that indicates whether the set is a strict subset + /// of the given set. + /// + /// Set *A* is a strict subset of another set *B* if every member of *A* is + /// also a member of *B* and *B* contains at least one element that is not a + /// member of *A*. (Ignoring the order the elements appear in the sets.) + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: OrderedSet = [4, 2, 1] + /// b.isStrictSubset(of: a.unordered) // true + /// + /// - Parameter other: Another set. + /// + /// - Returns: `true` if `self` is a strict subset of `other`; otherwise, + /// `false`. + /// + /// - Complexity: Expected to be O(`self.count`) on average, if `Element` + /// implements high-quality hashing. + @inlinable + @inline(__always) + public func isStrictSubset(of other: UnorderedView) -> Bool { + isStrictSubset(of: other._base) + } + + /// Returns a Boolean value that indicates whether the set is a strict subset + /// of the given set. + /// + /// Set *A* is a strict subset of another set *B* if every member of *A* is + /// also a member of *B* and *B* contains at least one element that is not a + /// member of *A*. (Ignoring the order the elements appear in the sets.) + /// + /// let a: Set = [1, 2, 3, 4] + /// let b: OrderedSet = [4, 2, 1] + /// b.isStrictSubset(of: a) // true + /// + /// - Parameter other: Another set. + /// + /// - Returns: `true` if `self` is a strict subset of `other`; otherwise, + /// `false`. + /// + /// - Complexity: Expected to be O(`self.count`) on average, if `Element` + /// implements high-quality hashing. + @inlinable + public func isStrictSubset(of other: Set) -> Bool { + self.count < other.count && self.isSubset(of: other) + } + + /// Returns a Boolean value that indicates whether the set is a strict subset + /// of the given sequence. + /// + /// Set *A* is a strict subset of another set *B* if every member of *A* is + /// also a member of *B* and *B* contains at least one element that is not a + /// member of *A*. (Ignoring the order the elements appear in the sets.) + /// + /// let a: Array = [1, 2, 3, 4] + /// let b: OrderedSet = [4, 2, 1] + /// b.isStrictSubset(of: a) // true + /// + /// - Parameter other: A finite sequence of elements. + /// + /// - Returns: `true` if `self` is a strict subset of `other`; otherwise, + /// `false`. + /// + /// - Complexity: Expected to be O(`self.count` + *n*) on average, where *n* + /// is the number of elements in `other`, if `Element` implements + /// high-quality hashing. + @inlinable + public func isStrictSubset( + of other: S + ) -> Bool where S.Element == Element { + if S.self == Self.self { + return self.isStrictSubset(of: other as! Self) + } + if S.self == Set.self { + return self.isStrictSubset(of: other as! Set) + } + + var it = self.makeIterator() + guard let first = it.next() else { + return other.contains(where: { _ in true }) + } + if let match = other._customContainsEquatableElement(first) { + // Fast path: the sequence has fast containment checks. + guard match else { return false } + while let item = it.next() { + guard other.contains(item) else { return false } + } + return !other.allSatisfy { self.contains($0) } + } + + return _UnsafeBitset.withTemporaryBitset(capacity: count) { seen in + // Mark elements in `self` that we've seen in `other`. + var isKnownStrict = false + for item in other { + if let index = _find(item).index { + if seen.insert(index), seen.count == self.count, isKnownStrict { + // We've seen enough. + return true + } + } else { + if !isKnownStrict, seen.count == self.count { return true } + isKnownStrict = true + } + } + return false + } + } +} diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isStrictSuperset.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isStrictSuperset.swift new file mode 100644 index 00000000..53f98b4a --- /dev/null +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isStrictSuperset.swift @@ -0,0 +1,152 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021-2022 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 +// +//===----------------------------------------------------------------------===// + +// `OrderedSet` does not directly conform to `SetAlgebra` because its definition +// of equality conflicts with `SetAlgebra` requirements. However, it still +// implements most `SetAlgebra` requirements (except `insert`, which is replaced +// by `append`). +// +// `OrderedSet` also provides an `unordered` view that explicitly conforms to +// `SetAlgebra`. That view implements `Equatable` by ignoring element order, +// so it can satisfy `SetAlgebra` requirements. + +extension OrderedSet { + /// Returns a Boolean value that indicates whether the set is a strict + /// superset of the given set. + /// + /// Set *A* is a strict superset of another set *B* if every member of *B* is + /// also a member of *A* and *A* contains at least one element that is *not* + /// a member of *B*. (Ignoring the order the elements appear in the sets.) + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: OrderedSet = [4, 2, 1] + /// a.isStrictSuperset(of: b) // true + /// + /// - Parameter other: Another set. + /// + /// - Returns: `true` if `self` is a strict superset of `other`; otherwise, + /// `false`. + /// + /// - Complexity: Expected to be O(`other.count`) on average, if `Element` + /// implements high-quality hashing. + @inlinable + public func isStrictSuperset(of other: Self) -> Bool { + self.count > other.count && other.isSubset(of: self) + } + + // Generalizations + + /// Returns a Boolean value that indicates whether the set is a strict + /// superset of the given set. + /// + /// Set *A* is a strict superset of another set *B* if every member of *B* is + /// also a member of *A* and *A* contains at least one element that is *not* + /// a member of *B*. (Ignoring the order the elements appear in the sets.) + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: OrderedSet = [4, 2, 1] + /// a.isStrictSuperset(of: b.unordered) // true + /// + /// - Parameter other: Another set. + /// + /// - Returns: `true` if `self` is a strict superset of `other`; otherwise, + /// `false`. + /// + /// - Complexity: Expected to be O(`other.count`) on average, if `Element` + /// implements high-quality hashing. + @inlinable + @inline(__always) + public func isStrictSuperset(of other: UnorderedView) -> Bool { + isStrictSuperset(of: other._base) + } + + /// Returns a Boolean value that indicates whether the set is a strict + /// superset of the given set. + /// + /// Set *A* is a strict superset of another set *B* if every member of *B* is + /// also a member of *A* and *A* contains at least one element that is *not* + /// a member of *B*. (Ignoring the order the elements appear in the sets.) + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: Set = [4, 2, 1] + /// a.isStrictSuperset(of: b) // true + /// + /// - Parameter other: Another set. + /// + /// - Returns: `true` if `self` is a strict superset of `other`; otherwise, + /// `false`. + /// + /// - Complexity: Expected to be O(`other.count`) on average, if `Element` + /// implements high-quality hashing. + @inlinable + public func isStrictSuperset(of other: Set) -> Bool { + self.count > other.count && other.isSubset(of: self) + } + + /// Returns a Boolean value that indicates whether the set is a strict + /// superset of the given sequence. + /// + /// Set *A* is a strict superset of another set *B* if every member of *B* is + /// also a member of *A* and *A* contains at least one element that is *not* + /// a member of *B*. (Ignoring the order the elements appear in the sets.) + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: Array = [4, 2, 1] + /// a.isStrictSuperset(of: b) // true + /// + /// - Parameter other: A finite sequence of elements, some of whose members + /// may appear more than once. (Duplicate items are ignored.) + /// + /// - Returns: `true` if `self` is a strict superset of `other`; otherwise, + /// `false`. + /// + /// - Complexity: Expected to be O(`self.count` + *n*) on average, where *n* + /// is the number of elements in `other`, if `Element` implements + /// high-quality hashing. + @inlinable + public func isStrictSuperset( + of other: S + ) -> Bool where S.Element == Element { + if S.self == Self.self { + return self.isStrictSuperset(of: other as! Self) + } + if S.self == Set.self { + return self.isStrictSuperset(of: other as! Set) + } + + var it = self.makeIterator() + guard let first = it.next() else { return false } + if let match = other._customContainsEquatableElement(first) { + // Fast path: the sequence has fast containment checks. + guard other.allSatisfy({ self.contains($0) }) else { return false } + guard match else { return true } + while let item = it.next() { + guard other.contains(item) else { return true } + } + return false + } + + return _UnsafeBitset.withTemporaryBitset(capacity: count) { seen in + // Mark elements in `self` that we've seen in `other`. + for item in other { + guard let index = _find(item).index else { + return false + } + if seen.insert(index), seen.count == self.count { + // We've seen enough. + return false + } + } + return seen.count < self.count + } + } +} + diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isSubset.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isSubset.swift new file mode 100644 index 00000000..0fc3d599 --- /dev/null +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isSubset.swift @@ -0,0 +1,147 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021-2022 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 +// +//===----------------------------------------------------------------------===// + +// `OrderedSet` does not directly conform to `SetAlgebra` because its definition +// of equality conflicts with `SetAlgebra` requirements. However, it still +// implements most `SetAlgebra` requirements (except `insert`, which is replaced +// by `append`). +// +// `OrderedSet` also provides an `unordered` view that explicitly conforms to +// `SetAlgebra`. That view implements `Equatable` by ignoring element order, +// so it can satisfy `SetAlgebra` requirements. + +extension OrderedSet { + /// Returns a Boolean value that indicates whether this set is a subset of + /// the given set. + /// + /// Set *A* is a subset of another set *B* if every member of *A* is also a + /// member of *B*, ignoring the order they appear in the two sets. + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: OrderedSet = [4, 2, 1] + /// b.isSubset(of: a) // true + /// + /// - Parameter other: Another set. + /// + /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. + /// + /// - Complexity: Expected to be O(`self.count`) on average, if `Element` + /// implements high-quality hashing. + @inlinable + public func isSubset(of other: Self) -> Bool { + guard other.count >= self.count else { return false } + for item in self { + guard other.contains(item) else { return false } + } + return true + } + + // Generalizations + + /// Returns a Boolean value that indicates whether this set is a subset of + /// the given set. + /// + /// Set *A* is a subset of another set *B* if every member of *A* is also a + /// member of *B*, ignoring the order they appear in the two sets. + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: OrderedSet = [4, 2, 1] + /// b.isSubset(of: a.unordered) // true + /// + /// - Parameter other: Another set. + /// + /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. + /// + /// - Complexity: Expected to be O(`self.count`) on average, if `Element` + /// implements high-quality hashing. + @inlinable + @inline(__always) + public func isSubset(of other: UnorderedView) -> Bool { + isSubset(of: other._base) + } + + /// Returns a Boolean value that indicates whether this set is a subset of + /// the given set. + /// + /// Set *A* is a subset of another set *B* if every member of *A* is also a + /// member of *B*, ignoring the order they appear in the two sets. + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: Set = [4, 2, 1] + /// b.isSubset(of: a) // true + /// + /// - Parameter other: Another set. + /// + /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. + /// + /// - Complexity: Expected to be O(`self.count`) on average, if `Element` + /// implements high-quality hashing. + @inlinable + public func isSubset(of other: Set) -> Bool { + guard other.count >= self.count else { return false } + for item in self { + guard other.contains(item) else { return false } + } + return true + } + + /// Returns a Boolean value that indicates whether this set is a subset of + /// the elements in the given sequence. + /// + /// Set *A* is a subset of another set *B* if every member of *A* is also a + /// member of *B*, ignoring the order they appear in the two sets. + /// + /// let a: Array = [1, 2, 3, 4] + /// let b: OrderedSet = [4, 2, 1] + /// b.isSubset(of: a) // true + /// + /// - Parameter other: A finite sequence. + /// + /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. + /// + /// - Complexity: Expected to be O(`self.count` + *n*) on average, where *n* + /// is the number of elements in `other`, if `Element` implements + /// high-quality hashing. + @inlinable + public func isSubset( + of other: S + ) -> Bool where S.Element == Element { + guard !isEmpty else { return true } + + if S.self == Self.self { + return isSubset(of: other as! Self) + } + + var it = self.makeIterator() + let first = it.next()! + if let match = other._customContainsEquatableElement(first) { + // Fast path: the sequence has fast containment checks. + guard match else { return false } + while let item = it.next() { + guard other.contains(item) else { return false } + } + return true + } + + return _UnsafeBitset.withTemporaryBitset(capacity: count) { seen in + // Mark elements in `self` that we've seen in `other`. + for item in other { + if let index = _find(item).index { + if seen.insert(index), seen.count == self.count { + // We've seen enough. + return true + } + } + } + return false + } + } +} diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isSuperset.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isSuperset.swift new file mode 100644 index 00000000..2cb62aca --- /dev/null +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isSuperset.swift @@ -0,0 +1,124 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021-2022 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 +// +//===----------------------------------------------------------------------===// + +// `OrderedSet` does not directly conform to `SetAlgebra` because its definition +// of equality conflicts with `SetAlgebra` requirements. However, it still +// implements most `SetAlgebra` requirements (except `insert`, which is replaced +// by `append`). +// +// `OrderedSet` also provides an `unordered` view that explicitly conforms to +// `SetAlgebra`. That view implements `Equatable` by ignoring element order, +// so it can satisfy `SetAlgebra` requirements. + +extension OrderedSet { + /// Returns a Boolean value that indicates whether this set is a superset of + /// the given set. + /// + /// Set *A* is a superset of another set *B* if every member of *B* is also a + /// member of *A*, ignoring the order they appear in the two sets. + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: OrderedSet = [4, 2, 1] + /// a.isSuperset(of: b) // true + /// + /// - Parameter other: Another set. + /// + /// - Returns: `true` if the set is a superset of `other`; otherwise, `false`. + /// + /// - Complexity: Expected to be O(`other.count`) on average, if `Element` + /// implements high-quality hashing. + @inlinable + public func isSuperset(of other: Self) -> Bool { + other.isSubset(of: self) + } + + // Generalizations + + /// Returns a Boolean value that indicates whether this set is a superset of + /// the given set. + /// + /// Set *A* is a superset of another set *B* if every member of *B* is also a + /// member of *A*, ignoring the order they appear in the two sets. + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: Set = [4, 2, 1] + /// a.isSuperset(of: b) // true + /// + /// - Parameter other: Another set. + /// + /// - Returns: `true` if the set is a superset of `other`; otherwise, `false`. + /// + /// - Complexity: Expected to be O(`other.count`) on average, if `Element` + /// implements high-quality hashing. + @inlinable + public func isSuperset(of other: UnorderedView) -> Bool { + isSuperset(of: other._base) + } + + /// Returns a Boolean value that indicates whether this set is a superset of + /// the given set. + /// + /// Set *A* is a superset of another set *B* if every member of *B* is also a + /// member of *A*, ignoring the order they appear in the two sets. + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: Set = [4, 2, 1] + /// a.isSuperset(of: b) // true + /// + /// - Parameter other: Another set. + /// + /// - Returns: `true` if the set is a superset of `other`; otherwise, `false`. + /// + /// - Complexity: Expected to be O(`other.count`) on average, if `Element` + /// implements high-quality hashing. + @inlinable + public func isSuperset(of other: Set) -> Bool { + guard self.count >= other.count else { return false } + return _isSuperset(of: other) + } + + /// Returns a Boolean value that indicates whether this set is a superset of + /// the given sequence. + /// + /// Set *A* is a superset of another set *B* if every member of *B* is also a + /// member of *A*, ignoring the order they appear in the two sets. + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: Array = [4, 2, 1] + /// a.isSuperset(of: b) // true + /// + /// - Parameter other: A finite sequence of elements, some of whose members + /// may appear more than once. (Duplicate items are ignored.) + /// + /// - Returns: `true` if the set is a superset of `other`; otherwise, `false`. + /// + /// - Complexity: Expected to be O(*n*) on average, where *n* is the number of + /// elements in `other`, if `Element` implements high-quality hashing. + @inlinable + public func isSuperset( + of other: S + ) -> Bool where S.Element == Element { + _isSuperset(of: other) + } + + @inlinable + internal func _isSuperset( + of other: S + ) -> Bool where S.Element == Element { + if S.self == Self.self { + return self.isSuperset(of: other as! Self) + } + for item in other { + guard self.contains(item) else { return false } + } + return true + } +} diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra+Predicates.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra+Predicates.swift deleted file mode 100644 index c5f67ba7..00000000 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra+Predicates.swift +++ /dev/null @@ -1,629 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift Collections open source project -// -// Copyright (c) 2021 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 -// -//===----------------------------------------------------------------------===// - -import _CollectionsUtilities - -// `OrderedSet` does not directly conform to `SetAlgebra` because its definition -// of equality conflicts with `SetAlgebra` requirements. However, it still -// implements most `SetAlgebra` requirements (except `insert`, which is replaced -// by `append`). -// -// `OrderedSet` also provides an `unordered` view that explicitly conforms to -// `SetAlgebra`. That view implements `Equatable` by ignoring element order, -// so it can satisfy `SetAlgebra` requirements. - -extension OrderedSet { - /// Returns a Boolean value that indicates whether this set is a subset of - /// the given set. - /// - /// Set *A* is a subset of another set *B* if every member of *A* is also a - /// member of *B*, ignoring the order they appear in the two sets. - /// - /// let a: OrderedSet = [1, 2, 3, 4] - /// let b: OrderedSet = [4, 2, 1] - /// b.isSubset(of: a) // true - /// - /// - Parameter other: Another set. - /// - /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. - /// - /// - Complexity: Expected to be O(`self.count`) on average, if `Element` - /// implements high-quality hashing. - @inlinable - public func isSubset(of other: Self) -> Bool { - guard other.count >= self.count else { return false } - for item in self { - guard other.contains(item) else { return false } - } - return true - } - - // Generalizations - - /// Returns a Boolean value that indicates whether this set is a subset of - /// the given set. - /// - /// Set *A* is a subset of another set *B* if every member of *A* is also a - /// member of *B*, ignoring the order they appear in the two sets. - /// - /// let a: OrderedSet = [1, 2, 3, 4] - /// let b: OrderedSet = [4, 2, 1] - /// b.isSubset(of: a.unordered) // true - /// - /// - Parameter other: Another set. - /// - /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. - /// - /// - Complexity: Expected to be O(`self.count`) on average, if `Element` - /// implements high-quality hashing. - @inlinable - @inline(__always) - public func isSubset(of other: UnorderedView) -> Bool { - isSubset(of: other._base) - } - - /// Returns a Boolean value that indicates whether this set is a subset of - /// the given set. - /// - /// Set *A* is a subset of another set *B* if every member of *A* is also a - /// member of *B*, ignoring the order they appear in the two sets. - /// - /// let a: OrderedSet = [1, 2, 3, 4] - /// let b: Set = [4, 2, 1] - /// b.isSubset(of: a) // true - /// - /// - Parameter other: Another set. - /// - /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. - /// - /// - Complexity: Expected to be O(`self.count`) on average, if `Element` - /// implements high-quality hashing. - @inlinable - public func isSubset(of other: Set) -> Bool { - guard other.count >= self.count else { return false } - for item in self { - guard other.contains(item) else { return false } - } - return true - } - - /// Returns a Boolean value that indicates whether this set is a subset of - /// the elements in the given sequence. - /// - /// Set *A* is a subset of another set *B* if every member of *A* is also a - /// member of *B*, ignoring the order they appear in the two sets. - /// - /// let a: Array = [1, 2, 3, 4] - /// let b: OrderedSet = [4, 2, 1] - /// b.isSubset(of: a) // true - /// - /// - Parameter other: A finite sequence. - /// - /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. - /// - /// - Complexity: Expected to be O(`self.count` + *n*) on average, where *n* - /// is the number of elements in `other`, if `Element` implements - /// high-quality hashing. - @inlinable - public func isSubset( - of other: S - ) -> Bool where S.Element == Element { - guard !isEmpty else { return true } - - if S.self == Self.self { - return isSubset(of: other as! Self) - } - - var it = self.makeIterator() - let first = it.next()! - if let match = other._customContainsEquatableElement(first) { - // Fast path: the sequence has fast containment checks. - guard match else { return false } - while let item = it.next() { - guard other.contains(item) else { return false } - } - return true - } - - return _UnsafeBitset.withTemporaryBitset(capacity: count) { seen in - // Mark elements in `self` that we've seen in `other`. - for item in other { - if let index = _find(item).index { - if seen.insert(index), seen.count == self.count { - // We've seen enough. - return true - } - } - } - return false - } - } -} - -extension OrderedSet { - /// Returns a Boolean value that indicates whether this set is a superset of - /// the given set. - /// - /// Set *A* is a superset of another set *B* if every member of *B* is also a - /// member of *A*, ignoring the order they appear in the two sets. - /// - /// let a: OrderedSet = [1, 2, 3, 4] - /// let b: OrderedSet = [4, 2, 1] - /// a.isSuperset(of: b) // true - /// - /// - Parameter other: Another set. - /// - /// - Returns: `true` if the set is a superset of `other`; otherwise, `false`. - /// - /// - Complexity: Expected to be O(`other.count`) on average, if `Element` - /// implements high-quality hashing. - @inlinable - public func isSuperset(of other: Self) -> Bool { - other.isSubset(of: self) - } - - // Generalizations - - /// Returns a Boolean value that indicates whether this set is a superset of - /// the given set. - /// - /// Set *A* is a superset of another set *B* if every member of *B* is also a - /// member of *A*, ignoring the order they appear in the two sets. - /// - /// let a: OrderedSet = [1, 2, 3, 4] - /// let b: Set = [4, 2, 1] - /// a.isSuperset(of: b) // true - /// - /// - Parameter other: Another set. - /// - /// - Returns: `true` if the set is a superset of `other`; otherwise, `false`. - /// - /// - Complexity: Expected to be O(`other.count`) on average, if `Element` - /// implements high-quality hashing. - @inlinable - public func isSuperset(of other: UnorderedView) -> Bool { - isSuperset(of: other._base) - } - - /// Returns a Boolean value that indicates whether this set is a superset of - /// the given set. - /// - /// Set *A* is a superset of another set *B* if every member of *B* is also a - /// member of *A*, ignoring the order they appear in the two sets. - /// - /// let a: OrderedSet = [1, 2, 3, 4] - /// let b: Set = [4, 2, 1] - /// a.isSuperset(of: b) // true - /// - /// - Parameter other: Another set. - /// - /// - Returns: `true` if the set is a superset of `other`; otherwise, `false`. - /// - /// - Complexity: Expected to be O(`other.count`) on average, if `Element` - /// implements high-quality hashing. - @inlinable - public func isSuperset(of other: Set) -> Bool { - guard self.count >= other.count else { return false } - return _isSuperset(of: other) - } - - /// Returns a Boolean value that indicates whether this set is a superset of - /// the given sequence. - /// - /// Set *A* is a superset of another set *B* if every member of *B* is also a - /// member of *A*, ignoring the order they appear in the two sets. - /// - /// let a: OrderedSet = [1, 2, 3, 4] - /// let b: Array = [4, 2, 1] - /// a.isSuperset(of: b) // true - /// - /// - Parameter other: A finite sequence of elements, some of whose members - /// may appear more than once. (Duplicate items are ignored.) - /// - /// - Returns: `true` if the set is a superset of `other`; otherwise, `false`. - /// - /// - Complexity: Expected to be O(*n*) on average, where *n* is the number of - /// elements in `other`, if `Element` implements high-quality hashing. - @inlinable - public func isSuperset( - of other: S - ) -> Bool where S.Element == Element { - _isSuperset(of: other) - } - - @inlinable - internal func _isSuperset( - of other: S - ) -> Bool where S.Element == Element { - if S.self == Self.self { - return self.isSuperset(of: other as! Self) - } - for item in other { - guard self.contains(item) else { return false } - } - return true - } -} - -extension OrderedSet { - /// Returns a Boolean value that indicates whether the set is a strict subset - /// of the given set. - /// - /// Set *A* is a strict subset of another set *B* if every member of *A* is - /// also a member of *B* and *B* contains at least one element that is not a - /// member of *A*. (Ignoring the order the elements appear in the sets.) - /// - /// let a: OrderedSet = [1, 2, 3, 4] - /// let b: OrderedSet = [4, 2, 1] - /// b.isStrictSubset(of: a) // true - /// - /// - Parameter other: Another set. - /// - /// - Returns: `true` if `self` is a strict subset of `other`; otherwise, - /// `false`. - /// - /// - Complexity: Expected to be O(`self.count`) on average, if `Element` - /// implements high-quality hashing. - @inlinable - public func isStrictSubset(of other: Self) -> Bool { - self.count < other.count && self.isSubset(of: other) - } - - // Generalizations - - /// Returns a Boolean value that indicates whether the set is a strict subset - /// of the given set. - /// - /// Set *A* is a strict subset of another set *B* if every member of *A* is - /// also a member of *B* and *B* contains at least one element that is not a - /// member of *A*. (Ignoring the order the elements appear in the sets.) - /// - /// let a: OrderedSet = [1, 2, 3, 4] - /// let b: OrderedSet = [4, 2, 1] - /// b.isStrictSubset(of: a.unordered) // true - /// - /// - Parameter other: Another set. - /// - /// - Returns: `true` if `self` is a strict subset of `other`; otherwise, - /// `false`. - /// - /// - Complexity: Expected to be O(`self.count`) on average, if `Element` - /// implements high-quality hashing. - @inlinable - @inline(__always) - public func isStrictSubset(of other: UnorderedView) -> Bool { - isStrictSubset(of: other._base) - } - - /// Returns a Boolean value that indicates whether the set is a strict subset - /// of the given set. - /// - /// Set *A* is a strict subset of another set *B* if every member of *A* is - /// also a member of *B* and *B* contains at least one element that is not a - /// member of *A*. (Ignoring the order the elements appear in the sets.) - /// - /// let a: Set = [1, 2, 3, 4] - /// let b: OrderedSet = [4, 2, 1] - /// b.isStrictSubset(of: a) // true - /// - /// - Parameter other: Another set. - /// - /// - Returns: `true` if `self` is a strict subset of `other`; otherwise, - /// `false`. - /// - /// - Complexity: Expected to be O(`self.count`) on average, if `Element` - /// implements high-quality hashing. - @inlinable - public func isStrictSubset(of other: Set) -> Bool { - self.count < other.count && self.isSubset(of: other) - } - - /// Returns a Boolean value that indicates whether the set is a strict subset - /// of the given sequence. - /// - /// Set *A* is a strict subset of another set *B* if every member of *A* is - /// also a member of *B* and *B* contains at least one element that is not a - /// member of *A*. (Ignoring the order the elements appear in the sets.) - /// - /// let a: Array = [1, 2, 3, 4] - /// let b: OrderedSet = [4, 2, 1] - /// b.isStrictSubset(of: a) // true - /// - /// - Parameter other: A finite sequence of elements. - /// - /// - Returns: `true` if `self` is a strict subset of `other`; otherwise, - /// `false`. - /// - /// - Complexity: Expected to be O(`self.count` + *n*) on average, where *n* - /// is the number of elements in `other`, if `Element` implements - /// high-quality hashing. - @inlinable - public func isStrictSubset( - of other: S - ) -> Bool where S.Element == Element { - if S.self == Self.self { - return self.isStrictSubset(of: other as! Self) - } - if S.self == Set.self { - return self.isStrictSubset(of: other as! Set) - } - - var it = self.makeIterator() - guard let first = it.next() else { - return other.contains(where: { _ in true }) - } - if let match = other._customContainsEquatableElement(first) { - // Fast path: the sequence has fast containment checks. - guard match else { return false } - while let item = it.next() { - guard other.contains(item) else { return false } - } - return !other.allSatisfy { self.contains($0) } - } - - return _UnsafeBitset.withTemporaryBitset(capacity: count) { seen in - // Mark elements in `self` that we've seen in `other`. - var isKnownStrict = false - for item in other { - if let index = _find(item).index { - if seen.insert(index), seen.count == self.count, isKnownStrict { - // We've seen enough. - return true - } - } else { - if !isKnownStrict, seen.count == self.count { return true } - isKnownStrict = true - } - } - return false - } - } -} - -extension OrderedSet { - /// Returns a Boolean value that indicates whether the set is a strict - /// superset of the given set. - /// - /// Set *A* is a strict superset of another set *B* if every member of *B* is - /// also a member of *A* and *A* contains at least one element that is *not* - /// a member of *B*. (Ignoring the order the elements appear in the sets.) - /// - /// let a: OrderedSet = [1, 2, 3, 4] - /// let b: OrderedSet = [4, 2, 1] - /// a.isStrictSuperset(of: b) // true - /// - /// - Parameter other: Another set. - /// - /// - Returns: `true` if `self` is a strict superset of `other`; otherwise, - /// `false`. - /// - /// - Complexity: Expected to be O(`other.count`) on average, if `Element` - /// implements high-quality hashing. - @inlinable - public func isStrictSuperset(of other: Self) -> Bool { - self.count > other.count && other.isSubset(of: self) - } - - // Generalizations - - /// Returns a Boolean value that indicates whether the set is a strict - /// superset of the given set. - /// - /// Set *A* is a strict superset of another set *B* if every member of *B* is - /// also a member of *A* and *A* contains at least one element that is *not* - /// a member of *B*. (Ignoring the order the elements appear in the sets.) - /// - /// let a: OrderedSet = [1, 2, 3, 4] - /// let b: OrderedSet = [4, 2, 1] - /// a.isStrictSuperset(of: b.unordered) // true - /// - /// - Parameter other: Another set. - /// - /// - Returns: `true` if `self` is a strict superset of `other`; otherwise, - /// `false`. - /// - /// - Complexity: Expected to be O(`other.count`) on average, if `Element` - /// implements high-quality hashing. - @inlinable - @inline(__always) - public func isStrictSuperset(of other: UnorderedView) -> Bool { - isStrictSuperset(of: other._base) - } - - /// Returns a Boolean value that indicates whether the set is a strict - /// superset of the given set. - /// - /// Set *A* is a strict superset of another set *B* if every member of *B* is - /// also a member of *A* and *A* contains at least one element that is *not* - /// a member of *B*. (Ignoring the order the elements appear in the sets.) - /// - /// let a: OrderedSet = [1, 2, 3, 4] - /// let b: Set = [4, 2, 1] - /// a.isStrictSuperset(of: b) // true - /// - /// - Parameter other: Another set. - /// - /// - Returns: `true` if `self` is a strict superset of `other`; otherwise, - /// `false`. - /// - /// - Complexity: Expected to be O(`other.count`) on average, if `Element` - /// implements high-quality hashing. - @inlinable - public func isStrictSuperset(of other: Set) -> Bool { - self.count > other.count && other.isSubset(of: self) - } - - /// Returns a Boolean value that indicates whether the set is a strict - /// superset of the given sequence. - /// - /// Set *A* is a strict superset of another set *B* if every member of *B* is - /// also a member of *A* and *A* contains at least one element that is *not* - /// a member of *B*. (Ignoring the order the elements appear in the sets.) - /// - /// let a: OrderedSet = [1, 2, 3, 4] - /// let b: Array = [4, 2, 1] - /// a.isStrictSuperset(of: b) // true - /// - /// - Parameter other: A finite sequence of elements, some of whose members - /// may appear more than once. (Duplicate items are ignored.) - /// - /// - Returns: `true` if `self` is a strict superset of `other`; otherwise, - /// `false`. - /// - /// - Complexity: Expected to be O(`self.count` + *n*) on average, where *n* - /// is the number of elements in `other`, if `Element` implements - /// high-quality hashing. - @inlinable - public func isStrictSuperset( - of other: S - ) -> Bool where S.Element == Element { - if S.self == Self.self { - return self.isStrictSuperset(of: other as! Self) - } - if S.self == Set.self { - return self.isStrictSuperset(of: other as! Set) - } - - var it = self.makeIterator() - guard let first = it.next() else { return false } - if let match = other._customContainsEquatableElement(first) { - // Fast path: the sequence has fast containment checks. - guard other.allSatisfy({ self.contains($0) }) else { return false } - guard match else { return true } - while let item = it.next() { - guard other.contains(item) else { return true } - } - return false - } - - return _UnsafeBitset.withTemporaryBitset(capacity: count) { seen in - // Mark elements in `self` that we've seen in `other`. - for item in other { - guard let index = _find(item).index else { - return false - } - if seen.insert(index), seen.count == self.count { - // We've seen enough. - return false - } - } - return seen.count < self.count - } - } -} - -extension OrderedSet { - /// Returns a Boolean value that indicates whether the set has no members in - /// common with the given set. - /// - /// let a: OrderedSet = [1, 2, 3, 4] - /// let b: OrderedSet = [5, 6] - /// a.isDisjoint(with: b) // true - /// - /// - Parameter other: Another set. - /// - /// - Returns: `true` if `self` has no elements in common with `other`; - /// otherwise, `false`. - /// - /// - Complexity: Expected to be O(min(`self.count`, `other.count`)) on - /// average, if `Element` implements high-quality hashing. - @inlinable - public func isDisjoint(with other: Self) -> Bool { - guard !self.isEmpty && !other.isEmpty else { return true } - if self.count <= other.count { - for item in self { - if other.contains(item) { return false } - } - } else { - for item in other { - if self.contains(item) { return false } - } - } - return true - } - - // Generalizations - - /// Returns a Boolean value that indicates whether the set has no members in - /// common with the given set. - /// - /// let a: OrderedSet = [1, 2, 3, 4] - /// let b: OrderedSet = [5, 6] - /// a.isDisjoint(with: b.unordered) // true - /// - /// - Parameter other: Another set. - /// - /// - Returns: `true` if `self` has no elements in common with `other`; - /// otherwise, `false`. - /// - /// - Complexity: Expected to be O(min(`self.count`, `other.count`)) on - /// average, if `Element` implements high-quality hashing. - @inlinable - @inline(__always) - public func isDisjoint(with other: UnorderedView) -> Bool { - isDisjoint(with: other._base) - } - - /// Returns a Boolean value that indicates whether the set has no members in - /// common with the given set. - /// - /// let a: OrderedSet = [1, 2, 3, 4] - /// let b: Set = [5, 6] - /// a.isDisjoint(with: b) // true - /// - /// - Parameter other: Another set. - /// - /// - Returns: `true` if `self` has no elements in common with `other`; - /// otherwise, `false`. - /// - /// - Complexity: Expected to be O(min(`self.count`, `other.count`)) on - /// average, if `Element` implements high-quality hashing. - @inlinable - public func isDisjoint(with other: Set) -> Bool { - guard !self.isEmpty && !other.isEmpty else { return true } - if self.count <= other.count { - for item in self { - if other.contains(item) { return false } - } - } else { - for item in other { - if self.contains(item) { return false } - } - } - return true - } - - /// Returns a Boolean value that indicates whether the set has no members in - /// common with the given sequence. - /// - /// let a: OrderedSet = [1, 2, 3, 4] - /// let b: Array = [5, 6] - /// a.isDisjoint(with: b) // true - /// - /// - Parameter other: A finite sequence of elements. - /// - /// - Returns: `true` if `self` has no elements in common with `other`; - /// otherwise, `false`. - /// - /// - Complexity: Expected to be O(*n*) on average, where *n* is the number of - /// elements in `other`, if `Element` implements high-quality hashing. - @inlinable - public func isDisjoint( - with other: S - ) -> Bool where S.Element == Element { - guard !self.isEmpty else { return true } - for item in other { - if self.contains(item) { return false } - } - return true - } -} - From 3c6cb8cd56d04392bf9f79a2d5020fc2abf1958d Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 19 Oct 2022 17:35:13 -0700 Subject: [PATCH 25/31] Update CMake configuration --- Sources/BitCollections/CMakeLists.txt | 1 + Sources/OrderedCollections/CMakeLists.txt | 17 +++++++++++------ Sources/_CollectionsUtilities/CMakeLists.txt | 2 ++ ...ollections.swift => _SortedCollection.swift} | 0 4 files changed, 14 insertions(+), 6 deletions(-) rename Sources/_CollectionsUtilities/{_SortedCollections.swift => _SortedCollection.swift} (100%) diff --git a/Sources/BitCollections/CMakeLists.txt b/Sources/BitCollections/CMakeLists.txt index e7f62c45..2e9c3681 100644 --- a/Sources/BitCollections/CMakeLists.txt +++ b/Sources/BitCollections/CMakeLists.txt @@ -47,6 +47,7 @@ add_library(BitCollections "BitSet/BitSet+SetAlgebra formUnion.swift" "BitSet/BitSet+SetAlgebra intersection.swift" "BitSet/BitSet+SetAlgebra isDisjoint.swift" + "BitSet/BitSet+SetAlgebra isEqual.swift" "BitSet/BitSet+SetAlgebra isStrictSubset.swift" "BitSet/BitSet+SetAlgebra isStrictSuperset.swift" "BitSet/BitSet+SetAlgebra isSubset.swift" diff --git a/Sources/OrderedCollections/CMakeLists.txt b/Sources/OrderedCollections/CMakeLists.txt index e6408926..f1cd5271 100644 --- a/Sources/OrderedCollections/CMakeLists.txt +++ b/Sources/OrderedCollections/CMakeLists.txt @@ -8,14 +8,16 @@ See https://swift.org/LICENSE.txt for license information #]] add_library(OrderedCollections + "HashTable/_HashTable.swift" "HashTable/_HashTable+Bucket.swift" "HashTable/_HashTable+BucketIterator.swift" "HashTable/_HashTable+Constants.swift" "HashTable/_HashTable+CustomStringConvertible.swift" + "HashTable/_Hashtable+Header.swift" "HashTable/_HashTable+Testing.swift" "HashTable/_HashTable+UnsafeHandle.swift" - "HashTable/_HashTable.swift" - "HashTable/_Hashtable+Header.swift" + "OrderedDictionary/OrderedDictionary.Elements.swift" + "OrderedDictionary/OrderedDictionary.swift" "OrderedDictionary/OrderedDictionary+Codable.swift" "OrderedDictionary/OrderedDictionary+CustomReflectable.swift" "OrderedDictionary/OrderedDictionary+Deprecations.swift" @@ -31,8 +33,7 @@ add_library(OrderedCollections "OrderedDictionary/OrderedDictionary+Sendable.swift" "OrderedDictionary/OrderedDictionary+Sequence.swift" "OrderedDictionary/OrderedDictionary+Values.swift" - "OrderedDictionary/OrderedDictionary.Elements.swift" - "OrderedDictionary/OrderedDictionary.swift" + "OrderedSet/OrderedSet.swift" "OrderedSet/OrderedSet+Codable.swift" "OrderedSet/OrderedSet+CustomReflectable.swift" "OrderedSet/OrderedSet+Descriptions.swift" @@ -45,9 +46,14 @@ add_library(OrderedCollections "OrderedSet/OrderedSet+Invariants.swift" "OrderedSet/OrderedSet+Partial MutableCollection.swift" "OrderedSet/OrderedSet+Partial RangeReplaceableCollection.swift" + "OrderedSet/OrderedSet+Partial SetAlgebra isDisjoint.swift" + "OrderedSet/OrderedSet+Partial SetAlgebra isEqual.swift" + "OrderedSet/OrderedSet+Partial SetAlgebra isStrictSubset.swift" + "OrderedSet/OrderedSet+Partial SetAlgebra isStrictSuperset.swift" + "OrderedSet/OrderedSet+Partial SetAlgebra isSubset.swift" + "OrderedSet/OrderedSet+Partial SetAlgebra isSuperset.swift" "OrderedSet/OrderedSet+Partial SetAlgebra+Basics.swift" "OrderedSet/OrderedSet+Partial SetAlgebra+Operations.swift" - "OrderedSet/OrderedSet+Partial SetAlgebra+Predicates.swift" "OrderedSet/OrderedSet+RandomAccessCollection.swift" "OrderedSet/OrderedSet+ReserveCapacity.swift" "OrderedSet/OrderedSet+Sendable.swift" @@ -55,7 +61,6 @@ add_library(OrderedCollections "OrderedSet/OrderedSet+Testing.swift" "OrderedSet/OrderedSet+UnorderedView.swift" "OrderedSet/OrderedSet+UnstableInternals.swift" - "OrderedSet/OrderedSet.swift" "Utilities/_UnsafeBitset.swift" ) target_link_libraries(OrderedCollections PRIVATE diff --git a/Sources/_CollectionsUtilities/CMakeLists.txt b/Sources/_CollectionsUtilities/CMakeLists.txt index fd24b7e4..e3572ef5 100644 --- a/Sources/_CollectionsUtilities/CMakeLists.txt +++ b/Sources/_CollectionsUtilities/CMakeLists.txt @@ -8,6 +8,8 @@ See https://swift.org/LICENSE.txt for license information #]] add_library(_CollectionsUtilities + "_SortedCollection.swift" + "_UniqueCollection.swift" "Array+WithContiguousStorage Compatibility.swift" "Debugging.swift" "Descriptions.swift" diff --git a/Sources/_CollectionsUtilities/_SortedCollections.swift b/Sources/_CollectionsUtilities/_SortedCollection.swift similarity index 100% rename from Sources/_CollectionsUtilities/_SortedCollections.swift rename to Sources/_CollectionsUtilities/_SortedCollection.swift From 2e276ba42b7c723dd142fc8149cccaf3bf49acdd Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Sat, 1 Oct 2022 12:36:42 -0700 Subject: [PATCH 26/31] [PersistentCollections] Clean up _Node.Builder & removals This sanitizes the semantics of _Node.Builder, removing the (unneccessary) need to pass around hash paths. It also slightly refactors removal operations, but stops short of implementing node shrinking. # Conflicts: # Sources/PersistentCollections/Node/_Node+Builder.swift # Sources/PersistentCollections/Node/_Node+Initializers.swift # Sources/PersistentCollections/Node/_Node+Structural intersection.swift # Sources/PersistentCollections/Node/_Node+Structural subtracting.swift # Sources/PersistentCollections/Node/_Node+Subtree Modify.swift # Sources/PersistentCollections/Node/_Node+Subtree Removals.swift # Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Initializers.swift # Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra Initializers.swift # Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra intersection.swift # Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra subtracting.swift (cherry picked from commit c73a8caad13a33043532f8e701e8c932c738808b) --- .../PersistentCollections/Node/_Hash.swift | 2 +- .../Node/_Node+Builder.swift | 318 ++++++++++++------ .../Node/_Node+CustomStringConvertible.swift | 42 --- .../Node/_Node+Debugging.swift | 9 +- .../Node/_Node+Initializers.swift | 5 +- .../Node/_Node+Invariants.swift | 9 +- .../Node/_Node+Primitive Removals.swift | 11 +- .../Node/_Node+Primitive Replacement.swift | 38 +-- .../_Node+Structural compactMapValues.swift | 15 +- .../Node/_Node+Structural filter.swift | 25 +- .../Node/_Node+Structural intersection.swift | 72 ++-- .../Node/_Node+Structural merge.swift | 14 +- .../Node/_Node+Structural subtracting.swift | 74 ++-- ..._Node+Structural symmetricDifference.swift | 102 +++--- .../Node/_Node+Structural union.swift | 28 +- .../Node/_Node+Subtree Insertions.swift | 71 +--- .../Node/_Node+Subtree Modify.swift | 25 +- .../Node/_Node+Subtree Removals.swift | 261 +++++++------- .../Node/_UnsafePath.swift | 33 -- .../PersistentDictionary+Debugging.swift | 2 +- .../PersistentDictionary+Filter.swift | 2 +- .../PersistentDictionary+Initializers.swift | 2 +- .../PersistentDictionary+MapValues.swift | 2 +- .../PersistentDictionary+Merge.swift | 2 +- .../PersistentDictionary.swift | 14 +- .../PersistentSet+Debugging.swift | 2 +- .../PersistentSet/PersistentSet+Filter.swift | 4 +- ...ersistentSet+SetAlgebra Initializers.swift | 2 +- .../PersistentSet+SetAlgebra basics.swift | 4 +- ...rsistentSet+SetAlgebra fluent basics.swift | 3 +- ...ersistentSet+SetAlgebra intersection.swift | 6 +- ...PersistentSet+SetAlgebra subtracting.swift | 4 +- ...ntSet+SetAlgebra symmetricDifference.swift | 3 +- .../PersistentSet+SetAlgebra union.swift | 4 +- 34 files changed, 558 insertions(+), 652 deletions(-) delete mode 100644 Sources/PersistentCollections/Node/_Node+CustomStringConvertible.swift diff --git a/Sources/PersistentCollections/Node/_Hash.swift b/Sources/PersistentCollections/Node/_Hash.swift index 43bf0818..ad26ab1b 100644 --- a/Sources/PersistentCollections/Node/_Hash.swift +++ b/Sources/PersistentCollections/Node/_Hash.swift @@ -70,7 +70,7 @@ extension _Hash { extension _Hash { @inlinable - internal static var emptyPrefix: _Hash { + internal static var emptyPath: _Hash { _Hash(_value: 0) } diff --git a/Sources/PersistentCollections/Node/_Node+Builder.swift b/Sources/PersistentCollections/Node/_Node+Builder.swift index b2b23347..7a7b1ea2 100644 --- a/Sources/PersistentCollections/Node/_Node+Builder.swift +++ b/Sources/PersistentCollections/Node/_Node+Builder.swift @@ -12,166 +12,276 @@ extension _Node { @usableFromInline @frozen - internal enum Builder { + internal struct Builder { @usableFromInline typealias Element = _Node.Element - case empty - case item(Element, _Hash) - case node(_Node, _Hash) + @usableFromInline + @frozen + internal enum Kind { + case empty + case item(Element, at: _Bucket) + case node(_Node) + case collisionNode(_Node) + } + + @usableFromInline + internal var level: _Level + + @usableFromInline + internal var kind: Kind + + @inlinable + internal init(_ level: _Level, _ kind: Kind) { + self.level = level + self.kind = kind + } + } +} + +extension _Node.Builder { + @usableFromInline + internal func dump() { + let head = "Builder(level: \(level.depth), kind: " + switch self.kind { + case .empty: + print(head + "empty)") + case .item(let item, at: let bucket): + print(head + "item(\(_Node._itemString(for: item)), at: \(bucket))") + case .node(let node): + print(head + "node)") + node.dump() + case .collisionNode(let node): + print(head + "collisionNode)") + node.dump() + } + } +} + +extension _Node.Builder { + @inlinable @inline(__always) + internal static func empty(_ level: _Level) -> Self { + Self(level, .empty) + } + + @inlinable @inline(__always) + internal static func item( + _ level: _Level, _ item: __owned Element, at bucket: _Bucket + ) -> Self { + Self(level, .item(item, at: bucket)) + } + + @inlinable @inline(__always) + internal static func node( + _ level: _Level, _ node: __owned _Node + ) -> Self { + assert(!node.isCollisionNode) + return Self(level, .node(node)) + } + + @inlinable @inline(__always) + internal static func collisionNode( + _ level: _Level, _ node: __owned _Node + ) -> Self { + assert(node.isCollisionNode) + return Self(level, .collisionNode(node)) } } extension _Node.Builder { @inlinable internal var count: Int { - switch self { + switch kind { case .empty: return 0 case .item: return 1 - case .node(let node, _): + case .node(let node): + return node.count + case .collisionNode(let node): return node.count } } @inlinable internal var isEmpty: Bool { - guard case .empty = self else { return false } + guard case .empty = kind else { return false } return true } } extension _Node.Builder { @inlinable - internal init(_ level: _Level, _ node: _Node, _ hashPrefix: _Hash) { + internal init(_ level: _Level, _ node: _Node) { + self.level = level if node.count == 0 { - self = .empty + kind = .empty + } else if node.isCollisionNode { + assert(!node.hasSingletonItem) + kind = .collisionNode(node) } else if node.hasSingletonItem { - let item = node.read { $0[item: .zero] } - self = .item(item, hashPrefix) + kind = node.read { .item($0[item: .zero], at: $0.itemMap.first!) } } else { - self = .node(node, hashPrefix) + kind = .node(node) } } @inlinable - internal func finalize(_ level: _Level) -> _Node { - assert(level.isAtRoot) - switch self { + internal __consuming func finalize(_ level: _Level) -> _Node { + assert(level.isAtRoot && self.level.isAtRoot) + switch kind { case .empty: - return ._empty() - case .item(let item, let h): - return ._regularNode(item, h[level]) - case .node(let node, _): + return ._emptyNode() + case .item(let item, let bucket): + return ._regularNode(item, bucket) + case .node(let node): + return node + case .collisionNode(let node): return node } } +} +extension _Node { @inlinable - internal mutating func addNewCollision(_ newItem: Element, _ hash: _Hash) { - switch self { + internal mutating func applyReplacement( + _ level: _Level, + _ replacement: Builder + ) -> Element? { + assert(level == replacement.level) + switch replacement.kind { case .empty: - self = .item(newItem, hash) - case .item(let oldItem, let h): - assert(hash == h) + self = ._emptyNode() + case .node(let n), .collisionNode(let n): + self = n + case .item(let item, let bucket): + guard level.isAtRoot else { + self = ._emptyNode() + return item + } + self = ._regularNode(item, bucket) + } + return nil + } +} + +extension _Node.Builder { + @inlinable + internal mutating func addNewCollision( + _ level: _Level, _ newItem: __owned Element, _ hash: _Hash + ) { + assert(level == self.level) + switch kind { + case .empty: + kind = .item(newItem, at: hash[level]) + case .item(let oldItem, at: let bucket): + assert(hash[level] == bucket) let node = _Node._collisionNode(hash, oldItem, newItem) - self = .node(node, hash) - case .node(var node, let h): - self = .empty + kind = .collisionNode(node) + case .collisionNode(var node): + kind = .empty assert(node.isCollisionNode) - assert(hash == h) assert(hash == node.collisionHash) _ = node.ensureUniqueAndAppendCollision(isUnique: true, newItem) - self = .node(node, h) + kind = .collisionNode(node) + case .node: + fatalError() } } @inlinable internal mutating func addNewItem( - _ level: _Level, _ newItem: Element, _ hashPrefix: _Hash + _ level: _Level, _ newItem: __owned Element, at newBucket: _Bucket ) { - switch self { + assert(level == self.level) + switch kind { case .empty: - self = .item(newItem, hashPrefix) - case .item(let oldItem, let oldHash): - let bucket1 = oldHash[level] - let bucket2 = hashPrefix[level] - assert(bucket1 != bucket2) - assert(oldHash.isEqual(to: hashPrefix, upTo: level)) - let node = _Node._regularNode(oldItem, bucket1, newItem, bucket2) - self = .node(node, hashPrefix) - case .node(var node, let nodeHash): - self = .empty - if node.isCollisionNode { - // Expansion + kind = .item(newItem, at: newBucket) + case .item(let oldItem, let oldBucket): + assert(oldBucket != newBucket) + let node = _Node._regularNode(oldItem, oldBucket, newItem, newBucket) + kind = .node(node) + case .node(var node): + kind = .empty + let isUnique = node.isUnique() + node.ensureUniqueAndInsertItem(isUnique: isUnique, newItem, at: newBucket) + kind = .node(node) + case .collisionNode(var node): + // Expansion + assert(!level.isAtBottom) + self.kind = .empty + node = _Node._regularNode( + newItem, newBucket, node, node.collisionHash[level]) + kind = .node(node) + } + } + + @inlinable + internal mutating func addNewChildNode( + _ level: _Level, _ newChild: __owned _Node, at newBucket: _Bucket + ) { + assert(level == self.level) + switch self.kind { + case .empty: + if newChild.isCollisionNode { + // Compression assert(!level.isAtBottom) - node = _Node._regularNode(node, nodeHash[level]) + self.kind = .collisionNode(newChild) + } else { + self.kind = .node(._regularNode(newChild, newBucket)) } - assert(nodeHash.isEqual(to: hashPrefix, upTo: level)) - let bucket = hashPrefix[level] - node.ensureUniqueAndInsertItem(isUnique: true, newItem, at: bucket) - self = .node(node, nodeHash) + case let .item(oldItem, oldBucket): + let node = _Node._regularNode(oldItem, oldBucket, newChild, newBucket) + self.kind = .node(node) + case .node(var node): + self.kind = .empty + let isUnique = node.isUnique() + node.ensureUnique( + isUnique: isUnique, withFreeSpace: _Node.spaceForNewChild) + node.insertChild(newChild, newBucket) + self.kind = .node(node) + case .collisionNode(var node): + // Expansion + self.kind = .empty + assert(!level.isAtBottom) + node = _Node._regularNode( + node, node.collisionHash[level], newChild, newBucket) + self.kind = .node(node) } } @inlinable internal mutating func addNewChildBranch( - _ level: _Level, _ branch: Self + _ level: _Level, _ newChild: __owned Self, at newBucket: _Bucket ) { - switch (self, branch) { - case (_, .empty): + assert(level == self.level) + assert(newChild.level == self.level.descend()) + switch newChild.kind { + case .empty: break - case (.empty, .item): - self = branch - case (.empty, .node(let child, let childHash)): - if child.isCollisionNode { - // Compression - assert(!level.isAtBottom) - self = branch - } else { - let node = _Node._regularNode(child, childHash[level]) - self = .node(node, childHash) - } - case let (.item(li, lh), .item(ri, rh)): - let node = _Node._regularNode(li, lh[level], ri, rh[level]) - self = .node(node, lh) - case let (.item(item, itemHash), .node(child, childHash)): - assert(itemHash.isEqual(to: childHash, upTo: level)) - let node = _Node._regularNode( - item, itemHash[level], - child, childHash[level]) - self = .node(node, childHash) - case (.node(var node, let nodeHash), .item(let item, let itemHash)): - if node.isCollisionNode { - // Expansion - assert(!level.isAtBottom) - node = _Node._regularNode(node, nodeHash[level]) - } - assert(!node.isCollisionNode) - assert(nodeHash.isEqual(to: itemHash, upTo: level)) - node.ensureUniqueAndInsertItem( - isUnique: true, item, at: itemHash[level]) - self = .node(node, nodeHash) - case (.node(var node, let nodeHash), .node(let child, let childHash)): - if node.isCollisionNode { - // Expansion - assert(!level.isAtBottom) - node = _Node._regularNode(node, nodeHash[level]) - } - assert(nodeHash.isEqual(to: childHash, upTo: level)) - node.ensureUnique(isUnique: true, withFreeSpace: _Node.spaceForNewChild) - node.insertChild(child, childHash[level]) - self = .node(node, nodeHash) + case .item(let newItem, _): + self.addNewItem(level, newItem, at: newBucket) + case .node(let newNode), .collisionNode(let newNode): + self.addNewChildNode(level, newNode, at: newBucket) } } @inlinable internal static func childBranch( - _ level: _Level, _ branch: Self + _ level: _Level, _ child: Self, at bucket: _Bucket ) -> Self { - var result: Self = .empty - result.addNewChildBranch(level, branch) - return result + assert(child.level == level.descend()) + switch child.kind { + case .empty: + return self.empty(level) + case .item(let item, _): + return self.item(level, item, at: bucket) + case .node(let n): + return self.node(level, ._regularNode(n, bucket)) + case .collisionNode(let node): + // Compression + assert(!level.isAtBottom) + return self.collisionNode(level, node) + } } } @@ -186,42 +296,38 @@ extension _Node.Builder { assert(end < source.itemsEndSlot) let h = source.collisionHash for slot: _Slot in stride(from: .zero, to: end, by: 1) { - self.addNewCollision(source[item: slot], h) + self.addNewCollision(self.level, source[item: slot], h) } } @inlinable internal mutating func copyItems( _ level: _Level, - _ hashPrefix: _Hash, from source: _Node.UnsafeHandle, upTo end: _Bucket ) { + assert(level == self.level) assert(isEmpty) assert(!source.isCollisionNode) for (b, s) in source.itemMap.intersection(_Bitmap(upTo: end)) { - let h = hashPrefix.appending(b, at: level) - self.addNewItem(level, source[item: s], h) + self.addNewItem(level, source[item: s], at: b) } } @inlinable internal mutating func copyItemsAndChildren( _ level: _Level, - _ hashPrefix: _Hash, from source: _Node.UnsafeHandle, upTo end: _Bucket ) { + assert(level == self.level) assert(isEmpty) assert(!source.isCollisionNode) for (b, s) in source.itemMap { - let h = hashPrefix.appending(b, at: level) - self.addNewItem(level, source[item: s], h) + self.addNewItem(level, source[item: s], at: b) } for (b, s) in source.childMap.intersection(_Bitmap(upTo: end)) { - let h = hashPrefix.appending(b, at: level) - self.addNewChildBranch(level, .node(source[child: s], h)) + self.addNewChildNode(level, source[child: s], at: b) } } - } diff --git a/Sources/PersistentCollections/Node/_Node+CustomStringConvertible.swift b/Sources/PersistentCollections/Node/_Node+CustomStringConvertible.swift deleted file mode 100644 index 36a62d27..00000000 --- a/Sources/PersistentCollections/Node/_Node+CustomStringConvertible.swift +++ /dev/null @@ -1,42 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift Collections open source project -// -// Copyright (c) 2022 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 -// -//===----------------------------------------------------------------------===// - -extension _Node: CustomStringConvertible { - @usableFromInline - internal var description: String { - guard count > 0 else { - return "[:]" - } - - var result = "[" - var first = true - read { - for (key, value) in $0.reverseItems.reversed() { - if first { - first = false - } else { - result += ", " - } - result += "\(key): \(value)" - } - for child in $0.children { - if first { - first = false - } else { - result += ", " - } - result += "\(child.description)" - } - } - result += "]" - return result - } -} diff --git a/Sources/PersistentCollections/Node/_Node+Debugging.swift b/Sources/PersistentCollections/Node/_Node+Debugging.swift index 3b0dd1c7..094a2476 100644 --- a/Sources/PersistentCollections/Node/_Node+Debugging.swift +++ b/Sources/PersistentCollections/Node/_Node+Debugging.swift @@ -39,11 +39,16 @@ extension _Node.Storage { } } +extension _Node { + internal static func _itemString(for item: Element) -> String { + let hash = _Hash(item.key).description + return "hash: \(hash), key: \(item.key), value: \(item.value)" + } +} extension _Node.UnsafeHandle { internal func _itemString(at slot: _Slot) -> String { let item = self[item: slot] - let hash = _Hash(item.key).description - return "hash: \(hash), key: \(item.key), value: \(item.value)" + return _Node._itemString(for: item) } @usableFromInline diff --git a/Sources/PersistentCollections/Node/_Node+Initializers.swift b/Sources/PersistentCollections/Node/_Node+Initializers.swift index 1de96ee5..1620de96 100644 --- a/Sources/PersistentCollections/Node/_Node+Initializers.swift +++ b/Sources/PersistentCollections/Node/_Node+Initializers.swift @@ -11,7 +11,7 @@ extension _Node { @inlinable @inline(__always) - internal static func _empty() -> _Node { + internal static func _emptyNode() -> _Node { _Node(storage: _emptySingleton, count: 0) } @@ -98,7 +98,8 @@ extension _Node { @inlinable internal static func _regularNode( - _ child: __owned _Node, _ bucket: _Bucket + _ child: __owned _Node, + _ bucket: _Bucket ) -> _Node { let r = _Node.allocate( itemMap: .empty, diff --git a/Sources/PersistentCollections/Node/_Node+Invariants.swift b/Sources/PersistentCollections/Node/_Node+Invariants.swift index af02f666..570df8cc 100644 --- a/Sources/PersistentCollections/Node/_Node+Invariants.swift +++ b/Sources/PersistentCollections/Node/_Node+Invariants.swift @@ -56,9 +56,14 @@ extension _Node { internal func _invariantCheck() {} #endif + @inlinable @inline(__always) + public func _fullInvariantCheck() { + self._fullInvariantCheck(.top, .emptyPath) + } + #if COLLECTIONS_INTERNAL_CHECKS @inlinable @inline(never) - public func _fullInvariantCheck(_ level: _Level, _ path: _Hash) { + internal func _fullInvariantCheck(_ level: _Level, _ path: _Hash) { _invariantCheck() read { precondition(level.isAtRoot || !hasSingletonItem) @@ -96,7 +101,7 @@ extension _Node { } #else @inlinable @inline(__always) - public func _fullInvariantCheck(_ level: _Level, _ path: _Hash) {} + internal func _fullInvariantCheck(_ level: _Level, _ path: _Hash) {} #endif } diff --git a/Sources/PersistentCollections/Node/_Node+Primitive Removals.swift b/Sources/PersistentCollections/Node/_Node+Primitive Removals.swift index 050805cf..9c5d2281 100644 --- a/Sources/PersistentCollections/Node/_Node+Primitive Removals.swift +++ b/Sources/PersistentCollections/Node/_Node+Primitive Removals.swift @@ -67,14 +67,14 @@ extension _Node { at bucket: _Bucket ) -> Element { let slot = read { $0.itemMap.slot(of: bucket) } - return removeItem(at: slot, bucket, by: { $0.move() }) + return removeItem(at: bucket, slot, by: { $0.move() }) } @inlinable internal mutating func removeItem( - at slot: _Slot, _ bucket: _Bucket + at bucket: _Bucket, _ slot: _Slot ) -> Element { - removeItem(at: slot, bucket, by: { $0.move() }) + removeItem(at: bucket, slot, by: { $0.move() }) } /// Remove the item at `slot`, increasing the amount of free @@ -84,7 +84,7 @@ extension _Node { /// storage slot corresponding to the item to be removed. @inlinable internal mutating func removeItem( - at slot: _Slot, _ bucket: _Bucket, + at bucket: _Bucket, _ slot: _Slot, by remover: (UnsafeMutablePointer) -> R ) -> R { defer { _invariantCheck() } @@ -106,9 +106,8 @@ extension _Node { @inlinable internal mutating func removeChild( - at slot: _Slot, _ bucket: _Bucket + at bucket: _Bucket, _ slot: _Slot ) -> _Node { - defer { _invariantCheck() } assert(!isCollisionNode) let child: _Node = update { assert($0.childMap.contains(bucket)) diff --git a/Sources/PersistentCollections/Node/_Node+Primitive Replacement.swift b/Sources/PersistentCollections/Node/_Node+Primitive Replacement.swift index 2d013915..a687a3ce 100644 --- a/Sources/PersistentCollections/Node/_Node+Primitive Replacement.swift +++ b/Sources/PersistentCollections/Node/_Node+Primitive Replacement.swift @@ -12,7 +12,7 @@ extension _Node { @inlinable internal mutating func replaceItem( - at bucket: _Bucket, _ slot: _Slot, with item: Element + at bucket: _Bucket, _ slot: _Slot, with item: __owned Element ) { update { assert($0.isCollisionNode || $0.itemMap.contains(bucket)) @@ -24,7 +24,7 @@ extension _Node { @inlinable internal mutating func replaceChild( - at bucket: _Bucket, with child: _Node + at bucket: _Bucket, with child: __owned _Node ) -> Int { let slot = read { $0.childMap.slot(of: bucket) } return replaceChild(at: bucket, slot, with: child) @@ -32,7 +32,7 @@ extension _Node { @inlinable internal mutating func replaceChild( - at bucket: _Bucket, _ slot: _Slot, with child: _Node + at bucket: _Bucket, _ slot: _Slot, with child: __owned _Node ) -> Int { let delta: Int = update { assert(!$0.isCollisionNode) @@ -50,41 +50,41 @@ extension _Node { @inlinable internal func replacingChild( _ level: _Level, - _ hashPrefix: _Hash, + at bucket: _Bucket, _ slot: _Slot, with child: __owned Builder ) -> Builder { - let bucket = hashPrefix[level] + assert(child.level == level.descend()) read { assert(!$0.isCollisionNode) assert($0.childMap.contains(bucket)) assert(slot == $0.childMap.slot(of: bucket)) } - switch child { + switch child.kind { case .empty: - return _removingChild(level, hashPrefix, bucket, slot) - case let .item(item, hash): - assert(hash.isEqual(to: hashPrefix, upTo: level)) - assert(hash[level] == bucket) + return _removingChild(level, at: bucket, slot) + case let .item(item, _): if hasSingletonChild { - return child + return .item(level, item, at: bucket) } var node = self.copy(withFreeSpace: _Node.spaceForInlinedChild) - _ = node.removeChild(at: slot, bucket) + _ = node.removeChild(at: bucket, slot) node.insertItem(item, at: bucket) node._invariantCheck() - return .node(node, hashPrefix) - case let .node(node, hash): - assert(hash.isEqual(to: hashPrefix, upTo: level)) - assert(hash[level] == bucket) - if node.isCollisionNode, self.hasSingletonChild { + return .node(level, node) + case let .node(node): + var copy = self.copy() + _ = copy.replaceChild(at: bucket, slot, with: node) + return .node(level, copy) + case let .collisionNode(node): + if hasSingletonChild { // Compression assert(!level.isAtBottom) - return child + return .collisionNode(level, node) } var copy = self.copy() _ = copy.replaceChild(at: bucket, slot, with: node) - return .node(copy, hashPrefix) + return .node(level, copy) } } } diff --git a/Sources/PersistentCollections/Node/_Node+Structural compactMapValues.swift b/Sources/PersistentCollections/Node/_Node+Structural compactMapValues.swift index 1cd0e6d3..a52b4384 100644 --- a/Sources/PersistentCollections/Node/_Node+Structural compactMapValues.swift +++ b/Sources/PersistentCollections/Node/_Node+Structural compactMapValues.swift @@ -13,17 +13,16 @@ extension _Node { @inlinable internal func compactMapValues( _ level: _Level, - _ hashPrefix: _Hash, _ transform: (Value) throws -> T? ) rethrows -> _Node.Builder { return try self.read { - var result: _Node.Builder = .empty + var result: _Node.Builder = .empty(level) if isCollisionNode { let items = $0.reverseItems for i in items.indices { if let v = try transform(items[i].value) { - result.addNewCollision((items[i].key, v), $0.collisionHash) + result.addNewCollision(level, (items[i].key, v), $0.collisionHash) } } return result @@ -32,16 +31,14 @@ extension _Node { for (bucket, slot) in $0.itemMap { let p = $0.itemPtr(at: slot) if let v = try transform(p.pointee.value) { - let h = hashPrefix.appending(bucket, at: level) - result.addNewItem(level, (p.pointee.key, v), h) + result.addNewItem(level, (p.pointee.key, v), at: bucket) } } for (bucket, slot) in $0.childMap { - let h = hashPrefix.appending(bucket, at: level) - let branch = try $0[child: slot].compactMapValues( - level.descend(), h, transform) - result.addNewChildBranch(level, branch) + let branch = try $0[child: slot] + .compactMapValues(level.descend(), transform) + result.addNewChildBranch(level, branch, at: bucket) } return result } diff --git a/Sources/PersistentCollections/Node/_Node+Structural filter.swift b/Sources/PersistentCollections/Node/_Node+Structural filter.swift index 2931d9df..93cc75c9 100644 --- a/Sources/PersistentCollections/Node/_Node+Structural filter.swift +++ b/Sources/PersistentCollections/Node/_Node+Structural filter.swift @@ -13,14 +13,13 @@ extension _Node { @inlinable internal func filter( _ level: _Level, - _ hashPrefix: _Hash, _ isIncluded: (Element) throws -> Bool ) rethrows -> Builder? { guard !isCollisionNode else { - return try _filter_slow(isIncluded) + return try _filter_slow(level, isIncluded) } return try self.read { - var result: Builder = .empty + var result: Builder = .empty(level) var removing = false // true if we need to remove something for (bucket, slot) in $0.itemMap { @@ -28,29 +27,26 @@ extension _Node { let include = try isIncluded(p.pointee) switch (include, removing) { case (true, true): - let h = hashPrefix.appending(bucket, at: level) - result.addNewItem(level, p.pointee, h) + result.addNewItem(level, p.pointee, at: bucket) case (false, false): removing = true - result.copyItems(level, hashPrefix, from: $0, upTo: bucket) + result.copyItems(level, from: $0, upTo: bucket) default: break } } for (bucket, slot) in $0.childMap { - let h = hashPrefix.appending(bucket, at: level) - let branch = try $0[child: slot].filter(level.descend(), h, isIncluded) + let branch = try $0[child: slot].filter(level.descend(), isIncluded) if let branch = branch { assert(branch.count < self.count) if !removing { removing = true - result.copyItemsAndChildren( - level, hashPrefix, from: $0, upTo: bucket) + result.copyItemsAndChildren(level, from: $0, upTo: bucket) } - result.addNewChildBranch(level, branch) + result.addNewChildBranch(level, branch, at: bucket) } else if removing { - result.addNewChildBranch(level, .node($0[child: slot], h)) + result.addNewChildNode(level, $0[child: slot], at: bucket) } } @@ -61,17 +57,18 @@ extension _Node { @inlinable @inline(never) internal func _filter_slow( + _ level: _Level, _ isIncluded: (Element) throws -> Bool ) rethrows -> Builder? { try self.read { - var result: Builder = .empty + var result: Builder = .empty(level) var removing = false for slot: _Slot in stride(from: .zero, to: $0.itemsEndSlot, by: 1) { let p = $0.itemPtr(at: slot) let include = try isIncluded(p.pointee) if include, removing { - result.addNewCollision(p.pointee, $0.collisionHash) + result.addNewCollision(level, p.pointee, $0.collisionHash) } else if !include, !removing { removing = true diff --git a/Sources/PersistentCollections/Node/_Node+Structural intersection.swift b/Sources/PersistentCollections/Node/_Node+Structural intersection.swift index ed7d0c77..4fbebcbc 100644 --- a/Sources/PersistentCollections/Node/_Node+Structural intersection.swift +++ b/Sources/PersistentCollections/Node/_Node+Structural intersection.swift @@ -13,18 +13,17 @@ extension _Node { @inlinable internal func intersection( _ level: _Level, - _ hashPrefix: _Hash, _ other: _Node ) -> Builder? { if self.raw.storage === other.raw.storage { return nil } if self.isCollisionNode || other.isCollisionNode { - return _intersection_slow(level, hashPrefix, other) + return _intersection_slow(level, other) } return self.read { l in other.read { r in - var result: Builder = .empty + var result: Builder = .empty(level) var removing = false for (bucket, lslot) in l.itemMap { @@ -43,12 +42,11 @@ extension _Node { else { include = false} if include, removing { - let hashPrefix = hashPrefix.appending(bucket, at: level) - result.addNewItem(level, lp.pointee, hashPrefix) + result.addNewItem(level, lp.pointee, at: bucket) } else if !include, !removing { removing = true - result.copyItems(level, hashPrefix, from: l, upTo: bucket) + result.copyItems(level, from: l, upTo: bucket) } } @@ -56,43 +54,35 @@ extension _Node { if r.itemMap.contains(bucket) { if !removing { removing = true - result.copyItemsAndChildren( - level, hashPrefix, from: l, upTo: bucket) + result.copyItemsAndChildren(level, from: l, upTo: bucket) } let rslot = r.itemMap.slot(of: bucket) let rp = r.itemPtr(at: rslot) let h = _Hash(rp.pointee.key) let res = l[child: lslot].lookup(level.descend(), rp.pointee.key, h) if let res = res { - UnsafeHandle.read(res.node) { - let p = $0.itemPtr(at: res.slot) - result.addNewItem(level, p.pointee, h) - } + let item = UnsafeHandle.read(res.node) { $0[item: res.slot] } + result.addNewItem(level, item, at: bucket) } } else if r.childMap.contains(bucket) { let rslot = r.childMap.slot(of: bucket) - let branch = l[child: lslot].intersection( - level.descend(), - hashPrefix.appending(bucket, at: level), - r[child: rslot]) + let branch = l[child: lslot] + .intersection(level.descend(), r[child: rslot]) if let branch = branch { assert(branch.count < self.count) if !removing { removing = true - result.copyItemsAndChildren( - level, hashPrefix, from: l, upTo: bucket) + result.copyItemsAndChildren(level, from: l, upTo: bucket) } - result.addNewChildBranch(level, branch) + result.addNewChildBranch(level, branch, at: bucket) } else if removing { - let h = hashPrefix.appending(bucket, at: level) - result.addNewChildBranch(level, .node(l[child: lslot], h)) + result.addNewChildNode(level, l[child: lslot], at: bucket) } } else if !removing { removing = true - result.copyItemsAndChildren( - level, hashPrefix, from: l, upTo: bucket) + result.copyItemsAndChildren(level, from: l, upTo: bucket) } } guard removing else { return nil } @@ -104,7 +94,6 @@ extension _Node { @inlinable @inline(never) internal func _intersection_slow( _ level: _Level, - _ hashPrefix: _Hash, _ other: _Node ) -> Builder? { let lc = self.isCollisionNode @@ -112,16 +101,16 @@ extension _Node { if lc && rc { return read { l in other.read { r in - guard l.collisionHash == r.collisionHash else { return .empty } - var result: Builder = .empty - var removing = false + var result: Builder = .empty(level) + guard l.collisionHash == r.collisionHash else { return result } + var removing = false let ritems = r.reverseItems for lslot: _Slot in stride(from: .zero, to: l.itemsEndSlot, by: 1) { let lp = l.itemPtr(at: lslot) let include = ritems.contains { $0.key == lp.pointee.key } if include, removing { - result.addNewCollision(lp.pointee, l.collisionHash) + result.addNewCollision(level, lp.pointee, l.collisionHash) } else if !include, !removing { removing = true @@ -149,17 +138,15 @@ extension _Node { let ritem = r.itemPtr(at: rslot) let litems = l.reverseItems let i = litems.firstIndex { $0.key == ritem.pointee.key } - guard let i = i else { return .empty } - return .item(litems[i], l.collisionHash) + guard let i = i else { return .empty(level) } + return .item(level, litems[i], at: l.collisionHash[level]) } if r.childMap.contains(bucket) { let rslot = r.childMap.slot(of: bucket) - return intersection( - level.descend(), - hashPrefix.appending(bucket, at: level), - r[child: rslot]) + return intersection(level.descend(), r[child: rslot]) + .map { .childBranch(level, $0, at: bucket) } } - return .empty + return .empty(level) } } } @@ -174,24 +161,21 @@ extension _Node { let litem = l.itemPtr(at: lslot) let ritems = r.reverseItems let found = ritems.contains { $0.key == litem.pointee.key } - guard found else { return .empty } - return .item(litem.pointee, r.collisionHash) + guard found else { return .empty(level) } + return .item(level, litem.pointee, at: bucket) } if l.childMap.contains(bucket) { let lslot = l.childMap.slot(of: bucket) - let branch = l[child: lslot].intersection( - level.descend(), - hashPrefix.appending(bucket, at: level), - other) + let branch = l[child: lslot].intersection(level.descend(), other) guard let branch = branch else { assert(l[child: lslot].isCollisionNode) assert(l[child: lslot].collisionHash == r.collisionHash) // Compression - return .node(l[child: lslot], r.collisionHash) + return .collisionNode(level, l[child: lslot]) } - return .childBranch(level, branch) + return .childBranch(level, branch, at: bucket) } - return .empty + return .empty(level) } } } diff --git a/Sources/PersistentCollections/Node/_Node+Structural merge.swift b/Sources/PersistentCollections/Node/_Node+Structural merge.swift index ab121628..08a36e60 100644 --- a/Sources/PersistentCollections/Node/_Node+Structural merge.swift +++ b/Sources/PersistentCollections/Node/_Node+Structural merge.swift @@ -13,7 +13,6 @@ extension _Node { @inlinable internal mutating func merge( _ level: _Level, - _ hashPrefix: _Hash, _ other: _Node, _ combine: (Value, Value) throws -> Value ) rethrows { @@ -45,13 +44,12 @@ extension _Node { return } - try _merge(level, hashPrefix, other, combine) + try _merge(level, other, combine) } @inlinable internal mutating func _merge( _ level: _Level, - _ hashPrefix: _Hash, _ other: _Node, _ combine: (Value, Value) throws -> Value ) rethrows { @@ -59,7 +57,7 @@ extension _Node { // of identical nodes. if self.isCollisionNode || other.isCollisionNode { - try _merge_slow(level, hashPrefix, other, combine) + try _merge_slow(level, other, combine) return } @@ -154,7 +152,6 @@ extension _Node { try self.update { l in try l[child: lslot].merge( level.descend(), - hashPrefix.appending(bucket, at: level), r[child: rslot], combine) } @@ -187,7 +184,6 @@ extension _Node { @inlinable @inline(never) internal mutating func _merge_slow( _ level: _Level, - _ hashPrefix: _Hash, _ other: _Node, _ combine: (Value, Value) throws -> Value ) rethrows { @@ -260,8 +256,7 @@ extension _Node { if r.childMap.contains(bucket) { let rslot = r.childMap.slot(of: bucket) - let h = hashPrefix.appending(bucket, at: level) - try self._merge(level.descend(), h, r[child: rslot], combine) + try self._merge(level.descend(), r[child: rslot], combine) var node = other.copy() _ = node.replaceChild(at: bucket, rslot, with: self) self = node @@ -303,10 +298,9 @@ extension _Node { self.ensureUnique(isUnique: isUnique) let delta: Int = try self.update { l in let lslot = l.childMap.slot(of: bucket) - let h = hashPrefix.appending(bucket, at: level) let lchild = l.childPtr(at: lslot) let origCount = lchild.pointee.count - try lchild.pointee._merge(level.descend(), h, other, combine) + try lchild.pointee._merge(level.descend(), other, combine) return lchild.pointee.count &- origCount } assert(delta >= 0) diff --git a/Sources/PersistentCollections/Node/_Node+Structural subtracting.swift b/Sources/PersistentCollections/Node/_Node+Structural subtracting.swift index b49dd23c..498447d0 100644 --- a/Sources/PersistentCollections/Node/_Node+Structural subtracting.swift +++ b/Sources/PersistentCollections/Node/_Node+Structural subtracting.swift @@ -13,18 +13,17 @@ extension _Node { @inlinable internal func subtracting( _ level: _Level, - _ hashPrefix: _Hash, _ other: _Node ) -> Builder? { - if self.raw.storage === other.raw.storage { return .empty } + if self.raw.storage === other.raw.storage { return .empty(level) } if self.isCollisionNode || other.isCollisionNode { - return _subtracting_slow(level, hashPrefix, other) + return _subtracting_slow(level, other) } return self.read { l in other.read { r in - var result: Builder = .empty + var result: Builder = .empty(level) var removing = false for (bucket, lslot) in l.itemMap { @@ -45,59 +44,48 @@ extension _Node { } if include, removing { - let h = hashPrefix.appending(bucket, at: level) - result.addNewItem(level, lp.pointee, h) + result.addNewItem(level, lp.pointee, at: bucket) } else if !include, !removing { removing = true - result.copyItems(level, hashPrefix, from: l, upTo: bucket) + result.copyItems(level, from: l, upTo: bucket) } } for (bucket, lslot) in l.childMap { + var done = false if r.itemMap.contains(bucket) { let rslot = r.itemMap.slot(of: bucket) let rp = r.itemPtr(at: rslot) let h = _Hash(rp.pointee.key) let child = l[child: lslot] - .removing2(level.descend(), rp.pointee.key, h)?.replacement + .removing(level.descend(), rp.pointee.key, h)?.replacement if let child = child { assert(child.count < self.count) if !removing { removing = true - result.copyItemsAndChildren( - level, hashPrefix, from: l, upTo: bucket) + result.copyItemsAndChildren(level, from: l, upTo: bucket) } - result.addNewChildBranch(level, child) - } - else if removing { - let h = hashPrefix.appending(bucket, at: level) - result.addNewChildBranch(level, .node(l[child: lslot], h)) + result.addNewChildBranch(level, child, at: bucket) + done = true } } else if r.childMap.contains(bucket) { let rslot = r.childMap.slot(of: bucket) - let child = l[child: lslot].subtracting( - level.descend(), - hashPrefix.appending(bucket, at: level), - r[child: rslot]) + let child = l[child: lslot] + .subtracting(level.descend(), r[child: rslot]) if let child = child { assert(child.count < self.count) if !removing { removing = true - result.copyItemsAndChildren( - level, hashPrefix, from: l, upTo: bucket) + result.copyItemsAndChildren(level, from: l, upTo: bucket) } - result.addNewChildBranch(level, child) - } - else if removing { - let h = hashPrefix.appending(bucket, at: level) - result.addNewChildBranch(level, .node(l[child: lslot], h)) + result.addNewChildBranch(level, child, at: bucket) + done = true } } - else if removing { - let h = hashPrefix.appending(bucket, at: level) - result.addNewChildBranch(level, .node(l[child: lslot], h)) + if !done, removing { + result.addNewChildNode(level, l[child: lslot], at: bucket) } } guard removing else { return nil } @@ -109,7 +97,6 @@ extension _Node { @inlinable @inline(never) internal func _subtracting_slow( _ level: _Level, - _ hashPrefix: _Hash, _ other: _Node ) -> Builder? { let lc = self.isCollisionNode @@ -120,7 +107,7 @@ extension _Node { guard l.collisionHash == r.collisionHash else { return nil } - var result: Builder = .empty + var result: Builder = .empty(level) var removing = false let ritems = r.reverseItems @@ -128,7 +115,7 @@ extension _Node { let lp = l.itemPtr(at: lslot) let include = !ritems.contains { $0.key == lp.pointee.key } if include, removing { - result.addNewCollision(lp.pointee, l.collisionHash) + result.addNewCollision(level, lp.pointee, l.collisionHash) } else if !include, !removing { removing = true @@ -157,14 +144,13 @@ extension _Node { let h = _Hash(ritem.pointee.key) let res = l.find(level, ritem.pointee.key, h) guard let res = res else { return nil } - return self._removingItemFromLeaf( - level, hashPrefix.appending(bucket, at: level), res.slot - ).replacement + return self._removingItemFromLeaf(level, at: bucket, res.slot) + .replacement } else if r.childMap.contains(bucket) { let rslot = r.childMap.slot(of: bucket) - let h = hashPrefix.appending(bucket, at: level) - return self.subtracting(level.descend(), h, r[child: rslot]) + return subtracting(level.descend(), r[child: rslot]) + .map { .childBranch(level, $0, at: bucket) } } return nil } @@ -182,19 +168,15 @@ extension _Node { let h = _Hash(litem.pointee.key) let res = r.find(level, litem.pointee.key, h) if res == nil { return nil } - return self._removingItemFromLeaf( - level, hashPrefix.appending(bucket, at: level), lslot - ).replacement + return self._removingItemFromLeaf(level, at: bucket, lslot) + .replacement } if l.childMap.contains(bucket) { let lslot = l.childMap.slot(of: bucket) - let branch = l[child: lslot].subtracting( - level.descend(), - hashPrefix.appending(bucket, at: level), - other) + let branch = l[child: lslot].subtracting(level.descend(), other) guard let branch = branch else { return nil } - var result = self._removingChild(level, hashPrefix, bucket, lslot) - result.addNewChildBranch(level, branch) + var result = self._removingChild(level, at: bucket, lslot) + result.addNewChildBranch(level, branch, at: bucket) return result } return nil diff --git a/Sources/PersistentCollections/Node/_Node+Structural symmetricDifference.swift b/Sources/PersistentCollections/Node/_Node+Structural symmetricDifference.swift index 89c8ad89..a37d1ed2 100644 --- a/Sources/PersistentCollections/Node/_Node+Structural symmetricDifference.swift +++ b/Sources/PersistentCollections/Node/_Node+Structural symmetricDifference.swift @@ -13,32 +13,30 @@ extension _Node { @inlinable internal func symmetricDifference( _ level: _Level, - _ hashPrefix: _Hash, _ other: _Node ) -> Builder? { - guard self.count > 0 else { return .node(other, hashPrefix) } + guard self.count > 0 else { return Builder(level, other) } guard other.count > 0 else { return nil } - return _symmetricDifference(level, hashPrefix, other) + return _symmetricDifference(level, other) } @inlinable internal func _symmetricDifference( _ level: _Level, - _ hashPrefix: _Hash, _ other: _Node ) -> Builder { assert(self.count > 0 && other.count > 0) if self.raw.storage === other.raw.storage { - return .empty + return .empty(level) } if self.isCollisionNode || other.isCollisionNode { - return _symmetricDifference_slow(level, hashPrefix, other) + return _symmetricDifference_slow(level, other) } return self.read { l in other.read { r in - var result: Builder = .empty + var result: Builder = .empty(level) for (bucket, lslot) in l.itemMap { let lp = l.itemPtr(at: lslot) @@ -52,7 +50,7 @@ extension _Node { level: level.descend(), item1: lp.pointee, h1, item2: { $0.initialize(to: rp.pointee) }, h2) - result.addNewChildBranch(level, .node(child.top, h1)) + result.addNewChildNode(level, child.top, at: bucket) } } else if r.childMap.contains(bucket) { @@ -60,19 +58,18 @@ extension _Node { let rp = r.childPtr(at: rslot) let h = _Hash(lp.pointee.key) let child = rp.pointee - .removing2(level.descend(), lp.pointee.key, h)?.replacement + .removing(level.descend(), lp.pointee.key, h)?.replacement if let child = child { - result.addNewChildBranch(level, child) + result.addNewChildBranch(level, child, at: bucket) } else { let child2 = rp.pointee.inserting(level.descend(), lp.pointee, h) assert(child2.inserted) - result.addNewChildBranch(level, .node(child2.node, h)) + result.addNewChildNode(level, child2.node, at: bucket) } } else { - let h = hashPrefix.appending(bucket, at: level) - result.addNewItem(level, lp.pointee, h) + result.addNewItem(level, lp.pointee, at: bucket) } } @@ -83,39 +80,35 @@ extension _Node { let rp = r.itemPtr(at: rslot) let h = _Hash(rp.pointee.key) let child = lp.pointee - .removing2(level.descend(), rp.pointee.key, h)?.replacement + .removing(level.descend(), rp.pointee.key, h)?.replacement if let child = child { - result.addNewChildBranch(level, child) + result.addNewChildBranch(level, child, at: bucket) } else { let child2 = lp.pointee.inserting(level.descend(), rp.pointee, h) assert(child2.inserted) - result.addNewChildBranch(level, .node(child2.node, h)) + result.addNewChildNode(level, child2.node, at: bucket) } } else if r.childMap.contains(bucket) { let rslot = r.childMap.slot(of: bucket) - let hp = hashPrefix.appending(bucket, at: level) let b = l[child: lslot]._symmetricDifference( - level.descend(), hp, r[child: rslot]) - result.addNewChildBranch(level, b) + level.descend(), r[child: rslot]) + result.addNewChildBranch(level, b, at: bucket) } else { - let h = hashPrefix.appending(bucket, at: level) - result.addNewChildBranch(level, .node(lp.pointee, h)) + result.addNewChildNode(level, lp.pointee, at: bucket) } } let seen = l.itemMap.union(l.childMap) for (bucket, rslot) in r.itemMap { guard !seen.contains(bucket) else { continue } - let h = hashPrefix.appending(bucket, at: level) - result.addNewItem(level, r[item: rslot], h) + result.addNewItem(level, r[item: rslot], at: bucket) } for (bucket, rslot) in r.childMap { guard !seen.contains(bucket) else { continue } - let h = hashPrefix.appending(bucket, at: level) - result.addNewChildBranch(level, .node(r[child: rslot], h)) + result.addNewChildNode(level, r[child: rslot], at: bucket) } return result } @@ -125,23 +118,21 @@ extension _Node { @inlinable @inline(never) internal func _symmetricDifference_slow( _ level: _Level, - _ hashPrefix: _Hash, _ other: _Node ) -> Builder { switch (self.isCollisionNode, other.isCollisionNode) { case (true, true): - return self._symmetricDifference_slow_both(level, hashPrefix, other) + return self._symmetricDifference_slow_both(level, other) case (true, false): - return self._symmetricDifference_slow_left(level, hashPrefix, other) + return self._symmetricDifference_slow_left(level, other) case (false, _): - return other._symmetricDifference_slow_left(level, hashPrefix, self) + return other._symmetricDifference_slow_left(level, self) } } @inlinable internal func _symmetricDifference_slow_both( _ level: _Level, - _ hashPrefix: _Hash, _ other: _Node ) -> Builder { read { l in @@ -151,15 +142,15 @@ extension _Node { level: level, child1: self, l.collisionHash, child2: other, r.collisionHash) - return .node(node, l.collisionHash) + return .node(level, node) } - var result: Builder = .empty + var result: Builder = .empty(level) let ritems = r.reverseItems for ls: _Slot in stride(from: .zero, to: l.itemsEndSlot, by: 1) { let lp = l.itemPtr(at: ls) let include = !ritems.contains(where: { $0.key == lp.pointee.key }) if include { - result.addNewCollision(lp.pointee, l.collisionHash) + result.addNewCollision(level, lp.pointee, l.collisionHash) } } // FIXME: Consider remembering slots of shared items in r by @@ -169,7 +160,7 @@ extension _Node { let rp = r.itemPtr(at: rs) let include = !litems.contains(where: { $0.key == rp.pointee.key }) if include { - result.addNewCollision(rp.pointee, r.collisionHash) + result.addNewCollision(level, rp.pointee, r.collisionHash) } } return result @@ -180,7 +171,6 @@ extension _Node { @inlinable internal func _symmetricDifference_slow_left( _ level: _Level, - _ hashPrefix: _Hash, _ other: _Node ) -> Builder { // `self` is a collision node on a compressed path. The other tree might @@ -192,40 +182,60 @@ extension _Node { if r.itemMap.contains(bucket) { let rslot = r.itemMap.slot(of: bucket) let rp = r.itemPtr(at: rslot) + let rh = _Hash(rp.pointee.key) + guard rh == l.collisionHash else { + var copy = other.copy(withFreeSpace: _Node.spaceForSpawningChild) + let item = copy.removeItem(at: bucket, rslot) + let child = _Node.build( + level: level.descend(), + item1: { $0.initialize(to: item) }, rh, + child2: self, l.collisionHash) + copy.insertChild(child.top, bucket) + return .node(level, copy) + } let litems = l.reverseItems if let li = litems.firstIndex(where: { $0.key == rp.pointee.key }) { if l.itemCount == 2 { var node = other.copy() node.replaceItem(at: bucket, rslot, with: litems[1 &- li]) - return .node(node, l.collisionHash) + return .node(level, node) } let lslot = _Slot(litems.count &- 1 &- li) var child = self.copy() - _ = child.removeItem(at: lslot, .invalid) + _ = child.removeItem(at: .invalid, lslot) + if other.hasSingletonItem { + // Compression + return .collisionNode(level, child) + } var node = other.copy(withFreeSpace: _Node.spaceForSpawningChild) - _ = node.removeItem(at: rslot, bucket) + _ = node.removeItem(at: bucket, rslot) node.insertChild(child, bucket) - return .node(node, hashPrefix) + return .node(level, node) + } + if other.hasSingletonItem { + // Compression + let copy = self.copyNodeAndAppendCollision { + $0.initialize(to: r[item: .zero]) + } + return .collisionNode(level, copy.node) } var node = other.copy(withFreeSpace: _Node.spaceForSpawningChild) - let item = node.removeItem(at: rslot, bucket) + let item = node.removeItem(at: bucket, rslot) let child = self.copyNodeAndAppendCollision { $0.initialize(to: item) } node.insertChild(child.node, bucket) - return .node(node, hashPrefix) + return .node(level, node) } if r.childMap.contains(bucket) { let rslot = r.childMap.slot(of: bucket) let rp = r.childPtr(at: rslot) - let hp = hashPrefix.appending(bucket, at: level) - let child = rp.pointee._symmetricDifference( - level.descend(), hp, self) - return other.replacingChild(level, hp, rslot, with: child) + let child = rp.pointee._symmetricDifference(level.descend(), self) + return other.replacingChild(level, at: bucket, rslot, with: child) } var node = other.copy(withFreeSpace: _Node.spaceForNewChild) node.insertChild(self, bucket) - return .node(node, hashPrefix) + return .node(level, node) } } } diff --git a/Sources/PersistentCollections/Node/_Node+Structural union.swift b/Sources/PersistentCollections/Node/_Node+Structural union.swift index 01b0de64..a504505e 100644 --- a/Sources/PersistentCollections/Node/_Node+Structural union.swift +++ b/Sources/PersistentCollections/Node/_Node+Structural union.swift @@ -13,7 +13,6 @@ extension _Node { @inlinable internal func union( _ level: _Level, - _ hashPrefix: _Hash, _ other: _Node ) -> (copied: Bool, node: _Node) { guard self.count > 0 else { return (true, other) } @@ -38,13 +37,12 @@ extension _Node { return (true, copy) } } - return _union(level, hashPrefix, other) + return _union(level, other) } @inlinable internal func _union( _ level: _Level, - _ hashPrefix: _Hash, _ other: _Node ) -> (copied: Bool, node: _Node) { if self.raw.storage === other.raw.storage { @@ -52,7 +50,7 @@ extension _Node { } if self.isCollisionNode || other.isCollisionNode { - return _union_slow(level, hashPrefix, other) + return _union_slow(level, other) } return self.read { l in @@ -116,10 +114,7 @@ extension _Node { } else if r.childMap.contains(bucket) { let rslot = r.childMap.slot(of: bucket) - let child = l[child: lslot]._union( - level.descend(), - hashPrefix.appending(bucket, at: level), - r[child: rslot]) + let child = l[child: lslot]._union(level.descend(), r[child: rslot]) guard child.copied else { // Nothing to do continue @@ -158,7 +153,6 @@ extension _Node { @inlinable @inline(never) internal func _union_slow( _ level: _Level, - _ hashPrefix: _Hash, _ other: _Node ) -> (copied: Bool, node: _Node) { let lc = self.isCollisionNode @@ -208,17 +202,13 @@ extension _Node { return (false, self) } let node = other.copyNodeAndPushItemIntoNewChild( - level: level, - self, - at: bucket, - itemSlot: rslot) + level: level, self, at: bucket, itemSlot: rslot) return (true, node) } if r.childMap.contains(bucket) { let rslot = r.childMap.slot(of: bucket) - let h = hashPrefix.appending(bucket, at: level) - let res = self._union(level.descend(), h, r[child: rslot]) + let res = self._union(level.descend(), r[child: rslot]) var node = other.copy() let delta = node.replaceChild(at: bucket, rslot, with: res.node) assert(delta >= 0) @@ -241,16 +231,12 @@ extension _Node { let lslot = l.itemMap.slot(of: bucket) assert(!l.hasSingletonItem) // Handled up front above let node = self.copyNodeAndPushItemIntoNewChild( - level: level, - other, - at: bucket, - itemSlot: lslot) + level: level, other, at: bucket, itemSlot: lslot) return (true, node) } if l.childMap.contains(bucket) { let lslot = l.childMap.slot(of: bucket) - let h = hashPrefix.appending(bucket, at: level) - let child = l[child: lslot]._union(level.descend(), h, other) + let child = l[child: lslot]._union(level.descend(), other) guard child.copied else { return (false, self) } var node = self.copy() let delta = node.replaceChild(at: bucket, lslot, with: child.node) diff --git a/Sources/PersistentCollections/Node/_Node+Subtree Insertions.swift b/Sources/PersistentCollections/Node/_Node+Subtree Insertions.swift index 758f4f6d..1c131781 100644 --- a/Sources/PersistentCollections/Node/_Node+Subtree Insertions.swift +++ b/Sources/PersistentCollections/Node/_Node+Subtree Insertions.swift @@ -204,8 +204,7 @@ extension _Node { assert(!isCollisionNode) if !isUnique { - self = copyNodeAndInsertItem( - at: bucket, itemSlot: slot, inserter) + self = copyNodeAndInsertItem(at: bucket, itemSlot: slot, inserter) return } if !hasFreeSpace(Self.spaceForNewItem) { @@ -220,17 +219,6 @@ extension _Node { self.count &+= 1 } - @inlinable @inline(__always) - internal func copyNodeAndInsertItem( - at bucket: _Bucket, - _ item: __owned Element - ) -> _Node { - let slot = read { $0.itemMap.slot(of: bucket) } - return copyNodeAndInsertItem(at: bucket, itemSlot: slot) { - $0.initialize(to: item) - } - } - @inlinable @inline(never) internal func copyNodeAndInsertItem( at bucket: _Bucket, @@ -466,43 +454,6 @@ extension _Node { } extension _Node { - @inlinable - internal mutating func ensureUniqueAndPushItemIntoNewChild( - isUnique: Bool, - level: _Level, - _ newChild: _Node, - at bucket: _Bucket, - itemSlot: _Slot - ) { - if !isUnique { - self = copyNodeAndPushItemIntoNewChild( - level: level, - newChild, - at: bucket, - itemSlot: itemSlot) - return - } - if !hasFreeSpace(Self.spaceForSpawningChild) { - resizeNodeAndPushItemIntoNewChild( - level: level, - newChild, - at: bucket, - itemSlot: itemSlot) - return - } - - assert(!isCollisionNode) - let item = removeItem(at: itemSlot, bucket) - let hash = _Hash(item.key) - let r = newChild.inserting(level.descend(), item, hash) - if self.count == 0, r.node.isCollisionNode { - // Compression - self = newChild - } else { - insertChild(r.node, bucket) - } - } - @inlinable @inline(never) internal func copyNodeAndPushItemIntoNewChild( level: _Level, @@ -520,24 +471,6 @@ extension _Node { at: bucket, itemSlot: itemSlot) } - - @inlinable @inline(never) - internal mutating func resizeNodeAndPushItemIntoNewChild( - level: _Level, - _ newChild: __owned _Node, - at bucket: _Bucket, - itemSlot: _Slot - ) { - assert(!isCollisionNode) - let item = update { $0.itemPtr(at: itemSlot).move() } - let hash = _Hash(item.key) - let r = newChild.inserting(level, item, hash) - _resizeNodeAndReplaceItemWithNewChild( - level: level, - r.node, - at: bucket, - itemSlot: itemSlot) - } } extension _Node { @@ -579,7 +512,7 @@ extension _Node { inserter) } - let existing = removeItem(at: itemSlot, bucket) + let existing = removeItem(at: bucket, itemSlot) let r = _Node.build( level: level.descend(), item1: existing, existingHash, diff --git a/Sources/PersistentCollections/Node/_Node+Subtree Modify.swift b/Sources/PersistentCollections/Node/_Node+Subtree Modify.swift index 25701bc2..fcf5bac0 100644 --- a/Sources/PersistentCollections/Node/_Node+Subtree Modify.swift +++ b/Sources/PersistentCollections/Node/_Node+Subtree Modify.swift @@ -124,7 +124,8 @@ extension _Node { } case (true, false): // Removal - _finalizeRemoval(.top, state.hash, at: state.path) + let remainder = _finalizeRemoval(.top, state.hash, at: state.path) + assert(remainder == nil) case (false, true): // Insertion let r = updateValue(.top, forKey: state.key, state.hash) { @@ -140,21 +141,19 @@ extension _Node { @inlinable internal mutating func _finalizeRemoval( _ level: _Level, _ hash: _Hash, at path: _UnsafePath - ) { + ) -> Element? { assert(isUnique()) if level == path.level { - _removeItemFromUniqueLeafNode( - level, hash[level], path.currentItemSlot, by: { _ in }) - } else { - let slot = path.childSlot(at: level) - let needsInlining: Bool = update { - let child = $0.childPtr(at: slot) - child.pointee._finalizeRemoval(level.descend(), hash, at: path) - return child.pointee.hasSingletonItem - } - _fixupUniqueAncestorAfterItemRemoval( - slot, { _ in hash[level] }, needsInlining: needsInlining) + return _removeItemFromUniqueLeafNode( + level, at: hash[level], path.currentItemSlot, by: { _ in } + ).remainder } + let slot = path.childSlot(at: level) + let remainder = update { + $0[child: slot]._finalizeRemoval(level.descend(), hash, at: path) + } + return _fixupUniqueAncestorAfterItemRemoval( + level, at: { _ in hash[level] }, slot, remainder: remainder) } } diff --git a/Sources/PersistentCollections/Node/_Node+Subtree Removals.swift b/Sources/PersistentCollections/Node/_Node+Subtree Removals.swift index 109580f4..29768d91 100644 --- a/Sources/PersistentCollections/Node/_Node+Subtree Removals.swift +++ b/Sources/PersistentCollections/Node/_Node+Subtree Removals.swift @@ -20,63 +20,47 @@ extension _Node { @inlinable internal mutating func remove( _ level: _Level, _ key: Key, _ hash: _Hash - ) -> Element? { - defer { _invariantCheck() } + ) -> (removed: Element, remainder: Element?)? { guard self.isUnique() else { guard let r = removing(level, key, hash) else { return nil } - self = r.replacement - return r.old + let remainder = self.applyReplacement(level, r.replacement) + return (r.removed, remainder) } guard let r = find(level, key, hash) else { return nil } + let bucket = hash[level] guard r.descend else { - let bucket = hash[level] - return _removeItemFromUniqueLeafNode(level, bucket, r.slot) { $0.move() } + let r = _removeItemFromUniqueLeafNode(level, at: bucket, r.slot) { + $0.move() + } + return (r.result, r.remainder) } - let (old, needsInlining): (Element?, Bool) = update { - let child = $0.childPtr(at: r.slot) - let old = child.pointee.remove(level.descend(), key, hash) - guard old != nil else { return (old, false) } - let needsInlining = child.pointee.hasSingletonItem - return (old, needsInlining) - } - guard old != nil else { return nil } - _fixupUniqueAncestorAfterItemRemoval( - r.slot, { _ in hash[level] }, needsInlining: needsInlining) - return old + let r2 = update { $0[child: r.slot].remove(level.descend(), key, hash) } + guard let r2 = r2 else { return nil } + let remainder = _fixupUniqueAncestorAfterItemRemoval( + level, + at: { _ in hash[level] }, + r.slot, + remainder: r2.remainder) + return (r2.removed, remainder) } } extension _Node { - // FIXME: Make this return a Builder @inlinable internal func removing( _ level: _Level, _ key: Key, _ hash: _Hash - ) -> (replacement: _Node, old: Element)? { + ) -> (removed: Element, replacement: Builder)? { guard let r = find(level, key, hash) else { return nil } + let bucket = hash[level] guard r.descend else { - return _removingItemFromLeaf(level, hash[level], r.slot) + return _removingItemFromLeaf(level, at: bucket, r.slot) } let r2 = read { $0[child: r.slot].removing(level.descend(), key, hash) } guard let r2 = r2 else { return nil } - return ( - _fixedUpAncestorAfterItemRemoval( - level, r.slot, hash[level], r2.replacement), - r2.old) - } - - @inlinable - internal func removing2( - _ level: _Level, _ key: Key, _ hash: _Hash - ) -> (replacement: Builder, old: Element)? { - guard let r = find(level, key, hash) else { return nil } - guard r.descend else { - return _removingItemFromLeaf(level, hash, r.slot) - } - let r2 = read { $0[child: r.slot].removing2(level.descend(), key, hash) } - guard let r2 = r2 else { return nil } - let result = self.replacingChild(level, hash, r.slot, with: r2.replacement) - return (result, r2.old) + let replacement = self.replacingChild( + level, at: bucket, r.slot, with: r2.replacement) + return (r2.removed, replacement) } } @@ -84,50 +68,47 @@ extension _Node { @inlinable internal mutating func remove( _ level: _Level, at path: _UnsafePath - ) -> Element { + ) -> (removed: Element, remainder: Element?) { defer { _invariantCheck() } guard self.isUnique() else { let r = removing(level, at: path) - self = r.replacement - return r.old + let remainder = applyReplacement(level, r.replacement) + return (r.removed, remainder) } if level == path.level { let slot = path.currentItemSlot let bucket = read { $0.itemBucket(at: slot) } - return _removeItemFromUniqueLeafNode( - level, bucket, slot, by: { $0.move() }) + let r = _removeItemFromUniqueLeafNode( + level, at: bucket, slot, by: { $0.move() }) + return (r.result, r.remainder) } let slot = path.childSlot(at: level) - let (item, needsInlining): (Element, Bool) = update { - let child = $0.childPtr(at: slot) - let item = child.pointee.remove(level.descend(), at: path) - return (item, child.pointee.hasSingletonItem) - } - _fixupUniqueAncestorAfterItemRemoval( + let r = update { $0[child: slot].remove(level.descend(), at: path) } + let remainder = _fixupUniqueAncestorAfterItemRemoval( + level, + at: { $0.childMap.bucket(at: slot) }, slot, - { $0.read { $0.childMap.bucket(at: slot) } }, - needsInlining: needsInlining) - return item + remainder: r.remainder) + return (r.removed, remainder) } @inlinable internal func removing( _ level: _Level, at path: _UnsafePath - ) -> (replacement: _Node, old: Element) { + ) -> (removed: Element, replacement: Builder) { if level == path.level { let slot = path.currentItemSlot let bucket = read { $0.itemBucket(at: slot) } - return _removingItemFromLeaf(level, bucket, slot) + return _removingItemFromLeaf(level, at: bucket, slot) } let slot = path.childSlot(at: level) - let (bucket, r) = read { - ($0.childMap.bucket(at: slot), - $0[child: slot].removing(level.descend(), at: path)) + return read { + let bucket = $0.childMap.bucket(at: slot) + let r = $0[child: slot].removing(level.descend(), at: path) + return ( + r.removed, + self.replacingChild(level, at: bucket, slot, with: r.replacement)) } - return ( - _fixedUpAncestorAfterItemRemoval(level, slot, bucket, r.replacement), - r.old - ) } } @@ -135,70 +116,81 @@ extension _Node { @inlinable internal mutating func _removeItemFromUniqueLeafNode( _ level: _Level, - _ bucket: _Bucket, + at bucket: _Bucket, _ slot: _Slot, by remover: (UnsafeMutablePointer) -> R - ) -> R { + ) -> (result: R, remainder: Element?) { assert(isUnique()) - let result = removeItem(at: slot, bucket, by: remover) + let result = removeItem(at: bucket, slot, by: remover) if isAtrophied { self = removeSingletonChild() } - if level.isAtRoot, isCollisionNode, hasSingletonItem { - self._convertToRegularNode() + if hasSingletonItem { + if level.isAtRoot { + if isCollisionNode { + _convertToRegularNode() + } + return (result, nil) + } + let item = removeSingletonItem() + return (result, item) } - return result + return (result, nil) } @inlinable internal func _removingItemFromLeaf( - _ level: _Level, _ bucket: _Bucket, _ slot: _Slot - ) -> (replacement: _Node, old: Element) { - // Don't copy the node if we'd immediately discard it. - let willAtrophy = read { - $0.itemCount == 1 - && $0.childCount == 1 - && $0[child: .zero].isCollisionNode - } - if willAtrophy { - return read { (replacement: $0[child: .zero], old: $0[item: .zero]) } - } - var node = self.copy() - let old = node.removeItem(at: slot, bucket) - if level.isAtRoot, node.isCollisionNode, node.hasSingletonItem { - node._convertToRegularNode() - } - node._invariantCheck() - return (node, old) - } - - @inlinable - internal func _removingItemFromLeaf( - _ level: _Level, _ hash: _Hash, _ slot: _Slot - ) -> (replacement: Builder, old: Element) { + _ level: _Level, at bucket: _Bucket, _ slot: _Slot + ) -> (removed: Element, replacement: Builder) { read { - assert($0.isCollisionNode || $0.itemMap.contains(hash[level])) - assert(!$0.isCollisionNode || slot.value < $0.collisionCount ) - assert($0.isCollisionNode || slot == $0.itemMap.slot(of: hash[level])) + if $0.isCollisionNode { + assert(slot.value < $0.collisionCount ) + + if $0.collisionCount == 2 { + // Node will evaporate + let remainder = _Slot(1 &- slot.value) + let bucket = $0.collisionHash[level] + return ( + removed: $0[item: slot], + replacement: .item(level, $0[item: remainder], at: bucket)) + } + + var node = self.copy() + let old = node.removeItem(at: bucket, slot) + node._invariantCheck() + return (old, .collisionNode(level, node)) + } + + assert($0.itemMap.contains(bucket)) + assert(slot == $0.itemMap.slot(of: bucket)) + let willAtrophy = ( $0.itemCount == 1 && $0.childCount == 1 && $0[child: .zero].isCollisionNode) if willAtrophy { + // Compression let child = $0[child: .zero] let old = $0[item: .zero] - return (.node(child, child.collisionHash), old) + return (old, .collisionNode(level, child)) } + let willEvaporate = ($0.itemCount == 2 && $0.childCount == 0) if willEvaporate { - let remainder = $0[item: _Slot(1 &- slot.value)] - let old = $0[item: slot] - return (.item(remainder, hash), old) + let remainder = _Slot(1 &- slot.value) + + var map = $0.itemMap + if remainder != .zero { _ = map.popFirst() } + let bucket = map.first! + + return ( + removed: $0[item: slot], + replacement: .item(level, $0[item: remainder], at: bucket)) } var node = self.copy() - let old = node.removeItem(at: slot, hash[level]) + let old = node.removeItem(at: bucket, slot) node._invariantCheck() - return (.node(node, hash), old) + return (old, .node(level, node)) } } } @@ -206,7 +198,7 @@ extension _Node { extension _Node { @inlinable internal func _removingChild( - _ level: _Level, _ hashPrefix: _Hash, _ bucket: _Bucket, _ slot: _Slot + _ level: _Level, at bucket: _Bucket, _ slot: _Slot ) -> Builder { read { assert(!$0.isCollisionNode && $0.childMap.contains(bucket)) @@ -216,21 +208,23 @@ extension _Node { && $0[child: _Slot(1 &- slot.value)].isCollisionNode ) if willAtrophy { + // Compression let child = $0[child: _Slot(1 &- slot.value)] - return .node(child, child.collisionHash) + return .collisionNode(level, child) } let willTurnIntoItem = ($0.itemCount == 1 && $0.childCount == 1) if willTurnIntoItem { - return .item($0[item: .zero], hashPrefix) + return .item(level, $0[item: .zero], at: $0.itemMap.first!) } let willEvaporate = ($0.itemCount == 0 && $0.childCount == 1) if willEvaporate { - return .empty + return .empty(level) } + var node = self.copy() - _ = node.removeChild(at: slot, bucket) + _ = node.removeChild(at: bucket, slot) node._invariantCheck() - return .node(node, hashPrefix) + return .node(level, node) } } } @@ -238,49 +232,32 @@ extension _Node { extension _Node { @inlinable internal mutating func _fixupUniqueAncestorAfterItemRemoval( - _ slot: _Slot, - _ bucket: (inout Self) -> _Bucket, - needsInlining: Bool - ) { + _ level: _Level, + at bucket: (UnsafeHandle) -> _Bucket, + _ childSlot: _Slot, + remainder: Element? + ) -> Element? { assert(isUnique()) count &-= 1 - if needsInlining { + if let remainder = remainder { + if hasSingletonChild, !level.isAtRoot { + self = ._emptyNode() + return remainder + } + // Child to be inlined has already been cleared, so we need to adjust + // the count manually. + assert(read { $0[child: childSlot].count == 0 }) + count &-= 1 + let bucket = read { bucket($0) } ensureUnique(isUnique: true, withFreeSpace: Self.spaceForInlinedChild) - let bucket = bucket(&self) - var child = self.removeChild(at: slot, bucket) - let item = child.removeSingletonItem() - insertItem(item, at: bucket) + _ = self.removeChild(at: bucket, childSlot) + insertItem(remainder, at: bucket) + return nil } if isAtrophied { self = removeSingletonChild() } - } - - @inlinable - internal func _fixedUpAncestorAfterItemRemoval( - _ level: _Level, - _ slot: _Slot, - _ bucket: _Bucket, - _ newChild: __owned _Node - ) -> _Node { - var newChild = newChild - if newChild.hasSingletonItem { - var node = copy(withFreeSpace: Self.spaceForInlinedChild) - _ = node.removeChild(at: slot, bucket) - let item = newChild.removeSingletonItem() - node.insertItem(item, at: bucket) - node._invariantCheck() - return node - } - if newChild.isCollisionNode && self.hasSingletonChild { - // Don't return an atrophied node. - return newChild - } - var node = copy() - node.update { $0[child: slot] = newChild } - node.count &-= 1 - node._invariantCheck() - return node + return nil } } diff --git a/Sources/PersistentCollections/Node/_UnsafePath.swift b/Sources/PersistentCollections/Node/_UnsafePath.swift index a3a878a3..5693ccc1 100644 --- a/Sources/PersistentCollections/Node/_UnsafePath.swift +++ b/Sources/PersistentCollections/Node/_UnsafePath.swift @@ -216,15 +216,6 @@ extension _UnsafePath { internal var isOnNodeEnd: Bool { !_isItem && nodeSlot.value == node.childCount } - - /// Returns true if this path addresses an item on the leftmost branch of the - /// tree, or the empty slot at the end of an empty tree. - @inlinable - internal var isOnLeftmostItem: Bool { - // We are on the leftmost item in the tree if we are currently - // addressing an item and the ancestors path is all zero bits. - _isItem && ancestors == .empty && nodeSlot == .zero - } } extension _UnsafePath { @@ -375,30 +366,6 @@ extension _UnsafePath { self = best return true } - /// Ascend to the parent node of this path. Because paths do not contain - /// references to every node on them, you need to manually supply a valid - /// reference to the root node. This method visits every node - /// between the root and the current final node on the path. - /// - /// - Note: It is undefined behavior to call this on a path that is no longer - /// valid. - internal mutating func ascend(under root: _RawNode) { - assert(!self.level.isAtRoot) - var n = root.unmanaged - var l: _Level = .top - while l.descend() < self.level { - n = n.unmanagedChild(at: self.ancestors[l]) - l = l.descend() - } - assert(l.descend() == self.level) - self._isItem = false - self.nodeSlot = self.ancestors[l] - let oldNode = self.node - self.node = n - self.ancestors.clear(l) - self.level = l - assert(self.currentChild == oldNode) - } } extension _UnsafePath { diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Debugging.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Debugging.swift index 5ad90df9..65e7a49b 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Debugging.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Debugging.swift @@ -24,7 +24,7 @@ extension PersistentDictionary { @inlinable public func _invariantCheck() { - _root._fullInvariantCheck(.top, .emptyPrefix) + _root._fullInvariantCheck() } public func _dump(iterationOrder: Bool = false) { diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Filter.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Filter.swift index de07b163..6e6272fe 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Filter.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Filter.swift @@ -14,7 +14,7 @@ extension PersistentDictionary { public func filter( _ isIncluded: (Element) throws -> Bool ) rethrows -> Self { - let result = try _root.filter(.top, .emptyPrefix, isIncluded) + let result = try _root.filter(.top, isIncluded) guard let result = result else { return self } return PersistentDictionary(_new: result.finalize(.top)) } diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Initializers.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Initializers.swift index 5ba31a3d..e8dedf1e 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Initializers.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Initializers.swift @@ -12,7 +12,7 @@ extension PersistentDictionary { @inlinable public init() { - self.init(_new: ._empty()) + self.init(_new: ._emptyNode()) } @inlinable diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+MapValues.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+MapValues.swift index ae996879..ebd35e27 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+MapValues.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+MapValues.swift @@ -22,7 +22,7 @@ extension PersistentDictionary { public func compactMapValues( _ transform: (Value) throws -> T? ) rethrows -> PersistentDictionary { - let result = try _root.compactMapValues(.top, .emptyPrefix, transform) + let result = try _root.compactMapValues(.top, transform) return PersistentDictionary(_new: result.finalize(.top)) } } diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Merge.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Merge.swift index d50533f8..1954ba5b 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Merge.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Merge.swift @@ -16,7 +16,7 @@ extension PersistentDictionary { uniquingKeysWith combine: (Value, Value) throws -> Value ) rethrows { _invalidateIndices() - try _root.merge(.top, .emptyPrefix, keysAndValues._root, combine) + try _root.merge(.top, keysAndValues._root, combine) } @inlinable diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary.swift index 138cd793..e31e4604 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary.swift @@ -382,16 +382,18 @@ extension PersistentDictionary { @inlinable @discardableResult public mutating func removeValue(forKey key: Key) -> Value? { + guard let r = _root.remove(.top, key, _Hash(key)) else { return nil } _invalidateIndices() - return _root.remove(.top, key, _Hash(key))?.value + assert(r.remainder == nil) + _invariantCheck() + return r.removed.value } // fluid/immutable API @inlinable public func removingValue(forKey key: Key) -> Self { - var copy = self - copy.removeValue(forKey: key) - return copy + guard let r = _root.removing(.top, key, _Hash(key)) else { return self } + return Self(_new: r.replacement.finalize(.top)) } @inlinable @@ -399,7 +401,9 @@ extension PersistentDictionary { precondition(_isValid(index), "Invalid index") precondition(index._path._isItem, "Can't remove item at end index") _invalidateIndices() - return _root.remove(.top, at: index._path) + let r = _root.remove(.top, at: index._path) + assert(r.remainder == nil) + return r.removed } } diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+Debugging.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+Debugging.swift index 9c108c37..58e4cfb7 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+Debugging.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+Debugging.swift @@ -24,7 +24,7 @@ extension PersistentSet { @inlinable public func _invariantCheck() { - _root._fullInvariantCheck(.top, .emptyPrefix) + _root._fullInvariantCheck() } public func _dump(iterationOrder: Bool = false) { diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+Filter.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+Filter.swift index 888a4447..31d02a48 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+Filter.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+Filter.swift @@ -24,9 +24,7 @@ extension PersistentSet { public func filter( _ isIncluded: (Element) throws -> Bool ) rethrows -> Self { - let result = try _root.filter(.top, .emptyPrefix) { - try isIncluded($0.key) - } + let result = try _root.filter(.top) { try isIncluded($0.key) } guard let result = result else { return self } return PersistentSet(_new: result.finalize(.top)) } diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra Initializers.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra Initializers.swift index 26608494..66861b6e 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra Initializers.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra Initializers.swift @@ -18,7 +18,7 @@ extension PersistentSet { /// - Complexity: O(1) @inlinable public init() { - self.init(_new: ._empty()) + self.init(_new: ._emptyNode()) } /// Creates a new set from a finite sequence of items. diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra basics.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra basics.swift index 99ece768..9d62afe6 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra basics.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra basics.swift @@ -85,8 +85,10 @@ extension PersistentSet: SetAlgebra { @inlinable public mutating func remove(_ member: Element) -> Element? { let hash = _Hash(member) + guard let r = _root.remove(.top, member, hash) else { return nil } _invalidateIndices() - return _root.remove(.top, member, hash)?.key + assert(r.remainder == nil) + return r.removed.key } /// Inserts the given element into the set unconditionally. diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra fluent basics.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra fluent basics.swift index 9764db72..45cf7d26 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra fluent basics.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra fluent basics.swift @@ -39,7 +39,8 @@ extension PersistentSet { let hash = _Hash(member) let r = _root.removing(.top, member, hash) guard let r = r else { return self } - return PersistentSet(_new: r.replacement) + let root = r.replacement.finalize(.top) + return PersistentSet(_new: root) } @inlinable diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra intersection.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra intersection.swift index 309d0d48..567d3c11 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra intersection.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra intersection.swift @@ -44,10 +44,10 @@ extension PersistentSet { internal func _intersection( _ other: PersistentCollections._Node ) -> Self { - let builder = _root.intersection(.top, .emptyPrefix, other) + let builder = _root.intersection(.top, other) guard let builder = builder else { return self } let root = builder.finalize(.top) - root._fullInvariantCheck(.top, .emptyPrefix) + root._fullInvariantCheck() return Self(_new: root) } @@ -80,7 +80,7 @@ extension PersistentSet { return self.filter { other.contains($0) } } - var result: _Node = ._empty() + var result: _Node = ._emptyNode() for item in other { let hash = _Hash(item) if let r = self._root.lookup(.top, item, hash) { diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra subtracting.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra subtracting.swift index b30739ed..01f0dec9 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra subtracting.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra subtracting.swift @@ -40,10 +40,10 @@ extension PersistentSet { internal __consuming func _subtracting( _ other: PersistentCollections._Node ) -> Self { - let builder = _root.subtracting(.top, .emptyPrefix, other) + let builder = _root.subtracting(.top, other) guard let builder = builder else { return self } let root = builder.finalize(.top) - root._fullInvariantCheck(.top, .emptyPrefix) + root._fullInvariantCheck() return Self(_new: root) } diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra symmetricDifference.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra symmetricDifference.swift index 53b379ea..d210d21d 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra symmetricDifference.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra symmetricDifference.swift @@ -26,9 +26,10 @@ extension PersistentSet { /// parts of the input trees directly into the result. @inlinable public func symmetricDifference(_ other: __owned Self) -> Self { - let branch = _root.symmetricDifference(.top, .emptyPrefix, other._root) + let branch = _root.symmetricDifference(.top, other._root) guard let branch = branch else { return self } let root = branch.finalize(.top) + root._fullInvariantCheck() return PersistentSet(_new: root) } diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra union.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra union.swift index 525272b8..80f1399d 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra union.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra union.swift @@ -29,9 +29,9 @@ extension PersistentSet { @inlinable public func union(_ other: __owned Self) -> Self { - let r = _root.union(.top, .emptyPrefix, other._root) + let r = _root.union(.top, other._root) guard r.copied else { return self } - r.node._fullInvariantCheck(.top, .emptyPrefix) + r.node._fullInvariantCheck() return PersistentSet(_new: r.node) } From 6b516b72fb5c6955b02c0eb8de0b9a8e3c579d08 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Sat, 1 Oct 2022 12:37:05 -0700 Subject: [PATCH 27/31] [PersistentCollections] Slightly more readable index descriptions (cherry picked from commit 785caa4a55f2638b11b4a89124f0220a26337ca4) --- Sources/PersistentCollections/Node/_UnsafePath.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Sources/PersistentCollections/Node/_UnsafePath.swift b/Sources/PersistentCollections/Node/_UnsafePath.swift index 5693ccc1..8800d41b 100644 --- a/Sources/PersistentCollections/Node/_UnsafePath.swift +++ b/Sources/PersistentCollections/Node/_UnsafePath.swift @@ -161,13 +161,13 @@ extension _UnsafePath: CustomStringConvertible { l = l.descend() } if isPlaceholder { - d += "[\(self.nodeSlot)]?" + d += ".end[\(self.nodeSlot)]" } else if isOnItem { d += "[\(self.nodeSlot)]" } else if isOnChild { d += ".\(self.nodeSlot)" } else if isOnNodeEnd { - d += ".$(\(self.nodeSlot))" + d += ".end(\(self.nodeSlot))" } return d } From bceadab267ce0ef79fcea4a0e322ec4b471ec2c0 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 5 Oct 2022 10:26:05 -0700 Subject: [PATCH 28/31] [PersistentCollections] Reduce popcount usages where possible # Conflicts: # Sources/PersistentCollections/Node/_Node+Primitive Removals.swift (cherry picked from commit e153ebf7985f2c0097bdf1d5302014e6e0e9c962) --- .../PersistentCollections/Node/_Bitmap.swift | 5 +++++ .../Node/_Node+Primitive Removals.swift | 4 ++-- .../Node/_Node+Subtree Removals.swift | 18 +++++++++--------- .../Node/_Node+UnsafeHandle.swift | 4 ++-- .../Node/_StorageHeader.swift | 13 +++++++++++++ 5 files changed, 31 insertions(+), 13 deletions(-) diff --git a/Sources/PersistentCollections/Node/_Bitmap.swift b/Sources/PersistentCollections/Node/_Bitmap.swift index 051a7732..cb06f271 100644 --- a/Sources/PersistentCollections/Node/_Bitmap.swift +++ b/Sources/PersistentCollections/Node/_Bitmap.swift @@ -86,6 +86,11 @@ extension _Bitmap { @inlinable @inline(__always) internal var isEmpty: Bool { _value == 0 } + @inlinable @inline(__always) + internal var hasExactlyOneMember: Bool { + _value != 0 && _value & (_value &- 1) == 0 + } + @inlinable @inline(__always) internal var first: _Bucket? { guard !isEmpty else { return nil } diff --git a/Sources/PersistentCollections/Node/_Node+Primitive Removals.swift b/Sources/PersistentCollections/Node/_Node+Primitive Removals.swift index 9c5d2281..367bf787 100644 --- a/Sources/PersistentCollections/Node/_Node+Primitive Removals.swift +++ b/Sources/PersistentCollections/Node/_Node+Primitive Removals.swift @@ -127,7 +127,7 @@ extension _Node { assert(count == 1) count = 0 return update { - assert($0.itemCount == 1 && $0.childCount == 0) + assert($0.hasSingletonItem) let old = $0._removeItem(at: .zero) { $0.move() } $0.clear() return old @@ -138,7 +138,7 @@ extension _Node { internal mutating func removeSingletonChild() -> _Node { defer { _invariantCheck() } let child: _Node = update { - assert($0.itemCount == 0 && $0.childCount == 1) + assert($0.hasSingletonChild) let child = $0._removeChild(at: .zero) $0.childMap = .empty return child diff --git a/Sources/PersistentCollections/Node/_Node+Subtree Removals.swift b/Sources/PersistentCollections/Node/_Node+Subtree Removals.swift index 29768d91..302b91c4 100644 --- a/Sources/PersistentCollections/Node/_Node+Subtree Removals.swift +++ b/Sources/PersistentCollections/Node/_Node+Subtree Removals.swift @@ -165,8 +165,9 @@ extension _Node { assert(slot == $0.itemMap.slot(of: bucket)) let willAtrophy = ( - $0.itemCount == 1 - && $0.childCount == 1 + !$0.isCollisionNode + && $0.itemMap.hasExactlyOneMember + && $0.childMap.hasExactlyOneMember && $0[child: .zero].isCollisionNode) if willAtrophy { // Compression @@ -175,8 +176,8 @@ extension _Node { return (old, .collisionNode(level, child)) } - let willEvaporate = ($0.itemCount == 2 && $0.childCount == 0) - if willEvaporate { + if $0.itemMap.count == 2 && $0.childMap.isEmpty { + // Evaporating node let remainder = _Slot(1 &- slot.value) var map = $0.itemMap @@ -203,7 +204,7 @@ extension _Node { read { assert(!$0.isCollisionNode && $0.childMap.contains(bucket)) let willAtrophy = ( - $0.itemCount == 0 + $0.itemMap.isEmpty && $0.childCount == 2 && $0[child: _Slot(1 &- slot.value)].isCollisionNode ) @@ -212,12 +213,11 @@ extension _Node { let child = $0[child: _Slot(1 &- slot.value)] return .collisionNode(level, child) } - let willTurnIntoItem = ($0.itemCount == 1 && $0.childCount == 1) - if willTurnIntoItem { + if $0.itemMap.hasExactlyOneMember && $0.childMap.hasExactlyOneMember { return .item(level, $0[item: .zero], at: $0.itemMap.first!) } - let willEvaporate = ($0.itemCount == 0 && $0.childCount == 1) - if willEvaporate { + if $0.hasSingletonChild { + // Evaporate node return .empty(level) } diff --git a/Sources/PersistentCollections/Node/_Node+UnsafeHandle.swift b/Sources/PersistentCollections/Node/_Node+UnsafeHandle.swift index f10d4e5e..680e0517 100644 --- a/Sources/PersistentCollections/Node/_Node+UnsafeHandle.swift +++ b/Sources/PersistentCollections/Node/_Node+UnsafeHandle.swift @@ -280,12 +280,12 @@ extension _Node.UnsafeHandle { extension _Node.UnsafeHandle { @inlinable internal var hasSingletonItem: Bool { - itemCount == 1 && childCount == 0 + _header.pointee.hasSingletonItem } @inlinable internal var hasSingletonChild: Bool { - itemMap.isEmpty && childCount == 1 + _header.pointee.hasSingletonChild } @inlinable diff --git a/Sources/PersistentCollections/Node/_StorageHeader.swift b/Sources/PersistentCollections/Node/_StorageHeader.swift index e5b6225f..3684b4a9 100644 --- a/Sources/PersistentCollections/Node/_StorageHeader.swift +++ b/Sources/PersistentCollections/Node/_StorageHeader.swift @@ -87,6 +87,19 @@ extension _StorageHeader { : itemMap.count) } + @inlinable + internal var hasSingletonChild: Bool { + itemMap.isEmpty && childMap.hasExactlyOneMember + } + + @inlinable + internal var hasSingletonItem: Bool { + if itemMap == childMap { + return itemMap._value == 1 + } + return childMap.isEmpty && itemMap.hasExactlyOneMember + } + @inlinable @inline(__always) internal var childrenEndSlot: _Slot { _Slot(childCount) From 25fd503fac0a8881ab707dac4348fc871a577acb Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 12 Oct 2022 15:08:22 -0700 Subject: [PATCH 29/31] [PersistentCollections] Fix up code added since c73a8caa originally landed (cherry picked from commit 4c842df1b8cfc9611762bdf5fbd9023ab2d3d333) --- .../PersistentSet/PersistentSet+Extras.swift | 4 +++- .../PersistentSet/PersistentSet+SetAlgebra isEqual.swift | 2 +- .../PersistentSet+SetAlgebra isStrictSubset.swift | 2 +- .../PersistentSet+SetAlgebra isStrictSuperset.swift | 2 +- .../PersistentSet/PersistentSet+SetAlgebra isSubset.swift | 2 +- 5 files changed, 7 insertions(+), 5 deletions(-) diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+Extras.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+Extras.swift index a5539c89..bd9ff73b 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+Extras.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+Extras.swift @@ -18,7 +18,9 @@ extension PersistentSet { public mutating func remove(at position: Index) -> Element { precondition(_isValid(position)) _invalidateIndices() - return _root.remove(.top, at: position._path).key + let r = _root.remove(.top, at: position._path) + precondition(r.remainder == nil) + return r.removed.key } /// Replace the member at the given index with a new value that compares equal diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isEqual.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isEqual.swift index 4bd0d739..fa2941bd 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isEqual.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isEqual.swift @@ -102,7 +102,7 @@ extension PersistentSet { } // FIXME: Would making this a BitSet of seen positions be better? - var seen: _Node? = ._empty() + var seen: _Node? = ._emptyNode() var it = other.makeIterator() while let item = it.next() { let hash = _Hash(item) diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSubset.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSubset.swift index c545278e..9fff1da7 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSubset.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSubset.swift @@ -111,7 +111,7 @@ extension PersistentSet { } // FIXME: Would making this a BitSet of seen positions be better? - var seen: _Node = ._empty() + var seen: _Node = ._emptyNode() var doneCollecting = false var isStrict = false var it = other.makeIterator() diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSuperset.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSuperset.swift index 5616be58..6625c7eb 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSuperset.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSuperset.swift @@ -108,7 +108,7 @@ extension PersistentSet { } // FIXME: Would making this a BitSet of seen positions be better? - var seen: _Node = ._empty() + var seen: _Node = ._emptyNode() for item in other { let hash = _Hash(item) guard self._root.containsKey(.top, item, hash) else { return false } diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isSubset.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isSubset.swift index e3af14d9..542d1df2 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isSubset.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isSubset.swift @@ -99,7 +99,7 @@ extension PersistentSet { } // FIXME: Would making this a BitSet of seen positions be better? - var seen: _Node = ._empty() + var seen: _Node = ._emptyNode() for item in other { let hash = _Hash(item) guard _root.containsKey(.top, item, hash) else { continue } From 56be3ae3fdcfc00ec97da7c99dbe481a3dc0be85 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 19 Oct 2022 17:56:22 -0700 Subject: [PATCH 30/31] [PersistentSet] Adjust code after merge --- .../PersistentSet/PersistentSet+SetAlgebra isStrictSubset.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSubset.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSubset.swift index 9fff1da7..9ccb06b8 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSubset.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSubset.swift @@ -126,7 +126,7 @@ extension PersistentSet { if isStrict { return true } // Stop collecting seen items -- we just need to decide // strictness now. - seen = ._empty() + seen = ._emptyNode() doneCollecting = true } } else { From 67fdff5a25539a51ce2a8bf574a7e4a6b72ebfb8 Mon Sep 17 00:00:00 2001 From: Saleem Abdulrasool Date: Wed, 19 Oct 2022 11:14:47 -0700 Subject: [PATCH 31/31] Update CMakeLists.txt Remove missing file. Thanks to @stevenbrix for identifying this! (cherry picked from commit 5e0a0149a4c9b2ab407f65b257b5b36bc589307d) --- Sources/PersistentCollections/CMakeLists.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/Sources/PersistentCollections/CMakeLists.txt b/Sources/PersistentCollections/CMakeLists.txt index c162866b..eac88614 100644 --- a/Sources/PersistentCollections/CMakeLists.txt +++ b/Sources/PersistentCollections/CMakeLists.txt @@ -16,7 +16,6 @@ add_library(PersistentCollections "Node/_HashTreeStatistics.swift" "Node/_Level.swift" "Node/_Node+Builder.swift" - "Node/_Node+CustomStringConvertible.swift" "Node/_Node+Debugging.swift" "Node/_Node+Initializers.swift" "Node/_Node+Invariants.swift"