From e74283a2fa64c490197edbf3192760a166020e5d Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 19 Oct 2022 18:43:12 -0700 Subject: [PATCH 01/39] [PersistentCollections] Remove BitmapSmokeTests.swift MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The underlying code no longer looks like what we had before, and @testable imports need to be disabled in release builds. We should be testing internals, but this isn’t carrying much weight right now. Also remove a couple of PersistentDictionary smoke tests that are also relying on @testable. --- .../BitmapSmokeTests.swift | 64 ------------------- .../PersistentDictionary Smoke Tests.swift | 27 +------- .../PersistentDictionary Tests.swift | 2 +- 3 files changed, 2 insertions(+), 91 deletions(-) delete mode 100644 Tests/PersistentCollectionsTests/BitmapSmokeTests.swift diff --git a/Tests/PersistentCollectionsTests/BitmapSmokeTests.swift b/Tests/PersistentCollectionsTests/BitmapSmokeTests.swift deleted file mode 100644 index fb85ddec..00000000 --- a/Tests/PersistentCollectionsTests/BitmapSmokeTests.swift +++ /dev/null @@ -1,64 +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 -// -//===----------------------------------------------------------------------===// - -import _CollectionsTestSupport -import XCTest -@testable import PersistentCollections - -#if false -final class BitmapSmokeTests: CollectionTestCase { - func test_BitPartitionSize_isValid() { - expectTrue(_bitPartitionSize > 0) - expectTrue((2 << (_bitPartitionSize - 1)) != 0) - expectTrue((2 << (_bitPartitionSize - 1)) <= Bitmap.bitWidth) - } - - func test_Bitmap_nonzeroBits() { - let bitmap: Bitmap = 0b0100_0000_0000_1011 - - expectEqual(Array(bitmap._nonzeroBits()), [0, 1, 3, 14]) - expectEqual( - Array(bitmap._zeroBits()), - (0 ..< Bitmap.bitWidth).filter { ![0, 1, 3, 14].contains($0) }) - } - - func test_Bitmap_nonzeroBitsToArray() { - let bitmap: Bitmap = 0b0100_0000_0000_1011 - - let counts = bitmap._nonzeroBits().reduce( - into: Array(repeating: 0, count: Bitmap.bitWidth) - ) { counts, index in - counts[index] = 1 - } - - expectEqual(counts.count, Bitmap.bitWidth) - expectEqual(counts.reduce(0, +), bitmap.nonzeroBitCount) - expectEqual(counts.reduce(0, +), 4) - expectEqual(counts[0], 1) - expectEqual(counts[1], 1) - expectEqual(counts[3], 1) - expectEqual(counts[14], 1) - } - - func test_Bitmap_enumerateCompactedArray() { - let bitmap: Bitmap = 0b0100_0000_0000_1011 - let elements: [String] = ["zero", "one", "three", "fourteen"] - - var zipIterator = zip(bitmap._nonzeroBits(), elements).makeIterator() - - expectEqual(zipIterator.next()!, (0, "zero")) - expectEqual(zipIterator.next()!, (1, "one")) - expectEqual(zipIterator.next()!, (3, "three")) - expectEqual(zipIterator.next()!, (14, "fourteen")) - expectNil(zipIterator.next()) - } -} -#endif diff --git a/Tests/PersistentCollectionsTests/PersistentDictionary Smoke Tests.swift b/Tests/PersistentCollectionsTests/PersistentDictionary Smoke Tests.swift index 686046d8..0cd0c9b3 100644 --- a/Tests/PersistentCollectionsTests/PersistentDictionary Smoke Tests.swift +++ b/Tests/PersistentCollectionsTests/PersistentDictionary Smoke Tests.swift @@ -10,7 +10,7 @@ //===----------------------------------------------------------------------===// import _CollectionsTestSupport -@testable import PersistentCollections +import PersistentCollections final class PersistentDictionarySmokeTests: CollectionTestCase { func testDummy() { @@ -204,31 +204,6 @@ final class PersistentDictionarySmokeTests: CollectionTestCase { expectNotEqual(res31, res12) } - func testCountForCopyOnWriteInsertion() { - let map = PersistentDictionary([ - Collider(1): Collider(1), - Collider(32769_1, 32769): Collider(32769_1, 32769), - Collider(32769_2, 32769): Collider(32769_2, 32769) - ]) - expectEqual(map._root.count, 3) - expectEqual(map.reduce(0, { count, _ in count + 1 }), 3) - map._root._invariantCheck() - } - - func testCountForCopyOnWriteDeletion() { - var map: PersistentDictionary = [:] - - map[Collider(32769)] = Collider(32769) - map[Collider(11, 1)] = Collider(11, 1) - map[Collider(12, 1)] = Collider(12, 1) - map[Collider(33, 33)] = Collider(33, 33) - map[Collider(11, 1)] = nil - map[Collider(12, 1)] = nil - expectEqual(map._root.count, 2) - expectEqual(map.reduce(0, { count, _ in count + 1 }), 2) - map._root._invariantCheck() - } - func testCompactionWhenDeletingFromHashCollisionNode1() { let map: PersistentDictionary = [:] diff --git a/Tests/PersistentCollectionsTests/PersistentDictionary Tests.swift b/Tests/PersistentCollectionsTests/PersistentDictionary Tests.swift index 3efadf10..d2855ed0 100644 --- a/Tests/PersistentCollectionsTests/PersistentDictionary Tests.swift +++ b/Tests/PersistentCollectionsTests/PersistentDictionary Tests.swift @@ -10,7 +10,7 @@ //===----------------------------------------------------------------------===// import _CollectionsTestSupport -@testable import PersistentCollections +import PersistentCollections extension PersistentDictionary: DictionaryAPIExtras {} From 5783b82d72e620f37545924d46bdbfb429f03cbb Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 19 Oct 2022 19:33:33 -0700 Subject: [PATCH 02/39] [PersistentCollections] Fix building with library stability enabled MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Building this package with library stability enabled is entirely unsupported, but let’s add a few @frozen attributes to fix such builds anyway. This package is explicitly not ABI stable; the @frozen attribute does not mean a guarantee to leave layout unchanged in future revisions. --- Sources/PersistentCollections/Node/_UnsafePath.swift | 1 + .../PersistentDictionary/PersistentDictionary.swift | 1 + Sources/PersistentCollections/PersistentSet/PersistentSet.swift | 1 + 3 files changed, 3 insertions(+) diff --git a/Sources/PersistentCollections/Node/_UnsafePath.swift b/Sources/PersistentCollections/Node/_UnsafePath.swift index 8800d41b..58170d57 100644 --- a/Sources/PersistentCollections/Node/_UnsafePath.swift +++ b/Sources/PersistentCollections/Node/_UnsafePath.swift @@ -34,6 +34,7 @@ /// in a fixed-size array; this would speed up walking over the tree, but it /// would considerably embiggen the size of the path construct.) @usableFromInline +@frozen internal struct _UnsafePath { @usableFromInline internal var ancestors: _AncestorSlots diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary.swift index e31e4604..d97a9ab0 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary.swift @@ -9,6 +9,7 @@ // //===----------------------------------------------------------------------===// +@frozen // Not really -- this package is not at all ABI stable public struct PersistentDictionary { @usableFromInline internal typealias _Node = PersistentCollections._Node diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet.swift index 98260bb9..e90aab25 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet.swift @@ -9,6 +9,7 @@ // //===----------------------------------------------------------------------===// +@frozen // Not really -- this package is not at all ABI stable public struct PersistentSet { @usableFromInline internal typealias _Node = PersistentCollections._Node From 71434218009c539b34acef6fe23d6b4c8f91b205 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 20 Oct 2022 13:29:10 -0700 Subject: [PATCH 03/39] [OrderedCollections] Add missing Custom[Debug]StringConvertable conformances, review existing ones Add `Custom[Debug]StringConvertible` conformance on: - `OrderedDictionary.Values` - `OrderedDictionary.Elements.Subsequence` - `OrderedSet.SubSequence` --- .../HashTable/_HashTable+Testing.swift | 1 + .../OrderedDictionary+Descriptions.swift | 4 ++-- ...eredDictionary+Elements.SubSequence.swift} | 20 +++++++++++++++++++ ...swift => OrderedDictionary+Elements.swift} | 2 ++ .../OrderedDictionary+Values.swift | 19 ++++++++++++++++++ .../OrderedSet/OrderedSet+Descriptions.swift | 4 ++-- .../OrderedSet/OrderedSet+SubSequence.swift | 18 +++++++++++++++++ .../OrderedSet/OrderedSet+UnorderedView.swift | 2 +- .../OrderedDictionary+Elements Tests.swift | 14 +++++++++++++ .../OrderedDictionary+Values Tests.swift | 12 +++++++++++ .../OrderedSet/OrderedSetTests.swift | 12 +++++++++++ 11 files changed, 103 insertions(+), 5 deletions(-) rename Sources/OrderedCollections/OrderedDictionary/{OrderedDictionary+Elements+SubSequence.swift => OrderedDictionary+Elements.SubSequence.swift} (95%) rename Sources/OrderedCollections/OrderedDictionary/{OrderedDictionary.Elements.swift => OrderedDictionary+Elements.swift} (99%) diff --git a/Sources/OrderedCollections/HashTable/_HashTable+Testing.swift b/Sources/OrderedCollections/HashTable/_HashTable+Testing.swift index f27006fa..16dc185f 100644 --- a/Sources/OrderedCollections/HashTable/_HashTable+Testing.swift +++ b/Sources/OrderedCollections/HashTable/_HashTable+Testing.swift @@ -10,6 +10,7 @@ //===----------------------------------------------------------------------===// extension _HashTable.Bucket: CustomStringConvertible { + // A textual representation of this instance. public var description: String { "Bucket(@\(offset))"} } diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Descriptions.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Descriptions.swift index 5598d2f5..fede81ec 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Descriptions.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Descriptions.swift @@ -22,10 +22,10 @@ extension OrderedDictionary: CustomDebugStringConvertible { /// A textual representation of this instance, suitable for debugging. public var debugDescription: String { _dictionaryDescription( - for: self.elements, debug: true, typeName: _debugTypeName()) + for: self.elements, debug: true, typeName: Self._debugTypeName()) } - internal func _debugTypeName() -> String { + internal static func _debugTypeName() -> String { "OrderedDictionary<\(Key.self), \(Value.self)>" } } diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements+SubSequence.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.SubSequence.swift similarity index 95% rename from Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements+SubSequence.swift rename to Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.SubSequence.swift index 67ff671c..64313fea 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements+SubSequence.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.SubSequence.swift @@ -9,6 +9,8 @@ // //===----------------------------------------------------------------------===// +import _CollectionsUtilities + extension OrderedDictionary.Elements { /// A collection that represents a contiguous slice of an ordered dictionary. /// @@ -35,6 +37,24 @@ extension OrderedDictionary.Elements.SubSequence: Sendable where Key: Sendable, Value: Sendable {} #endif +extension OrderedDictionary.Elements.SubSequence: CustomStringConvertible { + // A textual representation of this instance. + public var description: String { + _dictionaryDescription(for: self) + } +} + +extension OrderedDictionary.Elements.SubSequence: CustomDebugStringConvertible { + /// A textual representation of this instance, suitable for debugging. + public var debugDescription: String { + _dictionaryDescription( + for: self, + debug: true, + typeName: "\(OrderedDictionary._debugTypeName()).Elements.SubSequence" + ) + } +} + extension OrderedDictionary.Elements.SubSequence { /// A read-only collection view containing the keys in this slice. /// diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.Elements.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift similarity index 99% rename from Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.Elements.swift rename to Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift index a759aaef..39c4fb1d 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.Elements.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift @@ -333,12 +333,14 @@ extension OrderedDictionary.Elements: RandomAccessCollection { } extension OrderedDictionary.Elements: CustomStringConvertible { + // A textual representation of this instance. public var description: String { _base.description } } extension OrderedDictionary.Elements: CustomDebugStringConvertible { + /// A textual representation of this instance, suitable for debugging. public var debugDescription: String { _dictionaryDescription( for: self, diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Values.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Values.swift index 5945feb8..013badd9 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Values.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Values.swift @@ -9,6 +9,8 @@ // //===----------------------------------------------------------------------===// +import _CollectionsUtilities + extension OrderedDictionary { /// A view of an ordered dictionary's values as a standalone collection. @frozen @@ -29,6 +31,23 @@ extension OrderedDictionary.Values: Sendable where Key: Sendable, Value: Sendable {} #endif +extension OrderedDictionary.Values: CustomStringConvertible { + // A textual representation of this instance. + public var description: String { + _arrayDescription(for: self) + } +} + +extension OrderedDictionary.Values: CustomDebugStringConvertible { + /// A textual representation of this instance, suitable for debugging. + public var debugDescription: String { + _arrayDescription( + for: self, + debug: true, + typeName: "OrderedDictionary<\(Key.self), \(Value.self)>.Keys") + } +} + extension OrderedDictionary.Values { /// A read-only view of the contents of this collection as an array value. /// diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Descriptions.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Descriptions.swift index 31c516b6..3e405668 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Descriptions.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Descriptions.swift @@ -22,10 +22,10 @@ extension OrderedSet: CustomDebugStringConvertible { /// A textual representation of this instance, suitable for debugging. public var debugDescription: String { _arrayDescription( - for: self, debug: true, typeName: _debugTypeName()) + for: self, debug: true, typeName: Self._debugTypeName()) } - internal func _debugTypeName() -> String { + internal static func _debugTypeName() -> String { "OrderedSet<\(Element.self)>" } } diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+SubSequence.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+SubSequence.swift index e77bd27e..b21262d2 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+SubSequence.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+SubSequence.swift @@ -53,6 +53,24 @@ extension OrderedSet.SubSequence { } } +extension OrderedSet.SubSequence: CustomStringConvertible { + // A textual representation of this instance. + public var description: String { + _arrayDescription(for: self) + } +} + +extension OrderedSet.SubSequence: CustomDebugStringConvertible { + /// A textual representation of this instance, suitable for debugging. + public var debugDescription: String { + _arrayDescription( + for: self, + debug: true, + typeName: "\(OrderedSet._debugTypeName()).SubSequence" + ) + } +} + extension OrderedSet.SubSequence: Sequence { // A type representing the collection’s elements. public typealias Element = OrderedSet.Element diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+UnorderedView.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+UnorderedView.swift index 129d9b66..02c980ee 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+UnorderedView.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+UnorderedView.swift @@ -81,7 +81,7 @@ extension OrderedSet.UnorderedView: CustomDebugStringConvertible { _arrayDescription( for: _base, debug: true, - typeName: "\(_base._debugTypeName()).UnorderedView") + typeName: "\(OrderedSet._debugTypeName()).UnorderedView") } } diff --git a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Elements Tests.swift b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Elements Tests.swift index ae07e1e6..8ac1c4b1 100644 --- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Elements Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Elements Tests.swift @@ -108,6 +108,20 @@ class OrderedDictionaryElementsTests: CollectionTestCase { "OrderedDictionary.Elements([0: 1, 2: 3, 4: 5])") } + func test_SubSequence_descriptions() { + let d: OrderedDictionary = [ + "a": 1, + "b": 2 + ] + + let s = d.elements[0 ..< 1] + + expectEqual(s.description, "[a: 1]") + expectEqual( + s.debugDescription, + "OrderedDictionary.Elements.SubSequence([\"a\": 1])") + } + func test_customReflectable() { do { let d: OrderedDictionary = [1: 2, 3: 4, 5: 6] diff --git a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Values Tests.swift b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Values Tests.swift index d10c1528..d45e8059 100644 --- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Values Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Values Tests.swift @@ -25,6 +25,18 @@ class OrderedDictionaryValueTests: CollectionTestCase { expectEqualElements(d.values, [1, 2, 3, 4]) } + func test_descriptions() { + let d: OrderedDictionary = [ + "a": 1, + "b": 2 + ] + + expectEqual(d.values.description, "[1, 2]") + expectEqual( + d.values.debugDescription, + "OrderedDictionary.Keys([1, 2])") + } + func test_values_RandomAccessCollection() { withEvery("count", in: 0 ..< 30) { count in let keys = 0 ..< count diff --git a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift index fbec54fa..02480b78 100644 --- a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift +++ b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift @@ -152,6 +152,18 @@ class OrderedSetTests: CollectionTestCase { expectEqual(c.debugDescription, "OrderedSet([0, 1, 2, 3, 4])") } + func test_SubSequence_descriptions() { + let s: OrderedSet = [0, 1, 2, 3] + + let slice = s[1 ..< 3] + + expectEqual(slice.description, "[1, 2]") + expectEqual( + slice.debugDescription, + "OrderedSet.SubSequence([1, 2])") + + } + func test_customReflectable() { do { let set: OrderedSet = [1, 2, 3] From c12b454da138416aa3c7aa97ca46c36d4a1ca918 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 20 Oct 2022 13:29:33 -0700 Subject: [PATCH 04/39] [Heap] Add missing Custom[Debug]StringConvertable conformances, review existing ones Add `Custom[Debug]StringConvertible` conformance on `Heap`. --- Sources/HeapModule/Heap+Descriptions.swift | 25 ++++++++++++++++++++++ Tests/HeapTests/HeapTests.swift | 10 +++++++++ 2 files changed, 35 insertions(+) create mode 100644 Sources/HeapModule/Heap+Descriptions.swift diff --git a/Sources/HeapModule/Heap+Descriptions.swift b/Sources/HeapModule/Heap+Descriptions.swift new file mode 100644 index 00000000..12edec3d --- /dev/null +++ b/Sources/HeapModule/Heap+Descriptions.swift @@ -0,0 +1,25 @@ +//===----------------------------------------------------------------------===// +// +// 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 Heap: CustomStringConvertible { + /// A textual representation of this instance. + public var description: String { + "Heap<\(Element.self)>(count: \(count))" + } +} + +extension Heap: CustomDebugStringConvertible { + /// A textual representation of this instance, suitable for debugging. + public var debugDescription: String { + description + } +} + diff --git a/Tests/HeapTests/HeapTests.swift b/Tests/HeapTests/HeapTests.swift index 45792c7e..85d1f762 100644 --- a/Tests/HeapTests/HeapTests.swift +++ b/Tests/HeapTests/HeapTests.swift @@ -62,6 +62,16 @@ final class HeapTests: CollectionTestCase { expectEqual(heap.count, 1) } + func test_descriptions() { + let a: Heap = [] + expectEqual(a.description, "Heap(count: 0)") + expectEqual(a.debugDescription, "Heap(count: 0)") + + let b: Heap = [1, 2] + expectEqual(b.description, "Heap(count: 2)") + expectEqual(b.debugDescription, "Heap(count: 2)") + } + func test_unordered() { let heap = Heap((1...10)) expectEqual(Set(heap.unordered), Set(1...10)) From 9cd030f21e7c7f1895d8d64f6a7413ddcda390d1 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 20 Oct 2022 13:30:07 -0700 Subject: [PATCH 05/39] [BitSet] Add missing Custom[Debug]StringConvertable conformances, review existing ones Add `Custom[Debug]StringConvertible` conformance on `BitSet.Index`. --- Sources/BitCollections/BitSet/BitSet.Counted.swift | 2 ++ Sources/BitCollections/BitSet/BitSet.Index.swift | 7 +++++++ Tests/BitCollectionsTests/BitSetTests.swift | 8 ++++++++ 3 files changed, 17 insertions(+) diff --git a/Sources/BitCollections/BitSet/BitSet.Counted.swift b/Sources/BitCollections/BitSet/BitSet.Counted.swift index 7129d20c..33668076 100644 --- a/Sources/BitCollections/BitSet/BitSet.Counted.swift +++ b/Sources/BitCollections/BitSet/BitSet.Counted.swift @@ -188,12 +188,14 @@ extension BitSet.Counted: Codable { } extension BitSet.Counted: CustomStringConvertible { + // A textual representation of this instance. public var description: String { _bits.description } } extension BitSet.Counted: CustomDebugStringConvertible { + /// A textual representation of this instance, suitable for debugging. public var debugDescription: String { _bits._debugDescription(typeName: "BitSet.Counted") } diff --git a/Sources/BitCollections/BitSet/BitSet.Index.swift b/Sources/BitCollections/BitSet/BitSet.Index.swift index 35b7dd89..108e3206 100644 --- a/Sources/BitCollections/BitSet/BitSet.Index.swift +++ b/Sources/BitCollections/BitSet/BitSet.Index.swift @@ -50,6 +50,13 @@ extension BitSet.Index: CustomStringConvertible { } } +extension BitSet.Index: CustomDebugStringConvertible { + // A textual representation of this instance, suitable for debugging. + public var debugDescription: String { + "BitSet.Index(\(_value))" + } +} + extension BitSet.Index: Equatable { /// Returns a Boolean value indicating whether two values are equal. /// diff --git a/Tests/BitCollectionsTests/BitSetTests.swift b/Tests/BitCollectionsTests/BitSetTests.swift index dc6599af..aceead6a 100644 --- a/Tests/BitCollectionsTests/BitSetTests.swift +++ b/Tests/BitCollectionsTests/BitSetTests.swift @@ -1404,6 +1404,14 @@ final class BitSetTest: CollectionTestCase { expectEqual("\(String(reflecting: c))", "BitSet([23, 652, 892, 19230])") } + func test_index_descriptions() { + let a: BitSet = [3, 6, 8] + let i = a.startIndex + + expectEqual(i.description, "3") + expectEqual(i.debugDescription, "BitSet.Index(3)") + } + func test_mirror() { func check(_ v: T) -> String { var str = "" From ab750075a2283a5d5199248149f0b89b71b26683 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 20 Oct 2022 13:32:04 -0700 Subject: [PATCH 06/39] [PersistentCollections] Add missing Custom[Debug]StringConvertable conformances, review existing ones Add `Custom[Debug]StringConformance` conformances on: - `PersistentDictionary.Keys` - `PersistentDictionary.Values` - `PersistentDictionary.Index` - `PersistentSet.Index` --- .../PersistentDictionary+Collection.swift | 8 +++ .../PersistentDictionary+Descriptions.swift | 6 ++- .../PersistentDictionary+Keys.swift | 19 +++++++ .../PersistentDictionary+Values.swift | 19 +++++++ .../PersistentSet+Collection.swift | 8 +++ .../PersistentDictionary Tests.swift | 49 ++++++++++--------- .../PersistentDictionary.Keys Tests.swift | 47 ++++++++++++++++++ .../PersistentDictionary.Values Tests.swift | 41 ++++++++++++++++ .../PersistentSet Tests.swift | 34 +++++++++++++ 9 files changed, 205 insertions(+), 26 deletions(-) create mode 100644 Tests/PersistentCollectionsTests/PersistentDictionary.Keys Tests.swift create mode 100644 Tests/PersistentCollectionsTests/PersistentDictionary.Values Tests.swift diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Collection.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Collection.swift index a3a0eab6..0f71e296 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Collection.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Collection.swift @@ -64,11 +64,19 @@ extension PersistentDictionary.Index: Comparable { } extension PersistentDictionary.Index: CustomStringConvertible { + // A textual representation of this instance. public var description: String { _path.description } } +extension PersistentDictionary.Index: CustomDebugStringConvertible { + /// A textual representation of this instance, suitable for debugging. + public var debugDescription: String { + _path.description + } +} + extension PersistentDictionary: BidirectionalCollection { @inlinable public var isEmpty: Bool { diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Descriptions.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Descriptions.swift index c14a3284..6e16251e 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Descriptions.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Descriptions.swift @@ -12,18 +12,20 @@ import _CollectionsUtilities extension PersistentDictionary: CustomStringConvertible { + // A textual representation of this instance. public var description: String { _dictionaryDescription(for: self) } } extension PersistentDictionary: CustomDebugStringConvertible { + /// A textual representation of this instance, suitable for debugging. public var debugDescription: String { _dictionaryDescription( - for: self, debug: true, typeName: _debugTypeName()) + for: self, debug: true, typeName: Self._debugTypeName()) } - internal func _debugTypeName() -> String { + internal static func _debugTypeName() -> String { "PersistentDictionary<\(Key.self), \(Value.self)>" } } diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Keys.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Keys.swift index 7928893c..abc5da0f 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Keys.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Keys.swift @@ -39,6 +39,25 @@ extension PersistentDictionary.Keys: Sendable where Key: Sendable, Value: Sendable {} #endif +extension PersistentDictionary.Keys: _UniqueCollection {} + +extension PersistentDictionary.Keys: CustomStringConvertible { + // A textual representation of this instance. + public var description: String { + _arrayDescription(for: self) + } +} + +extension PersistentDictionary.Keys: CustomDebugStringConvertible { + /// A textual representation of this instance, suitable for debugging. + public var debugDescription: String { + _arrayDescription( + for: self, + debug: true, + typeName: "\(PersistentDictionary._debugTypeName()).Keys") + } +} + extension PersistentDictionary.Keys: Sequence { public typealias Element = Key diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Values.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Values.swift index 603bd801..454e8544 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Values.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Values.swift @@ -9,6 +9,8 @@ // //===----------------------------------------------------------------------===// +import _CollectionsUtilities + extension PersistentDictionary { /// A view of a dictionary’s values. @frozen @@ -53,6 +55,23 @@ extension PersistentDictionary.Values: Sendable where Key: Sendable, Value: Sendable {} #endif +extension PersistentDictionary.Values: CustomStringConvertible { + // A textual representation of this instance. + public var description: String { + _arrayDescription(for: self) + } +} + +extension PersistentDictionary.Values: CustomDebugStringConvertible { + /// A textual representation of this instance, suitable for debugging. + public var debugDescription: String { + _arrayDescription( + for: self, + debug: true, + typeName: "\(PersistentDictionary._debugTypeName()).Values") + } +} + extension PersistentDictionary.Values: Sequence { public typealias Element = Value diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+Collection.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+Collection.swift index 98cf0ffe..0d832613 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+Collection.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+Collection.swift @@ -65,11 +65,19 @@ extension PersistentSet.Index: Hashable { } extension PersistentSet.Index: CustomStringConvertible { + // A textual representation of this instance. public var description: String { _path.description } } +extension PersistentSet.Index: CustomDebugStringConvertible { + /// A textual representation of this instance, suitable for debugging. + public var debugDescription: String { + description + } +} + extension PersistentSet: BidirectionalCollection { @inlinable public var isEmpty: Bool { diff --git a/Tests/PersistentCollectionsTests/PersistentDictionary Tests.swift b/Tests/PersistentCollectionsTests/PersistentDictionary Tests.swift index d2855ed0..738734f5 100644 --- a/Tests/PersistentCollectionsTests/PersistentDictionary Tests.swift +++ b/Tests/PersistentCollectionsTests/PersistentDictionary Tests.swift @@ -264,30 +264,6 @@ class PersistentDictionaryTests: CollectionTestCase { checkBidirectionalCollection(d, expectedContents: Array(d), by: ==) } - func test_Keys_BidirectionalCollection_fixtures() { - withEachFixture { fixture in - withLifetimeTracking { tracker in - let (d, ref) = tracker.persistentDictionary(for: fixture) - checkBidirectionalCollection( - d.keys, - expectedContents: ref.map { $0.key }, - by: ==) - } - } - } - - func test_Values_BidirectionalCollection_fixtures() { - withEachFixture { fixture in - withLifetimeTracking { tracker in - let (d, ref) = tracker.persistentDictionary(for: fixture) - checkBidirectionalCollection( - d.values, - expectedContents: ref.map { $0.value }, - by: ==) - } - } - } - #if swift(>=5.6) @available(macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4, *) struct FancyDictionaryKey: CodingKeyRepresentable, Hashable, Codable { @@ -510,6 +486,31 @@ class PersistentDictionaryTests: CollectionTestCase { } + func test_index_descriptions() { + let a: PersistentDictionary = [ + RawCollider(1, "1"): 1, + RawCollider(2, "21"): 2, + RawCollider(3, "22"): 3, + ] + + let i = a.startIndex + expectEqual(i.description, "@[0]") + expectEqual(i.debugDescription, "@[0]") + + let j = a.index(i, offsetBy: 1) + expectEqual(j.description, "@.0[0]") + expectEqual(j.debugDescription, "@.0[0]") + + let k = a.index(j, offsetBy: 1) + expectEqual(k.description, "@.0[1]") + expectEqual(k.debugDescription, "@.0[1]") + + let end = a.endIndex + expectEqual(end.description, "@.end(1)") + expectEqual(end.debugDescription, "@.end(1)") + } + + func test_updateValueForKey_fixtures() { withEachFixture { fixture in withEvery("isShared", in: [false, true]) { isShared in diff --git a/Tests/PersistentCollectionsTests/PersistentDictionary.Keys Tests.swift b/Tests/PersistentCollectionsTests/PersistentDictionary.Keys Tests.swift new file mode 100644 index 00000000..2a49a413 --- /dev/null +++ b/Tests/PersistentCollectionsTests/PersistentDictionary.Keys Tests.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 XCTest +import _CollectionsTestSupport +import PersistentCollections + +class PersistentDictionaryKeysTests: CollectionTestCase { + func test_BidirectionalCollection_fixtures() { + withEachFixture { fixture in + withLifetimeTracking { tracker in + let (d, ref) = tracker.persistentDictionary(for: fixture) + checkBidirectionalCollection( + d.keys, + expectedContents: ref.map { $0.key }, + by: ==) + } + } + } + + func test_descriptions() { + let d: PersistentDictionary = [ + "a": 1, + "b": 2 + ] + + if d.first!.key == "a" { + expectEqual(d.keys.description, "[a, b]") + expectEqual( + d.keys.debugDescription, + "PersistentDictionary.Keys([\"a\", \"b\"])") + } else { + expectEqual(d.keys.description, "[b, a]") + expectEqual( + d.keys.debugDescription, + "PersistentDictionary.Keys([\"b\", \"a\"])") + } + } +} diff --git a/Tests/PersistentCollectionsTests/PersistentDictionary.Values Tests.swift b/Tests/PersistentCollectionsTests/PersistentDictionary.Values Tests.swift new file mode 100644 index 00000000..76265e4d --- /dev/null +++ b/Tests/PersistentCollectionsTests/PersistentDictionary.Values Tests.swift @@ -0,0 +1,41 @@ +//===----------------------------------------------------------------------===// +// +// 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 +import PersistentCollections + +class PersistentDictionaryValuesTests: CollectionTestCase { + func test_BidirectionalCollection_fixtures() { + withEachFixture { fixture in + withLifetimeTracking { tracker in + let (d, ref) = tracker.persistentDictionary(for: fixture) + checkBidirectionalCollection( + d.values, + expectedContents: ref.map { $0.value }, + by: ==) + } + } + } + + func test_descriptions() { + let d: PersistentDictionary = [ + "a": 1, + "b": 2 + ] + + if d.first!.key == "a" { + expectEqual(d.values.description, "[1, 2]") + } else { + expectEqual(d.values.description, "[2, 1]") + } + } +} diff --git a/Tests/PersistentCollectionsTests/PersistentSet Tests.swift b/Tests/PersistentCollectionsTests/PersistentSet Tests.swift index 796893b0..dee8438c 100644 --- a/Tests/PersistentCollectionsTests/PersistentSet Tests.swift +++ b/Tests/PersistentCollectionsTests/PersistentSet Tests.swift @@ -75,6 +75,40 @@ class PersistentSetTests: CollectionTestCase { expectTrue(set.contains(a2)) } + func test_descriptions() { + let empty: PersistentSet = [] + expectEqual(empty.description, "[]") + expectEqual(empty.debugDescription, "PersistentSet([])") + + let a: PersistentSet = ["a"] + expectEqual(a.description, "[a]") + expectEqual(a.debugDescription, "PersistentSet([\"a\"])") + } + + func test_index_descriptions() { + let a: PersistentSet = [ + RawCollider(1, "1"), + RawCollider(2, "21"), + RawCollider(3, "22"), + ] + let i = a.startIndex + expectEqual(i.description, "@[0]") + expectEqual(i.debugDescription, "@[0]") + + let j = a.index(i, offsetBy: 1) + expectEqual(j.description, "@.0[0]") + expectEqual(j.debugDescription, "@.0[0]") + + let k = a.index(j, offsetBy: 1) + expectEqual(k.description, "@.0[1]") + expectEqual(k.debugDescription, "@.0[1]") + + let end = a.endIndex + expectEqual(end.description, "@.end(1)") + expectEqual(end.debugDescription, "@.end(1)") + + } + func test_insert_fixtures() { withEachFixture { fixture in withEvery("isShared", in: [false, true]) { isShared in From 2df7f6d3a8fe5f9bb12b5034da2e095424694d44 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 20 Oct 2022 17:15:21 -0700 Subject: [PATCH 07/39] Update xcode schemes --- .../xcschemes/Collections.xcscheme | 20 +++---------------- 1 file changed, 3 insertions(+), 17 deletions(-) diff --git a/Utils/swift-collections.xcworkspace/xcshareddata/xcschemes/Collections.xcscheme b/Utils/swift-collections.xcworkspace/xcshareddata/xcschemes/Collections.xcscheme index feefde95..390945da 100644 --- a/Utils/swift-collections.xcworkspace/xcshareddata/xcschemes/Collections.xcscheme +++ b/Utils/swift-collections.xcworkspace/xcshareddata/xcschemes/Collections.xcscheme @@ -104,20 +104,6 @@ ReferencedContainer = "container:.."> - - - - From 648aaa7f569308db113280d093798aacaa11e7c7 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 20 Oct 2022 18:18:48 -0700 Subject: [PATCH 08/39] [PersistentSet] Review, test, fix, and document binary set operations --- .../Node/_Node+Builder.swift | 27 ++++ .../Node/_Node+Storage.swift | 2 +- .../Node/_Node+Structural mapValues.swift | 14 ++ ..._Node+Structural symmetricDifference.swift | 142 +++++++++++------- .../Node/_Node+Structural union.swift | 82 +++++----- ...stentSet+SetAlgebra formIntersection.swift | 28 ++++ ...t+SetAlgebra formSymmetricDifference.swift | 33 ++++ .../PersistentSet+SetAlgebra formUnion.swift | 52 +++++++ ...ersistentSet+SetAlgebra intersection.swift | 24 ++- .../PersistentSet+SetAlgebra subtract.swift | 27 ++++ ...PersistentSet+SetAlgebra subtracting.swift | 28 ++++ ...ntSet+SetAlgebra symmetricDifference.swift | 76 ++++++++-- .../PersistentSet+SetAlgebra union.swift | 89 ++++++++--- .../PersistentSet Tests.swift | 66 ++++++++ 14 files changed, 563 insertions(+), 127 deletions(-) diff --git a/Sources/PersistentCollections/Node/_Node+Builder.swift b/Sources/PersistentCollections/Node/_Node+Builder.swift index 7a7b1ea2..56045ee5 100644 --- a/Sources/PersistentCollections/Node/_Node+Builder.swift +++ b/Sources/PersistentCollections/Node/_Node+Builder.swift @@ -331,3 +331,30 @@ extension _Node.Builder { } } } + +extension _Node.Builder { + @inlinable + internal func mapValues( + _ transform: (Element) -> Value2 + ) -> _Node.Builder { + switch kind { + case .empty: + return .empty(level) + case let .item(item, at: bucket): + let value = transform(item) + return .item(level, (item.key, value), at: bucket) + case let .node(node): + return .node(level, node.mapValues(transform)) + case let .collisionNode(node): + return .collisionNode(level, node.mapValues(transform)) + } + } + + @inlinable + internal func mapValuesToVoid() -> _Node.Builder { + if Value.self == Void.self { + return unsafeBitCast(self, to: _Node.Builder.self) + } + return mapValues { _ in () } + } +} diff --git a/Sources/PersistentCollections/Node/_Node+Storage.swift b/Sources/PersistentCollections/Node/_Node+Storage.swift index d8489fce..44308155 100644 --- a/Sources/PersistentCollections/Node/_Node+Storage.swift +++ b/Sources/PersistentCollections/Node/_Node+Storage.swift @@ -121,7 +121,7 @@ extension _Node { } @inlinable - internal mutating func hasFreeSpace(_ bytes: Int) -> Bool { + internal func hasFreeSpace(_ bytes: Int) -> Bool { bytes <= self.raw.storage.header.bytesFree } diff --git a/Sources/PersistentCollections/Node/_Node+Structural mapValues.swift b/Sources/PersistentCollections/Node/_Node+Structural mapValues.swift index e6970df5..abab98ec 100644 --- a/Sources/PersistentCollections/Node/_Node+Structural mapValues.swift +++ b/Sources/PersistentCollections/Node/_Node+Structural mapValues.swift @@ -71,4 +71,18 @@ extension _Node { return result } } + + @inlinable + internal func mapValuesToVoid( + copy: Bool = false, extraBytes: Int = 0 + ) -> _Node { + if Value.self == Void.self { + let node = unsafeBitCast(self, to: _Node.self) + guard copy || !node.hasFreeSpace(extraBytes) else { return node } + return node.copy(withFreeSpace: extraBytes) + } + let node = mapValues { _ in () } + guard !node.hasFreeSpace(extraBytes) else { return node } + return node.copy(withFreeSpace: extraBytes) + } } diff --git a/Sources/PersistentCollections/Node/_Node+Structural symmetricDifference.swift b/Sources/PersistentCollections/Node/_Node+Structural symmetricDifference.swift index a37d1ed2..b236e3e5 100644 --- a/Sources/PersistentCollections/Node/_Node+Structural symmetricDifference.swift +++ b/Sources/PersistentCollections/Node/_Node+Structural symmetricDifference.swift @@ -11,20 +11,24 @@ extension _Node { @inlinable - internal func symmetricDifference( + internal func symmetricDifference( _ level: _Level, - _ other: _Node - ) -> Builder? { - guard self.count > 0 else { return Builder(level, other) } + _ other: _Node + ) -> _Node.Builder? { + guard self.count > 0 else { + return .init(level, other.mapValuesToVoid()) + } guard other.count > 0 else { return nil } return _symmetricDifference(level, other) } @inlinable - internal func _symmetricDifference( + internal func _symmetricDifference( _ level: _Level, - _ other: _Node - ) -> Builder { + _ other: _Node + ) -> _Node.Builder { + typealias VoidNode = _Node + assert(self.count > 0 && other.count > 0) if self.raw.storage === other.raw.storage { @@ -36,7 +40,7 @@ extension _Node { return self.read { l in other.read { r in - var result: Builder = .empty(level) + var result: VoidNode.Builder = .empty(level) for (bucket, lslot) in l.itemMap { let lp = l.itemPtr(at: lslot) @@ -46,10 +50,10 @@ extension _Node { if lp.pointee.key != rp.pointee.key { let h1 = _Hash(lp.pointee.key) let h2 = _Hash(rp.pointee.key) - let child = _Node.build( + let child = VoidNode.build( level: level.descend(), - item1: lp.pointee, h1, - item2: { $0.initialize(to: rp.pointee) }, h2) + item1: (lp.pointee.key, ()), h1, + item2: { $0.initialize(to: (rp.pointee.key, ())) }, h2) result.addNewChildNode(level, child.top, at: bucket) } } @@ -60,16 +64,20 @@ extension _Node { let child = rp.pointee .removing(level.descend(), lp.pointee.key, h)?.replacement if let child = child { + let child = child.mapValuesToVoid() result.addNewChildBranch(level, child, at: bucket) } else { - let child2 = rp.pointee.inserting(level.descend(), lp.pointee, h) - assert(child2.inserted) - result.addNewChildNode(level, child2.node, at: bucket) + var child2 = rp.pointee + .mapValuesToVoid( + copy: true, extraBytes: VoidNode.spaceForNewItem) + let r = child2.insert(level.descend(), (lp.pointee.key, ()), h) + assert(r.inserted) + result.addNewChildNode(level, child2, at: bucket) } } else { - result.addNewItem(level, lp.pointee, at: bucket) + result.addNewItem(level, (lp.pointee.key, ()), at: bucket) } } @@ -80,14 +88,17 @@ extension _Node { let rp = r.itemPtr(at: rslot) let h = _Hash(rp.pointee.key) let child = lp.pointee + .mapValuesToVoid() .removing(level.descend(), rp.pointee.key, h)?.replacement if let child = child { result.addNewChildBranch(level, child, at: bucket) } else { - let child2 = lp.pointee.inserting(level.descend(), rp.pointee, h) - assert(child2.inserted) - result.addNewChildNode(level, child2.node, at: bucket) + var child2 = lp.pointee.mapValuesToVoid( + copy: true, extraBytes: VoidNode.spaceForNewItem) + let r2 = child2.insert(level.descend(), (rp.pointee.key, ()), h) + assert(r2.inserted) + result.addNewChildNode(level, child2, at: bucket) } } else if r.childMap.contains(bucket) { @@ -97,18 +108,20 @@ extension _Node { result.addNewChildBranch(level, b, at: bucket) } else { - result.addNewChildNode(level, lp.pointee, at: bucket) + result.addNewChildNode( + level, lp.pointee.mapValuesToVoid(), at: bucket) } } let seen = l.itemMap.union(l.childMap) for (bucket, rslot) in r.itemMap { guard !seen.contains(bucket) else { continue } - result.addNewItem(level, r[item: rslot], at: bucket) + result.addNewItem(level, (r[item: rslot].key, ()), at: bucket) } for (bucket, rslot) in r.childMap { guard !seen.contains(bucket) else { continue } - result.addNewChildNode(level, r[child: rslot], at: bucket) + result.addNewChildNode( + level, r[child: rslot].mapValuesToVoid(), at: bucket) } return result } @@ -116,10 +129,10 @@ extension _Node { } @inlinable @inline(never) - internal func _symmetricDifference_slow( + internal func _symmetricDifference_slow( _ level: _Level, - _ other: _Node - ) -> Builder { + _ other: _Node + ) -> _Node.Builder { switch (self.isCollisionNode, other.isCollisionNode) { case (true, true): return self._symmetricDifference_slow_both(level, other) @@ -131,26 +144,27 @@ extension _Node { } @inlinable - internal func _symmetricDifference_slow_both( + internal func _symmetricDifference_slow_both( _ level: _Level, - _ other: _Node - ) -> Builder { - read { l in + _ other: _Node + ) -> _Node.Builder { + typealias VoidNode = _Node + return read { l in other.read { r in guard l.collisionHash == r.collisionHash else { - let node = _Node.build( + let node = VoidNode.build( level: level, - child1: self, l.collisionHash, - child2: other, r.collisionHash) + child1: self.mapValuesToVoid(), l.collisionHash, + child2: other.mapValuesToVoid(), r.collisionHash) return .node(level, node) } - var result: Builder = .empty(level) + var result: VoidNode.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(level, lp.pointee, l.collisionHash) + result.addNewCollision(level, (lp.pointee.key, ()), l.collisionHash) } } // FIXME: Consider remembering slots of shared items in r by @@ -160,7 +174,7 @@ extension _Node { let rp = r.itemPtr(at: rs) let include = !litems.contains(where: { $0.key == rp.pointee.key }) if include { - result.addNewCollision(level, rp.pointee, r.collisionHash) + result.addNewCollision(level, (rp.pointee.key, ()), r.collisionHash) } } return result @@ -169,13 +183,14 @@ extension _Node { } @inlinable - internal func _symmetricDifference_slow_left( + internal func _symmetricDifference_slow_left( _ level: _Level, - _ other: _Node - ) -> Builder { + _ other: _Node + ) -> _Node.Builder { + typealias VoidNode = _Node // `self` is a collision node on a compressed path. The other tree might // have the same set of collisions, just expanded a bit deeper. - read { l in + return read { l in other.read { r in assert(l.isCollisionNode && !r.isCollisionNode) let bucket = l.collisionHash[level] @@ -184,57 +199,68 @@ extension _Node { let rp = r.itemPtr(at: rslot) let rh = _Hash(rp.pointee.key) guard rh == l.collisionHash else { - var copy = other.copy(withFreeSpace: _Node.spaceForSpawningChild) + var copy = other.mapValuesToVoid( + copy: true, extraBytes: VoidNode.spaceForSpawningChild) let item = copy.removeItem(at: bucket, rslot) - let child = _Node.build( + let child = VoidNode.build( level: level.descend(), - item1: { $0.initialize(to: item) }, rh, - child2: self, l.collisionHash) + item1: { $0.initialize(to: (item.key, ())) }, rh, + child2: self.mapValuesToVoid(), 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]) + var node = other.mapValuesToVoid(copy: true) + node.replaceItem( + at: bucket, rslot, + with: (litems[1 &- li].key, ())) return .node(level, node) } let lslot = _Slot(litems.count &- 1 &- li) - var child = self.copy() + var child = self.mapValuesToVoid(copy: true) _ = child.removeItem(at: .invalid, lslot) if other.hasSingletonItem { // Compression return .collisionNode(level, child) } - var node = other.copy(withFreeSpace: _Node.spaceForSpawningChild) + var node = other.mapValuesToVoid( + copy: true, extraBytes: VoidNode.spaceForSpawningChild) _ = node.removeItem(at: bucket, rslot) node.insertChild(child, bucket) return .node(level, node) } if other.hasSingletonItem { // Compression - let copy = self.copyNodeAndAppendCollision { - $0.initialize(to: r[item: .zero]) - } - return .collisionNode(level, copy.node) + var copy = self.mapValuesToVoid( + copy: true, extraBytes: VoidNode.spaceForNewItem) + _ = copy.ensureUniqueAndAppendCollision( + isUnique: true, + (r[item: .zero].key, ())) + return .collisionNode(level, copy) } - var node = other.copy(withFreeSpace: _Node.spaceForSpawningChild) + var node = other.mapValuesToVoid( + copy: true, extraBytes: VoidNode.spaceForSpawningChild) let item = node.removeItem(at: bucket, rslot) - let child = self.copyNodeAndAppendCollision { - $0.initialize(to: item) - } - node.insertChild(child.node, bucket) + var child = self.mapValuesToVoid( + copy: true, extraBytes: VoidNode.spaceForNewItem) + _ = child.ensureUniqueAndAppendCollision( + isUnique: true, (item.key, ())) + node.insertChild(child, bucket) return .node(level, node) } if r.childMap.contains(bucket) { let rslot = r.childMap.slot(of: bucket) let rp = r.childPtr(at: rslot) let child = rp.pointee._symmetricDifference(level.descend(), self) - return other.replacingChild(level, at: bucket, rslot, with: child) + return other + .mapValuesToVoid() + .replacingChild(level, at: bucket, rslot, with: child) } - var node = other.copy(withFreeSpace: _Node.spaceForNewChild) - node.insertChild(self, bucket) + var node = other + .mapValuesToVoid(copy: true, extraBytes: VoidNode.spaceForNewChild) + node.insertChild(self.mapValuesToVoid(), bucket) return .node(level, node) } } diff --git a/Sources/PersistentCollections/Node/_Node+Structural union.swift b/Sources/PersistentCollections/Node/_Node+Structural union.swift index a504505e..4f0b3b21 100644 --- a/Sources/PersistentCollections/Node/_Node+Structural union.swift +++ b/Sources/PersistentCollections/Node/_Node+Structural union.swift @@ -11,23 +11,23 @@ extension _Node { @inlinable - internal func union( + internal func union( _ level: _Level, - _ other: _Node - ) -> (copied: Bool, node: _Node) { - guard self.count > 0 else { return (true, other) } - guard other.count > 0 else { return (false, self) } + _ other: _Node + ) -> (copied: Bool, node: _Node) { + guard self.count > 0 else { return (true, other.mapValuesToVoid()) } + guard other.count > 0 else { return (false, self.mapValuesToVoid()) } if level.isAtRoot, self.hasSingletonItem { // In this special case, the root node may turn into a collision node // during the merge process. Prevent this from causing issues below by // handling it up front. return self.read { l in let lp = l.itemPtr(at: .zero) - var copy = other + var copy = other.mapValuesToVoid(copy: true) let r = copy.updateValue( level, forKey: lp.pointee.key, _Hash(lp.pointee.key) ) { - $0.initialize(to: lp.pointee) + $0.initialize(to: (lp.pointee.key, ())) } if !r.inserted { UnsafeHandle.update(r.leaf) { @@ -41,12 +41,12 @@ extension _Node { } @inlinable - internal func _union( + internal func _union( _ level: _Level, - _ other: _Node - ) -> (copied: Bool, node: _Node) { + _ other: _Node + ) -> (copied: Bool, node: _Node) { if self.raw.storage === other.raw.storage { - return (false, self) + return (false, self.mapValuesToVoid()) } if self.isCollisionNode || other.isCollisionNode { @@ -55,7 +55,7 @@ extension _Node { return self.read { l in other.read { r in - var node = self + var node = self.mapValuesToVoid() var copied = false for (bucket, lslot) in l.itemMap { @@ -75,7 +75,7 @@ extension _Node { replacing: bucket, itemSlot: slot, newHash: _Hash(rp.pointee.key), - { $0.initialize(to: rp.pointee) }) + { $0.initialize(to: (rp.pointee.key, ())) }) // If we hadn't handled the singleton root node case above, // then this call would sometimes turn `node` into a collision // node on a compressed path, causing mischief. @@ -90,7 +90,8 @@ extension _Node { node.ensureUnique( isUnique: copied, withFreeSpace: _Node.spaceForSpawningChild) let item = node.removeItem(at: bucket) - let r = rp.pointee.inserting(level.descend(), item, _Hash(item.key)) + let r = rp.pointee.mapValuesToVoid() + .inserting(level.descend(), (item.key, ()), _Hash(item.key)) node.insertChild(r.node, bucket) copied = true } @@ -102,7 +103,8 @@ extension _Node { let rslot = r.itemMap.slot(of: bucket) let rp = r.itemPtr(at: rslot) let h = _Hash(rp.pointee.key) - let r = l[child: lslot].inserting(level.descend(), rp.pointee, h) + let r = l[child: lslot].mapValuesToVoid() + .inserting(level.descend(), (rp.pointee.key, ()), h) guard r.inserted else { // Nothing to do continue @@ -134,7 +136,7 @@ extension _Node { for (bucket, _) in r.itemMap.subtracting(seen) { let rslot = r.itemMap.slot(of: bucket) node.ensureUniqueAndInsertItem( - isUnique: copied, r[item: rslot], at: bucket) + isUnique: copied, (r[item: rslot].key, ()), at: bucket) copied = true } for (bucket, _) in r.childMap.subtracting(seen) { @@ -142,7 +144,7 @@ extension _Node { node.ensureUnique( isUnique: copied, withFreeSpace: _Node.spaceForNewChild) copied = true - node.insertChild(r[child: rslot], bucket) + node.insertChild(r[child: rslot].mapValuesToVoid(), bucket) } return (copied, node) @@ -151,30 +153,30 @@ extension _Node { } @inlinable @inline(never) - internal func _union_slow( + internal func _union_slow( _ level: _Level, - _ other: _Node - ) -> (copied: Bool, node: _Node) { + _ other: _Node + ) -> (copied: Bool, node: _Node) { let lc = self.isCollisionNode let rc = other.isCollisionNode if lc && rc { return read { l in other.read { r in guard l.collisionHash == r.collisionHash else { - let node = _Node.build( + let node = _Node.build( level: level, - child1: self, l.collisionHash, - child2: other, r.collisionHash) + child1: self.mapValuesToVoid(), l.collisionHash, + child2: other.mapValuesToVoid(), r.collisionHash) return (true, node) } var copied = false - var node = self + var node = self.mapValuesToVoid() let litems = l.reverseItems for rs: _Slot in stride(from: .zero, to: r.itemsEndSlot, by: 1) { let p = r.itemPtr(at: rs) if !litems.contains(where: { $0.key == p.pointee.key }) { _ = node.ensureUniqueAndAppendCollision( - isUnique: copied, p.pointee) + isUnique: copied, (p.pointee.key, ())) copied = true } } @@ -199,24 +201,25 @@ extension _Node { r.hasSingletonItem && l.reverseItems.contains(where: { $0.key == rp.pointee.key }) { - return (false, self) + return (false, self.mapValuesToVoid()) } - let node = other.copyNodeAndPushItemIntoNewChild( - level: level, self, at: bucket, itemSlot: rslot) + let node = other.mapValuesToVoid().copyNodeAndPushItemIntoNewChild( + level: level, self.mapValuesToVoid(), at: bucket, itemSlot: rslot) return (true, node) } if r.childMap.contains(bucket) { let rslot = r.childMap.slot(of: bucket) let res = self._union(level.descend(), r[child: rslot]) - var node = other.copy() + var node = other.mapValuesToVoid(copy: true) let delta = node.replaceChild(at: bucket, rslot, with: res.node) assert(delta >= 0) return (true, node) } - var node = other.copy(withFreeSpace: _Node.spaceForNewChild) - node.insertChild(self, bucket) + var node = other.mapValuesToVoid( + copy: true, extraBytes: _Node.spaceForNewChild) + node.insertChild(self.mapValuesToVoid(), bucket) return (true, node) } } @@ -224,28 +227,29 @@ extension _Node { assert(rc) // `other` is a collision node on a compressed path. - return read { l in - other.read { r in + return read { l -> (copied: Bool, node: _Node) in + other.read { r -> (copied: Bool, node: _Node) in let bucket = r.collisionHash[level] if l.itemMap.contains(bucket) { 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) + let node = self.mapValuesToVoid().copyNodeAndPushItemIntoNewChild( + level: level, other.mapValuesToVoid(), at: bucket, itemSlot: lslot) return (true, node) } if l.childMap.contains(bucket) { let lslot = l.childMap.slot(of: bucket) let child = l[child: lslot]._union(level.descend(), other) - guard child.copied else { return (false, self) } - var node = self.copy() + guard child.copied else { return (false, self.mapValuesToVoid()) } + var node = self.mapValuesToVoid(copy: true) let delta = node.replaceChild(at: bucket, lslot, with: child.node) assert(delta > 0) // If we didn't add an item, why did we copy? return (true, node) } - var node = self.copy(withFreeSpace: _Node.spaceForNewChild) - node.insertChild(other, bucket) + var node = self.mapValuesToVoid( + copy: true, extraBytes: _Node.spaceForNewChild) + node.insertChild(other.mapValuesToVoid(), bucket) return (true, node) } } diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra formIntersection.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra formIntersection.swift index 20012a86..466169dc 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra formIntersection.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra formIntersection.swift @@ -22,6 +22,7 @@ extension PersistentSet { /// identities, or by some other means.) /// /// - Parameter other: An arbitrary set of elements. + /// /// - Complexity: Expected complexity is O(`self.count` + `other.count`) in /// the worst case, if `Element` properly implements hashing. /// However, the implementation is careful to make the best use of @@ -32,6 +33,20 @@ extension PersistentSet { self = intersection(other) } + /// Removes the elements of this set that aren't also in the given keys view + /// of a persistent dictionary. + /// + /// The result will only contain instances that were originally in `self`. + /// (This matters if equal members can be distinguished by comparing their + /// identities, or by some other means.) + /// + /// - Parameter other: The keys view of a persistent dictionary. + /// + /// - Complexity: Expected complexity is O(`self.count` + `other.count`) in + /// the worst case, if `Element` properly implements hashing. + /// However, the implementation is careful to make the best use of + /// hash tree structure to minimize work when possible, e.g. by linking + /// parts of the input trees directly into the result. @inlinable public mutating func formIntersection( _ other: PersistentDictionary.Keys @@ -39,6 +54,19 @@ extension PersistentSet { self = intersection(other) } + /// Removes the elements of this set that aren't also in the given sequence. + /// + /// var a: PersistentSet = [1, 2, 3, 4] + /// let b = [0, 2, 4, 6] + /// a.formIntersection(b) + /// // `a` is now some permutation of `[2, 4]` + /// + /// The result will only contain instances that were originally in `self`. + /// (This matters if equal members can be distinguished by comparing their + /// identities, or by some other means.) + /// + /// - Parameter other: An arbitrary finite sequence of items, + /// possibly containing duplicate values. @inlinable public mutating func formIntersection( _ other: S diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra formSymmetricDifference.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra formSymmetricDifference.swift index 4969bd49..cf1b6cdd 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra formSymmetricDifference.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra formSymmetricDifference.swift @@ -19,6 +19,7 @@ extension PersistentSet { /// // `a` is now some permutation of `[0, 1, 3, 6]` /// /// - Parameter other: An arbitrary set of elements. + /// /// - Complexity: Expected complexity is O(`self.count` + `other.count`) in /// the worst case, if `Element` properly implements hashing. /// However, the implementation is careful to make the best use of @@ -29,6 +30,38 @@ extension PersistentSet { self = symmetricDifference(other) } + /// Replace this set with the elements contained in this set or the given + /// keys view of a persistent dictionary, but not both. + /// + /// var a: PersistentSet = [1, 2, 3, 4] + /// let b: PersistentDictionary = [0: "a", 2: "b", 4: "c", 6: "d"] + /// a.formSymmetricDifference(b.keys) + /// // `a` is now some permutation of `[0, 1, 3, 6]` + /// + /// - Parameter other: An arbitrary set of elements. + /// + /// - Complexity: Expected complexity is O(`self.count` + `other.count`) in + /// the worst case, if `Element` properly implements hashing. + /// However, the implementation is careful to make the best use of + /// hash tree structure to minimize work when possible, e.g. by linking + /// parts of the input trees directly into the result. + @inlinable + public mutating func formSymmetricDifference( + _ other: __owned PersistentDictionary.Keys + ) { + self = symmetricDifference(other) + } + + /// Replace this set with the elements contained in this set or the given + /// sequence, but not both. + /// + /// var a: PersistentSet = [1, 2, 3, 4] + /// let b = [0, 2, 4, 6, 2, 4, 6] + /// a.formSymmetricDifference(b) + /// // `a` is now some permutation of `[0, 1, 3, 6]` + /// + /// - Parameter other: A finite sequence of elements, possibly containing + /// duplicate values. @inlinable public mutating func formSymmetricDifference(_ other: __owned S) where S.Element == Element { diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra formUnion.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra formUnion.swift index 2a3508e9..3b3dc667 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra formUnion.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra formUnion.swift @@ -23,6 +23,7 @@ extension PersistentSet { /// means.) /// /// - Parameter other: The set of elements to insert. + /// /// - Complexity: Expected complexity is O(`self.count` + `other.count`) in /// the worst case, if `Element` properly implements hashing. /// However, the implementation is careful to make the best use of @@ -33,6 +34,57 @@ extension PersistentSet { self = union(other) } + /// Adds the elements of the given keys view of a persistent dictionary + /// to this set. + /// + /// var a: PersistentSet = [1, 2, 3, 4] + /// let b: PersistentDictionary = [0: "a", 2: "b", 4: "c", 6: "d"] + /// a.formUnion(b.keys) + /// // `a` is now some permutation of `[0, 1, 2, 3, 4, 6]` + /// + /// For values that are members of both inputs, this operation preserves the + /// instances that were originally in `self`. (This matters if equal members + /// can be distinguished by comparing their identities, or by some other + /// means.) + /// + /// - Parameter other: The keys view of a persistent dictionary. + /// + /// - Complexity: Expected complexity is O(`self.count` + `other.count`) in + /// the worst case, if `Element` properly implements hashing. + /// However, the implementation is careful to make the best use of + /// hash tree structure to minimize work when possible, e.g. by linking + /// parts of the input trees directly into the result. + @inlinable + public mutating func formUnion( + _ other: __owned PersistentDictionary.Keys + ) { + self = union(other) + } + + /// Adds the elements of the given sequence to this set. + /// + /// var a: PersistentSet = [1, 2, 3, 4] + /// let b = [0, 2, 4, 6, 0, 2] + /// a.formUnion(b) + /// // `a` is now some permutation of `[0, 1, 2, 3, 4, 6]` + /// + /// For values that are members of both inputs, this operation preserves the + /// instances that were originally in `self`. (This matters if equal members + /// can be distinguished by comparing their identities, or by some other + /// means.) + /// + /// If some of the values that are missing from `self` have multiple copies + /// in `other`, then the result of this function always contains the first + /// instances in the sequence -- the second and subsequent copies are ignored. + /// + /// - Parameter other: An arbitrary finite sequence of items, + /// possibly containing duplicate values. + /// + /// - Complexity: Expected complexity is O(`self.count` + `other.count`) in + /// the worst case, if `Element` properly implements hashing. + /// However, the implementation is careful to make the best use of + /// hash tree structure to minimize work when possible, e.g. by linking + /// parts of the input trees directly into the result. @inlinable public mutating func formUnion(_ other: __owned S) where S.Element == Element { diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra intersection.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra intersection.swift index 567d3c11..e45c3a5f 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra intersection.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra intersection.swift @@ -23,6 +23,7 @@ extension PersistentSet { /// identities, or by some other means.) /// /// - Parameter other: An arbitrary set of elements. + /// /// - Complexity: Expected complexity is O(`self.count` + `other.count`) in /// the worst case, if `Element` properly implements hashing. /// However, the implementation is careful to make the best use of @@ -33,6 +34,25 @@ extension PersistentSet { _intersection(other._root) } + /// Returns a new set with the elements that are common to both this set and + /// the provided keys view of a persistent dictionary. + /// + /// var a: PersistentSet = [1, 2, 3, 4] + /// let b: PersistentDictionary = [0: "a", 2: "b", 4: "c", 6: "d"] + /// let c = a.intersection(b.keys) + /// // `c` is some permutation of `[2, 4]` + /// + /// The result will only contain instances that were originally in `self`. + /// (This matters if equal members can be distinguished by comparing their + /// identities, or by some other means.) + /// + /// - Parameter other: The keys view of a persistent dictionary. + /// + /// - Complexity: Expected complexity is O(`self.count` + `other.count`) in + /// the worst case, if `Element` properly implements hashing. + /// However, the implementation is careful to make the best use of + /// hash tree structure to minimize work when possible, e.g. by linking + /// parts of the input trees directly into the result. @inlinable @inline(__always) public func intersection( _ other: PersistentDictionary.Keys @@ -63,8 +83,8 @@ extension PersistentSet { /// (This matters if equal members can be distinguished by comparing their /// identities, or by some other means.) /// - /// - Parameter other: An arbitrary sequence of items, possibly containing - /// duplicate values. + /// - Parameter other: An arbitrary finite sequence of items, + /// possibly containing duplicate values. @inlinable public func intersection( _ other: S diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra subtract.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra subtract.swift index a806595f..6463d527 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra subtract.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra subtract.swift @@ -18,6 +18,7 @@ extension PersistentSet { /// // `a` is now some permutation of `[1, 3]` /// /// - Parameter other: An arbitrary set of elements. + /// /// - Complexity: Expected complexity is O(`self.count` + `other.count`) in /// the worst case, if `Element` properly implements hashing. /// However, the implementation is careful to make the best use of @@ -28,6 +29,21 @@ extension PersistentSet { self = subtracting(other) } + /// Removes the elements of the given keys view of a persistent dictionary + /// from this set. + /// + /// var a: PersistentSet = [1, 2, 3, 4] + /// let b: PersistentDictionary = [0: "a", 2: "b", 4: "c", 6: "d"] + /// a.subtract(b.keys) + /// // `a` is now some permutation of `[1, 3]` + /// + /// - Parameter other: The keys view of a persistent dictionary. + /// + /// - Complexity: Expected complexity is O(`self.count` + `other.count`) in + /// the worst case, if `Element` properly implements hashing. + /// However, the implementation is careful to make the best use of + /// hash tree structure to minimize work when possible, e.g. by linking + /// parts of the input trees directly into the result. @inlinable public mutating func subtract( _ other: PersistentDictionary.Keys @@ -35,6 +51,17 @@ extension PersistentSet { self = subtracting(other) } + /// Removes the elements of the given sequence from this set. + /// + /// var a: PersistentSet = [1, 2, 3, 4] + /// let b = [0, 2, 4, 6] + /// a.subtract(b) + /// // `a` is now some permutation of `[1, 3]` + /// + /// - Parameter other: An arbitrary finite sequence. + /// + /// - Complexity: O(*n*) where *n* is the number of elements in `other`, + /// as long as `Element` properly implements hashing. @inlinable public mutating func subtract(_ other: S) where S.Element == Element { diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra subtracting.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra subtracting.swift index 01f0dec9..15ced7ff 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra subtracting.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra subtracting.swift @@ -19,6 +19,7 @@ extension PersistentSet { /// // `c` is some permutation of `[1, 3]` /// /// - Parameter other: An arbitrary set of elements. + /// /// - Complexity: Expected complexity is O(`self.count` + `other.count`) in /// the worst case, if `Element` properly implements hashing. /// However, the implementation is careful to make the best use of @@ -29,6 +30,21 @@ extension PersistentSet { _subtracting(other._root) } + /// Returns a new set containing the elements of this set that do not occur + /// in the given keys view of a persistent dictionary. + /// + /// var a: PersistentSet = [1, 2, 3, 4] + /// let b: PersistentDictionary = [0: "a", 2: "b", 4: "c", 6: "d"] + /// let c = a.subtracting(b.keys) + /// // `c` is some permutation of `[1, 3]` + /// + /// - Parameter other: The keys view of a persistent dictionary. + /// + /// - Complexity: Expected complexity is O(`self.count` + `other.count`) in + /// the worst case, if `Element` properly implements hashing. + /// However, the implementation is careful to make the best use of + /// hash tree structure to minimize work when possible, e.g. by linking + /// parts of the input trees directly into the result. @inlinable public __consuming func subtracting( _ other: PersistentDictionary.Keys @@ -47,6 +63,18 @@ extension PersistentSet { return Self(_new: root) } + /// Returns a new set containing the elements of this set that do not occur + /// in the given sequence. + /// + /// var a: PersistentSet = [1, 2, 3, 4] + /// let b = [0, 2, 4, 6] + /// let c = a.subtracting(b) + /// // `c` is some permutation of `[1, 3]` + /// + /// - Parameter other: An arbitrary finite sequence. + /// + /// - Complexity: O(*n*) where *n* is the number of elements in `other`, + /// as long as `Element` properly implements hashing. @inlinable public __consuming func subtracting( _ other: S diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra symmetricDifference.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra symmetricDifference.swift index d210d21d..5fd662a2 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra symmetricDifference.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra symmetricDifference.swift @@ -9,6 +9,8 @@ // //===----------------------------------------------------------------------===// +import _CollectionsUtilities + extension PersistentSet { /// Returns a new set with the elements that are either in this set or in /// `other`, but not in both. @@ -19,6 +21,7 @@ extension PersistentSet { /// // `c` is some permutation of `[0, 1, 3, 6]` /// /// - Parameter other: An arbitrary set of elements. + /// /// - Complexity: Expected complexity is O(`self.count` + `other.count`) in /// the worst case, if `Element` properly implements hashing. /// However, the implementation is careful to make the best use of @@ -33,6 +36,51 @@ extension PersistentSet { return PersistentSet(_new: root) } + /// Returns a new set with the elements that are either in this set or in + /// `other`, but not in both. + /// + /// var a: PersistentSet = [1, 2, 3, 4] + /// let b: PersistentDictionary = [0: "a", 2: "b", 4: "c", 6: "d"] + /// let c = a.symmetricDifference(b.keys) + /// // `c` is some permutation of `[0, 1, 3, 6]` + /// + /// - Parameter other: An arbitrary set of elements. + /// + /// - Complexity: Expected complexity is O(`self.count` + `other.count`) in + /// the worst case, if `Element` properly implements hashing. + /// However, the implementation is careful to make the best use of + /// hash tree structure to minimize work when possible, e.g. by linking + /// parts of the input trees directly into the result. + @inlinable + public func symmetricDifference( + _ other: __owned PersistentDictionary.Keys + ) -> Self { + let branch = _root.symmetricDifference(.top, other._base._root) + guard let branch = branch else { return self } + let root = branch.finalize(.top) + root._fullInvariantCheck() + return PersistentSet(_new: root) + } + + /// Returns a new set with the elements that are either in this set or in + /// the given sequence, but not in both. + /// + /// var a: PersistentSet = [1, 2, 3, 4] + /// let b = [0, 2, 4, 6, 6, 2] + /// let c = a.symmetricDifference(b) + /// // `c` is some permutation of `[0, 1, 3, 6]` + /// + /// In case the sequence contains duplicate elements, only the first instance + /// matters -- the second and subsequent instances are ignored by this method. + /// + /// - Parameter other: A finite sequence of elements, possibly containing + /// duplicates. + /// + /// - Complexity: Expected complexity is O(`self.count` + `other.count`) in + /// the worst case, if `Element` properly implements hashing. + /// However, the implementation is careful to make the best use of + /// hash tree structure to minimize work when possible, e.g. by linking + /// parts of the input trees directly into the result. @inlinable public func symmetricDifference(_ other: __owned S) -> Self where S.Element == Element { @@ -40,17 +88,25 @@ extension PersistentSet { return symmetricDifference(other as! Self) } - var root = self._root - for item in other { - let hash = _Hash(item) - var state = root.prepareValueUpdate(item, hash) - if state.found { - state.value = nil - } else { - state.value = () + if other is _UniqueCollection { + // Fast path: we can do a simple in-place loop. + var root = self._root + for item in other { + let hash = _Hash(item) + var state = root.prepareValueUpdate(item, hash) + if state.found { + state.value = nil + } else { + state.value = () + } + root.finalizeValueUpdate(state) } - root.finalizeValueUpdate(state) + return Self(_new: root) } - return Self(_new: root) + + // If `other` may contain duplicates, we need to be more + // careful (and slower). + let other = PersistentSet(other) + return self.symmetricDifference(other) } } diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra union.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra union.swift index 80f1399d..eb83644b 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra union.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra union.swift @@ -9,24 +9,26 @@ // //===----------------------------------------------------------------------===// -/// Returns a new set with the elements of both this and the given set. -/// -/// var a: PersistentSet = [1, 2, 3, 4] -/// let b: PersistentSet = [0, 2, 4, 6] -/// let c = a.union(b) -/// // `c` is some permutation of `[0, 1, 2, 3, 4, 6]` -/// -/// For values that are members of both sets, the result set contains the -/// instances that were originally in `self`. (This matters if equal members -/// can be distinguished by comparing their identities, or by some other means.) -/// -/// - Parameter other: The set of elements to insert. -/// - Complexity: Expected complexity is O(`self.count` + `other.count`) in -/// the worst case, if `Element` properly implements hashing. -/// However, the implementation is careful to make the best use of -/// hash tree structure to minimize work when possible, e.g. by linking -/// parts of the input trees directly into the result. extension PersistentSet { + /// Returns a new set with the elements of both this and the given set. + /// + /// var a: PersistentSet = [1, 2, 3, 4] + /// let b: PersistentSet = [0, 2, 4, 6] + /// let c = a.union(b) + /// // `c` is some permutation of `[0, 1, 2, 3, 4, 6]` + /// + /// For values that are members of both sets, the result set contains the + /// instances that were originally in `self`. (This matters if equal members + /// can be distinguished by comparing their identities, or by some other + /// means.) + /// + /// - Parameter other: The set of elements to insert. + /// + /// - Complexity: Expected complexity is O(`self.count` + `other.count`) in + /// the worst case, if `Element` properly implements hashing. + /// However, the implementation is careful to make the best use of + /// hash tree structure to minimize work when possible, e.g. by linking + /// parts of the input trees directly into the result. @inlinable public func union(_ other: __owned Self) -> Self { let r = _root.union(.top, other._root) @@ -35,6 +37,59 @@ extension PersistentSet { return PersistentSet(_new: r.node) } + /// Returns a new set with the elements of both this set and the given + /// keys view of a persistent dictionary. + /// + /// var a: PersistentSet = [1, 2, 3, 4] + /// let b: PersistentDictionary = [0: "a", 2: "b", 4: "c", 6: "d"] + /// let c = a.union(b) + /// // `c` is some permutation of `[0, 1, 2, 3, 4, 6]` + /// + /// For values that are members of both inputs, the result set contains the + /// instances that were originally in `self`. (This matters if equal members + /// can be distinguished by comparing their identities, or by some other + /// means.) + /// + /// - Parameter other: The keys view of a persistent dictionary. + /// + /// - Complexity: Expected complexity is O(`self.count` + `other.count`) in + /// the worst case, if `Element` properly implements hashing. + /// However, the implementation is careful to make the best use of + /// hash tree structure to minimize work when possible, e.g. by linking + /// parts of the input trees directly into the result. + @inlinable + public func union( + _ other: __owned PersistentDictionary.Keys + ) -> Self { + let r = _root.union(.top, other._base._root) + guard r.copied else { return self } + r.node._fullInvariantCheck() + return PersistentSet(_new: r.node) + } + + /// Returns a new set with the elements of both this set and the given + /// sequence. + /// + /// var a: PersistentSet = [1, 2, 3, 4] + /// let b = [0, 2, 4, 6, 0, 2] + /// let c = a.union(b) + /// // `c` is some permutation of `[0, 1, 2, 3, 4, 6]` + /// + /// For values that are members of both inputs, the result set contains the + /// instances that were originally in `self`. (This matters if equal members + /// can be distinguished by comparing their identities, or by some other + /// means.) + /// + /// If some of the values that are missing from `self` have multiple copies + /// in `other`, then the result of this function always contains the first + /// instances in the sequence -- the second and subsequent copies are ignored. + /// + /// - Parameter other: An arbitrary finite sequence of items, + /// possibly containing duplicate values. + /// + /// - Complexity: Expected complexity is O(*n*) in + /// the worst case, where *n* is the number of items in `other`, + /// as long as `Element` properly implements hashing. @inlinable public func union(_ other: __owned S) -> Self where S.Element == Element { diff --git a/Tests/PersistentCollectionsTests/PersistentSet Tests.swift b/Tests/PersistentCollectionsTests/PersistentSet Tests.swift index dee8438c..adce7d93 100644 --- a/Tests/PersistentCollectionsTests/PersistentSet Tests.swift +++ b/Tests/PersistentCollectionsTests/PersistentSet Tests.swift @@ -418,6 +418,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.intersection(v) @@ -430,9 +431,11 @@ class PersistentSetTests: CollectionTestCase { } expectEqualSets(x.intersection(y), reference) + expectEqualSets(x.intersection(z.keys), reference) expectEqualSets(checkSequence(x, y), reference) expectEqualSets(x.intersection(v), reference) expectEqualSets(x.intersection(b), reference) + expectEqualSets(x.intersection(b + b), reference) } } } @@ -445,6 +448,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.subtracting(v) @@ -457,9 +461,11 @@ class PersistentSetTests: CollectionTestCase { } expectEqualSets(x.subtracting(y), reference) + expectEqualSets(x.subtracting(z.keys), reference) expectEqualSets(checkSequence(x, y), reference) expectEqualSets(x.subtracting(v), reference) expectEqualSets(x.subtracting(b), reference) + expectEqualSets(x.subtracting(b + b), reference) } } } @@ -482,6 +488,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.union(v) @@ -494,9 +501,11 @@ class PersistentSetTests: CollectionTestCase { } expectEqualSets(x.union(y), reference) + expectEqualSets(x.union(z.keys), reference) expectEqualSets(checkSequence(x, y), reference) expectEqualSets(x.union(v), reference) expectEqualSets(x.union(b), reference) + expectEqualSets(x.union(b + b), reference) } } } @@ -509,6 +518,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.symmetricDifference(v) @@ -521,13 +531,69 @@ class PersistentSetTests: CollectionTestCase { } expectEqualSets(x.symmetricDifference(y), reference) + expectEqualSets(x.symmetricDifference(z.keys), reference) expectEqualSets(checkSequence(x, y), reference) expectEqualSets(x.symmetricDifference(v), reference) expectEqualSets(x.symmetricDifference(b), reference) + expectEqualSets(x.symmetricDifference(b + b), reference) } } } + func test_mutating_binary_set_operations() { + let a = [1, 2, 3, 4] + let b = [0, 2, 4, 6] + + let x = PersistentSet(a) + let y = PersistentSet(b) + let u = Set(a) + let v = Set(b) + let z = PersistentDictionary(uniqueKeysWithValues: b.map { ($0, $0) }) + + func check( + _ reference: Set, + _ body: (inout PersistentSet) -> Void, + file: StaticString = #file, + line: UInt = #line + ) { + var set = x + body(&set) + expectEqualSets(set, reference, file: file, line: line) + } + + do { + let reference = u.intersection(v) + check(reference) { $0.formIntersection(y) } + check(reference) { $0.formIntersection(z.keys) } + check(reference) { $0.formIntersection(b) } + check(reference) { $0.formIntersection(b + b) } + } + + do { + let reference = u.union(v) + check(reference) { $0.formUnion(y) } + check(reference) { $0.formUnion(z.keys) } + check(reference) { $0.formUnion(b) } + check(reference) { $0.formUnion(b + b) } + } + + do { + let reference = u.symmetricDifference(v) + check(reference) { $0.formSymmetricDifference(y) } + check(reference) { $0.formSymmetricDifference(z.keys) } + check(reference) { $0.formSymmetricDifference(b) } + check(reference) { $0.formSymmetricDifference(b + b) } + } + + do { + let reference = u.subtracting(v) + check(reference) { $0.subtract(y) } + check(reference) { $0.subtract(z.keys) } + check(reference) { $0.subtract(b) } + check(reference) { $0.subtract(b + b) } + } + } + func test_update_at() { withEverySubset("a", of: testItems) { a in withEvery("offset", in: 0 ..< a.count) { offset in From 3a07b859e060e5afa02f57ee7b92b2b0891b870b Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 20 Oct 2022 18:26:26 -0700 Subject: [PATCH 09/39] [OrderedSet] Split SetAlgebra binary operations into individual files --- ...+Partial SetAlgebra formIntersection.swift | 73 +++ ...l SetAlgebra formSymmetricDifference.swift | 87 +++ ...eredSet+Partial SetAlgebra formUnion.swift | 84 +++ ...dSet+Partial SetAlgebra intersection.swift | 96 +++ ...deredSet+Partial SetAlgebra subtract.swift | 76 +++ ...edSet+Partial SetAlgebra subtracting.swift | 108 ++++ ...rtial SetAlgebra symmetricDifference.swift | 130 ++++ .../OrderedSet+Partial SetAlgebra union.swift | 85 +++ ...redSet+Partial SetAlgebra+Operations.swift | 589 ------------------ 9 files changed, 739 insertions(+), 589 deletions(-) create mode 100644 Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra formIntersection.swift create mode 100644 Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra formSymmetricDifference.swift create mode 100644 Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra formUnion.swift create mode 100644 Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra intersection.swift create mode 100644 Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra subtract.swift create mode 100644 Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra subtracting.swift create mode 100644 Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra symmetricDifference.swift create mode 100644 Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra union.swift delete mode 100644 Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra+Operations.swift diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra formIntersection.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra formIntersection.swift new file mode 100644 index 00000000..f27e7455 --- /dev/null +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra formIntersection.swift @@ -0,0 +1,73 @@ +//===----------------------------------------------------------------------===// +// +// 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 { + /// Removes the elements of this set that aren't also in the given one. + /// + /// var set: OrderedSet = [1, 2, 3, 4] + /// let other: OrderedSet = [6, 4, 2, 0] + /// set.formIntersection(other) + /// // set is now [2, 4] + /// + /// - Parameter other: A set of elements. + /// + /// - Complexity: Expected to be O(`self.count`) on average, if `Element` + /// implements high-quality hashing. + @inlinable + public mutating func formIntersection(_ other: Self) { + self = self.intersection(other) + } + + // Generalizations + + /// Removes the elements of this set that aren't also in the given one. + /// + /// var set: OrderedSet = [1, 2, 3, 4] + /// let other: OrderedSet = [6, 4, 2, 0] + /// set.formIntersection(other) + /// // set is now [2, 4] + /// + /// - Parameter other: A set of elements. + /// + /// - Complexity: Expected to be O(`self.count`) on average, if `Element` + /// implements high-quality hashing. + @inlinable + @inline(__always) + public mutating func formIntersection(_ other: UnorderedView) { + formIntersection(other._base) + } + + /// Removes the elements of this set that aren't also in the given sequence. + /// + /// var set: OrderedSet = [1, 2, 3, 4] + /// set.formIntersection([6, 4, 2, 0] as Array) + /// // set is now [2, 4] + /// + /// - Parameter other: A finite sequence of elements. + /// + /// - 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 mutating func formIntersection( + _ other: S + ) where S.Element == Element { + self = self.intersection(other) + } +} diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra formSymmetricDifference.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra formSymmetricDifference.swift new file mode 100644 index 00000000..c028711d --- /dev/null +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra formSymmetricDifference.swift @@ -0,0 +1,87 @@ +//===----------------------------------------------------------------------===// +// +// 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 { + /// Replace this set with the elements contained in this set or the given + /// set, but not both. + /// + /// On return, `self` contains elements originally from `self` followed by + /// elements in `other`, in the same order they appeared in the input values. + /// + /// var set: OrderedSet = [1, 2, 3, 4] + /// let other: OrderedSet = [6, 4, 2, 0] + /// set.formSymmetricDifference(other) + /// // set is now [1, 3, 6, 0] + /// + /// - Parameter other: Another set. + /// + /// - Complexity: Expected to be O(`self.count + other.count`) on average, if + /// `Element` implements high-quality hashing. + @inlinable + public mutating func formSymmetricDifference(_ other: __owned Self) { + self = self.symmetricDifference(other) + } + + // Generalizations + + /// Replace this set with the elements contained in this set or the given + /// set, but not both. + /// + /// On return, `self` contains elements originally from `self` followed by + /// elements in `other`, in the same order they appeared in the input values. + /// + /// var set: OrderedSet = [1, 2, 3, 4] + /// let other: OrderedSet = [6, 4, 2, 0] + /// set.formSymmetricDifference(other.unordered) + /// // set is now [1, 3, 6, 0] + /// + /// - Parameter other: Another set. + /// + /// - Complexity: Expected to be O(`self.count + other.count`) on average, if + /// `Element` implements high-quality hashing. + @inlinable + @inline(__always) + public mutating func formSymmetricDifference(_ other: __owned UnorderedView) { + formSymmetricDifference(other._base) + } + + /// Replace this set with the elements contained in this set or the given + /// sequence, but not both. + /// + /// On return, `self` contains elements originally from `self` followed by + /// elements in `other`, in the same order they first appeared in the input + /// values. + /// + /// var set: OrderedSet = [1, 2, 3, 4] + /// set.formSymmetricDifference([6, 4, 2, 0] as Array) + /// // set is now [1, 3, 6, 0] + /// + /// - Parameter other: A finite sequence of elements. + /// + /// - 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 mutating func formSymmetricDifference( + _ other: __owned S + ) where S.Element == Element { + self = self.symmetricDifference(other) + } +} diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra formUnion.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra formUnion.swift new file mode 100644 index 00000000..36f0e567 --- /dev/null +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra formUnion.swift @@ -0,0 +1,84 @@ +//===----------------------------------------------------------------------===// +// +// 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 { + /// Adds the elements of the given set to this set. + /// + /// Members of `other` that aren't already in `self` get appended to the end + /// of the set, in the order they appear in `other`. + /// + /// var a: OrderedSet = [1, 2, 3, 4] + /// let b: OrderedSet = [0, 2, 4, 6] + /// a.formUnion(b) + /// // `a` is now `[1, 2, 3, 4, 0, 6]` + /// + /// - Parameter other: The set of elements to insert. + /// + /// - Complexity: Expected to be O(`other.count`) on average, if `Element` + /// implements high-quality hashing. + @inlinable + public mutating func formUnion(_ other: __owned Self) { + append(contentsOf: other) + } + + // Generalizations + + /// Adds the elements of the given set to this set. + /// + /// Members of `other` that aren't already in `self` get appended to the end + /// of the set, in the order they appear in `other`. + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: OrderedSet = [0, 2, 4, 6] + /// a.formUnion(b.unordered) + /// // a is now [1, 2, 3, 4, 0, 6] + /// + /// - Parameter other: The set of elements to add. + /// + /// - Complexity: Expected to be O(`self.count` + `other.count`) on average, + /// if `Element` implements high-quality hashing. + @inlinable + @inline(__always) + public mutating func formUnion(_ other: __owned UnorderedView) { + formUnion(other._base) + } + + /// Adds the elements of the given sequence to this set. + /// + /// Members of `other` that aren't already in `self` get appended to the end + /// of the set, in the order they appear in `other`. + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: Array = [0, 2, 4, 6] + /// a.formUnion(b) + /// // a is now [1, 2, 3, 4, 0, 6] + /// + /// - Parameter other: A finite sequence of elements. + /// + /// - Complexity: Expected to be O(`self.count` + `other.count`) on average, + /// if `Element` implements high-quality hashing. + @inlinable + public mutating func formUnion( + _ other: __owned S + ) where S.Element == Element { + append(contentsOf: other) + } +} + diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra intersection.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra intersection.swift new file mode 100644 index 00000000..5fb39d9a --- /dev/null +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra intersection.swift @@ -0,0 +1,96 @@ +//===----------------------------------------------------------------------===// +// +// 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 new set with the elements that are common to both this set and + /// the provided other one, in the order they appear in `self`. + /// + /// let set: OrderedSet = [1, 2, 3, 4] + /// let other: OrderedSet = [6, 4, 2, 0] + /// set.intersection(other) // [2, 4] + /// + /// - Parameter other: Another set. + /// + /// - Returns: A new set. + /// + /// - Complexity: Expected to be O(`self.count`) on average, if `Element` + /// implements high-quality hashing. + @inlinable + public __consuming func intersection(_ other: Self) -> Self { + var result = Self() + for item in self { + if other.contains(item) { + result._appendNew(item) + } + } + result._checkInvariants() + return result + } + + // Generalizations + + /// Returns a new set with the elements that are common to both this set and + /// the provided other one, in the order they appear in `self`. + /// + /// let set: OrderedSet = [1, 2, 3, 4] + /// let other: OrderedSet = [6, 4, 2, 0] + /// set.intersection(other) // [2, 4] + /// + /// - Parameter other: Another set. + /// + /// - Returns: A new set. + /// + /// - Complexity: Expected to be O(`self.count`) on average, if `Element` + /// implements high-quality hashing. + @inlinable + @inline(__always) + public __consuming func intersection(_ other: UnorderedView) -> Self { + intersection(other._base) + } + + /// Returns a new set with the elements that are common to both this set and + /// the provided sequence, in the order they appear in `self`. + /// + /// let set: OrderedSet = [1, 2, 3, 4] + /// set.intersection([6, 4, 2, 0] as Array) // [2, 4] + /// + /// - Parameter other: A finite sequence of elements. + /// + /// - Returns: A new set. + /// + /// - 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 __consuming func intersection( + _ other: S + ) -> Self where S.Element == Element { + _UnsafeBitset.withTemporaryBitset(capacity: self.count) { bitset in + for item in other { + if let index = self._find_inlined(item).index { + bitset.insert(index) + } + } + let result = self._extractSubset(using: bitset) + result._checkInvariants() + return result + } + } +} + diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra subtract.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra subtract.swift new file mode 100644 index 00000000..f21c9890 --- /dev/null +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra subtract.swift @@ -0,0 +1,76 @@ +//===----------------------------------------------------------------------===// +// +// 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 { + /// Removes the elements of the given set from this set. + /// + /// var set: OrderedSet = [1, 2, 3, 4] + /// let other: OrderedSet = [6, 4, 2, 0] + /// set.subtract(other) + /// // set is now [1, 3] + /// + /// - Parameter other: Another set. + /// + /// - Complexity: Expected to be O(`self.count + other.count`) on average, if + /// `Element` implements high-quality hashing. + @inlinable + @inline(__always) + public mutating func subtract(_ other: Self) { + self = subtracting(other) + } + + // Generalizations + + /// Removes the elements of the given set from this set. + /// + /// var set: OrderedSet = [1, 2, 3, 4] + /// let other: OrderedSet = [6, 4, 2, 0] + /// set.subtract(other.unordered) + /// // set is now [1, 3] + /// + /// - Parameter other: Another set. + /// + /// - Complexity: Expected to be O(`self.count + other.count`) on average, if + /// `Element` implements high-quality hashing. + @inlinable + @inline(__always) + public mutating func subtract(_ other: UnorderedView) { + subtract(other._base) + } + + /// Removes the elements of the given sequence from this set. + /// + /// var set: OrderedSet = [1, 2, 3, 4] + /// set.subtract([6, 4, 2, 0] as Array) + /// // set is now [1, 3] + /// + /// - Parameter other: A finite sequence of elements. + /// + /// - 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 + @inline(__always) + public mutating func subtract( + _ other: S + ) where S.Element == Element { + self = _subtracting(other) + } +} diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra subtracting.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra subtracting.swift new file mode 100644 index 00000000..943a8904 --- /dev/null +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra subtracting.swift @@ -0,0 +1,108 @@ +//===----------------------------------------------------------------------===// +// +// 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 new set containing the elements of this set that do not occur + /// in the given set. + /// + /// The result contains elements in the same order they appear in `self`. + /// + /// let set: OrderedSet = [1, 2, 3, 4] + /// let other: OrderedSet = [6, 4, 2, 0] + /// set.subtracting(other) // [1, 3] + /// + /// - Parameter other: Another set. + /// + /// - Returns: A new set. + /// + /// - Complexity: Expected to be O(`self.count + other.count`) on average, if + /// `Element` implements high-quality hashing. + @inlinable + @inline(__always) + public __consuming func subtracting(_ other: Self) -> Self { + _subtracting(other) + } + + // Generalizations + + /// Returns a new set containing the elements of this set that do not occur + /// in the given set. + /// + /// The result contains elements in the same order they appear in `self`. + /// + /// let set: OrderedSet = [1, 2, 3, 4] + /// let other: OrderedSet = [6, 4, 2, 0] + /// set.subtracting(other.unordered) // [1, 3] + /// + /// - Parameter other: Another set. + /// + /// - Returns: A new set. + /// + /// - Complexity: Expected to be O(`self.count + other.count`) on average, if + /// `Element` implements high-quality hashing. + @inlinable + @inline(__always) + public __consuming func subtracting(_ other: UnorderedView) -> Self { + subtracting(other._base) + } + + /// Returns a new set containing the elements of this set that do not occur + /// in the given sequence. + /// + /// The result contains elements in the same order they appear in `self`. + /// + /// let set: OrderedSet = [1, 2, 3, 4] + /// set.subtracting([6, 4, 2, 0] as Array) // [1, 3] + /// + /// - Parameter other: A finite sequence of elements. + /// + /// - Returns: A new set. + /// + /// - Complexity: Expected to be O(`self.count + other.count`) on average, if + /// `Element` implements high-quality hashing. + @inlinable + @inline(__always) + public __consuming func subtracting( + _ other: S + ) -> Self where S.Element == Element { + _subtracting(other) + } + + @inlinable + __consuming func _subtracting( + _ other: S + ) -> Self where S.Element == Element { + guard count > 0 else { return Self() } + return _UnsafeBitset.withTemporaryBitset(capacity: count) { difference in + difference.insertAll(upTo: count) + for item in other { + if let index = self._find(item).index { + if difference.remove(index), difference.count == 0 { + return Self() + } + } + } + assert(difference.count > 0) + let result = _extractSubset(using: difference) + result._checkInvariants() + return result + } + } +} diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra symmetricDifference.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra symmetricDifference.swift new file mode 100644 index 00000000..9a3da59a --- /dev/null +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra symmetricDifference.swift @@ -0,0 +1,130 @@ +//===----------------------------------------------------------------------===// +// +// 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 new set with the elements that are either in this set or in + /// `other`, but not in both. + /// + /// The result contains elements from `self` followed by elements in `other`, + /// in the same order they appeared in the original sets. + /// + /// let set: OrderedSet = [1, 2, 3, 4] + /// let other: OrderedSet = [6, 4, 2, 0] + /// set.symmetricDifference(other) // [1, 3, 6, 0] + /// + /// - Parameter other: Another set. + /// + /// - Returns: A new set. + /// + /// - Complexity: Expected to be O(`self.count + other.count`) on average, if + /// `Element` implements high-quality hashing. + @inlinable + public __consuming func symmetricDifference(_ other: __owned Self) -> Self { + _UnsafeBitset.withTemporaryBitset(capacity: self.count) { bitset1 in + _UnsafeBitset.withTemporaryBitset(capacity: other.count) { bitset2 in + bitset1.insertAll(upTo: self.count) + for item in other { + if let index = self._find(item).index { + bitset1.remove(index) + } + } + bitset2.insertAll(upTo: other.count) + for item in self { + if let index = other._find(item).index { + bitset2.remove(index) + } + } + var result = self._extractSubset(using: bitset1, + extraCapacity: bitset2.count) + for offset in bitset2 { + result._appendNew(other._elements[offset]) + } + result._checkInvariants() + return result + } + } + } + + // Generalizations + + /// Returns a new set with the elements that are either in this set or in + /// `other`, but not in both. + /// + /// The result contains elements from `self` followed by elements in `other`, + /// in the same order they appeared in the original sets. + /// + /// let set: OrderedSet = [1, 2, 3, 4] + /// let other: OrderedSet = [6, 4, 2, 0] + /// set.symmetricDifference(other.unordered) // [1, 3, 6, 0] + /// + /// - Parameter other: Another set. + /// + /// - Returns: A new set. + /// + /// - Complexity: Expected to be O(`self.count + other.count`) on average, if + /// `Element` implements high-quality hashing. + @inlinable + @inline(__always) + public __consuming func symmetricDifference( + _ other: __owned UnorderedView + ) -> Self { + symmetricDifference(other._base) + } + + /// Returns a new set with the elements that are either in this set or in + /// `other`, but not in both. + /// + /// The result contains elements from `self` followed by elements in `other`, + /// in the same order they appeared in the original input values. + /// + /// let set: OrderedSet = [1, 2, 3, 4] + /// let other: Array = [6, 4, 2, 0] + /// set.symmetricDifference(other) // [1, 3, 6, 0] + /// + /// - Parameter other: A finite sequence of elements. + /// + /// - Returns: A new set. + /// + /// - 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 __consuming func symmetricDifference( + _ other: __owned S + ) -> Self where S.Element == Element { + _UnsafeBitset.withTemporaryBitset(capacity: self.count) { bitset in + var new = Self() + bitset.insertAll(upTo: self.count) + for item in other { + if let index = self._find(item).index { + bitset.remove(index) + } else { + new.append(item) + } + } + var result = _extractSubset(using: bitset, extraCapacity: new.count) + for item in new._elements { + result._appendNew(item) + } + result._checkInvariants() + return result + } + } +} diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra union.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra union.swift new file mode 100644 index 00000000..15c23b5f --- /dev/null +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra union.swift @@ -0,0 +1,85 @@ +//===----------------------------------------------------------------------===// +// +// 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 new set with the elements of both this and the given set. + /// + /// Members of `other` that aren't already in `self` get appended to the end + /// of the result, in the order they appear in `other`. + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: OrderedSet = [0, 2, 4, 6] + /// a.union(b) // [1, 2, 3, 4, 0, 6] + /// + /// - Parameter other: The set of elements to add. + /// + /// - Complexity: Expected to be O(`self.count` + `other.count`) on average, + /// if `Element` implements high-quality hashing. + @inlinable + public __consuming func union(_ other: __owned Self) -> Self { + var result = self + result.formUnion(other) + return result + } + + // Generalizations + + /// Returns a new set with the elements of both this and the given set. + /// + /// Members of `other` that aren't already in `self` get appended to the end + /// of the result, in the order they appear in `other`. + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: OrderedSet = [0, 2, 4, 6] + /// a.union(b.unordered) // [1, 2, 3, 4, 0, 6] + /// + /// - Parameter other: The set of elements to add. + /// + /// - Complexity: Expected to be O(`self.count` + `other.count`) on average, + /// if `Element` implements high-quality hashing. + @inlinable + @inline(__always) + public __consuming func union(_ other: __owned UnorderedView) -> Self { + union(other._base) + } + + /// Returns a new set with the elements of both this and the given set. + /// + /// Members of `other` that aren't already in `self` get appended to the end + /// of the result, in the order they appear in `other`. + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: Array = [0, 2, 4, 6] + /// a.union(b) // [1, 2, 3, 4, 0, 6] + /// + /// - Parameter other: A finite sequence of elements. + /// + /// - Complexity: Expected to be O(`self.count` + `other.count`) on average, + /// if `Element` implements high-quality hashing. + @inlinable + public __consuming func union( + _ other: __owned S + ) -> Self where S.Element == Element { + var result = self + result.formUnion(other) + return result + } +} + diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra+Operations.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra+Operations.swift deleted file mode 100644 index 474d7431..00000000 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra+Operations.swift +++ /dev/null @@ -1,589 +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 -// -//===----------------------------------------------------------------------===// - -// `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 { - /// Adds the elements of the given set to this set. - /// - /// Members of `other` that aren't already in `self` get appended to the end - /// of the set, in the order they appear in `other`. - /// - /// var a: OrderedSet = [1, 2, 3, 4] - /// let b: OrderedSet = [0, 2, 4, 6] - /// a.formUnion(b) - /// // `a` is now `[1, 2, 3, 4, 0, 6]` - /// - /// - Parameter other: The set of elements to insert. - /// - /// - Complexity: Expected to be O(`other.count`) on average, if `Element` - /// implements high-quality hashing. - @inlinable - public mutating func formUnion(_ other: __owned Self) { - append(contentsOf: other) - } - - /// Returns a new set with the elements of both this and the given set. - /// - /// Members of `other` that aren't already in `self` get appended to the end - /// of the result, in the order they appear in `other`. - /// - /// let a: OrderedSet = [1, 2, 3, 4] - /// let b: OrderedSet = [0, 2, 4, 6] - /// a.union(b) // [1, 2, 3, 4, 0, 6] - /// - /// - Parameter other: The set of elements to add. - /// - /// - Complexity: Expected to be O(`self.count` + `other.count`) on average, - /// if `Element` implements high-quality hashing. - @inlinable - public __consuming func union(_ other: __owned Self) -> Self { - var result = self - result.formUnion(other) - return result - } - - // Generalizations - - /// Adds the elements of the given set to this set. - /// - /// Members of `other` that aren't already in `self` get appended to the end - /// of the set, in the order they appear in `other`. - /// - /// let a: OrderedSet = [1, 2, 3, 4] - /// let b: OrderedSet = [0, 2, 4, 6] - /// a.formUnion(b.unordered) - /// // a is now [1, 2, 3, 4, 0, 6] - /// - /// - Parameter other: The set of elements to add. - /// - /// - Complexity: Expected to be O(`self.count` + `other.count`) on average, - /// if `Element` implements high-quality hashing. - @inlinable - @inline(__always) - public mutating func formUnion(_ other: __owned UnorderedView) { - formUnion(other._base) - } - - /// Returns a new set with the elements of both this and the given set. - /// - /// Members of `other` that aren't already in `self` get appended to the end - /// of the result, in the order they appear in `other`. - /// - /// let a: OrderedSet = [1, 2, 3, 4] - /// let b: OrderedSet = [0, 2, 4, 6] - /// a.union(b.unordered) // [1, 2, 3, 4, 0, 6] - /// - /// - Parameter other: The set of elements to add. - /// - /// - Complexity: Expected to be O(`self.count` + `other.count`) on average, - /// if `Element` implements high-quality hashing. - @inlinable - @inline(__always) - public __consuming func union(_ other: __owned UnorderedView) -> Self { - union(other._base) - } - - /// Adds the elements of the given sequence to this set. - /// - /// Members of `other` that aren't already in `self` get appended to the end - /// of the set, in the order they appear in `other`. - /// - /// let a: OrderedSet = [1, 2, 3, 4] - /// let b: Array = [0, 2, 4, 6] - /// a.formUnion(b) - /// // a is now [1, 2, 3, 4, 0, 6] - /// - /// - Parameter other: A finite sequence of elements. - /// - /// - Complexity: Expected to be O(`self.count` + `other.count`) on average, - /// if `Element` implements high-quality hashing. - @inlinable - public mutating func formUnion( - _ other: __owned S - ) where S.Element == Element { - append(contentsOf: other) - } - - /// Returns a new set with the elements of both this and the given set. - /// - /// Members of `other` that aren't already in `self` get appended to the end - /// of the result, in the order they appear in `other`. - /// - /// let a: OrderedSet = [1, 2, 3, 4] - /// let b: Array = [0, 2, 4, 6] - /// a.union(b) // [1, 2, 3, 4, 0, 6] - /// - /// - Parameter other: A finite sequence of elements. - /// - /// - Complexity: Expected to be O(`self.count` + `other.count`) on average, - /// if `Element` implements high-quality hashing. - @inlinable - public __consuming func union( - _ other: __owned S - ) -> Self where S.Element == Element { - var result = self - result.formUnion(other) - return result - } -} - -extension OrderedSet { - /// Returns a new set with the elements that are common to both this set and - /// the provided other one, in the order they appear in `self`. - /// - /// let set: OrderedSet = [1, 2, 3, 4] - /// let other: OrderedSet = [6, 4, 2, 0] - /// set.intersection(other) // [2, 4] - /// - /// - Parameter other: Another set. - /// - /// - Returns: A new set. - /// - /// - Complexity: Expected to be O(`self.count`) on average, if `Element` - /// implements high-quality hashing. - @inlinable - public __consuming func intersection(_ other: Self) -> Self { - var result = Self() - for item in self { - if other.contains(item) { - result._appendNew(item) - } - } - result._checkInvariants() - return result - } - - /// Removes the elements of this set that aren't also in the given one. - /// - /// var set: OrderedSet = [1, 2, 3, 4] - /// let other: OrderedSet = [6, 4, 2, 0] - /// set.formIntersection(other) - /// // set is now [2, 4] - /// - /// - Parameter other: A set of elements. - /// - /// - Complexity: Expected to be O(`self.count`) on average, if `Element` - /// implements high-quality hashing. - @inlinable - public mutating func formIntersection(_ other: Self) { - self = self.intersection(other) - } - - // Generalizations - - /// Returns a new set with the elements that are common to both this set and - /// the provided other one, in the order they appear in `self`. - /// - /// let set: OrderedSet = [1, 2, 3, 4] - /// let other: OrderedSet = [6, 4, 2, 0] - /// set.intersection(other) // [2, 4] - /// - /// - Parameter other: Another set. - /// - /// - Returns: A new set. - /// - /// - Complexity: Expected to be O(`self.count`) on average, if `Element` - /// implements high-quality hashing. - @inlinable - @inline(__always) - public __consuming func intersection(_ other: UnorderedView) -> Self { - intersection(other._base) - } - - /// Removes the elements of this set that aren't also in the given one. - /// - /// var set: OrderedSet = [1, 2, 3, 4] - /// let other: OrderedSet = [6, 4, 2, 0] - /// set.formIntersection(other) - /// // set is now [2, 4] - /// - /// - Parameter other: A set of elements. - /// - /// - Complexity: Expected to be O(`self.count`) on average, if `Element` - /// implements high-quality hashing. - @inlinable - @inline(__always) - public mutating func formIntersection(_ other: UnorderedView) { - formIntersection(other._base) - } - - /// Returns a new set with the elements that are common to both this set and - /// the provided sequence, in the order they appear in `self`. - /// - /// let set: OrderedSet = [1, 2, 3, 4] - /// set.intersection([6, 4, 2, 0] as Array) // [2, 4] - /// - /// - Parameter other: A finite sequence of elements. - /// - /// - Returns: A new set. - /// - /// - 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 __consuming func intersection( - _ other: S - ) -> Self where S.Element == Element { - _UnsafeBitset.withTemporaryBitset(capacity: self.count) { bitset in - for item in other { - if let index = self._find_inlined(item).index { - bitset.insert(index) - } - } - let result = self._extractSubset(using: bitset) - result._checkInvariants() - return result - } - } - - /// Removes the elements of this set that aren't also in the given sequence. - /// - /// var set: OrderedSet = [1, 2, 3, 4] - /// set.formIntersection([6, 4, 2, 0] as Array) - /// // set is now [2, 4] - /// - /// - Parameter other: A finite sequence of elements. - /// - /// - 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 mutating func formIntersection( - _ other: S - ) where S.Element == Element { - self = self.intersection(other) - } -} - -extension OrderedSet { - /// Returns a new set with the elements that are either in this set or in - /// `other`, but not in both. - /// - /// The result contains elements from `self` followed by elements in `other`, - /// in the same order they appeared in the original sets. - /// - /// let set: OrderedSet = [1, 2, 3, 4] - /// let other: OrderedSet = [6, 4, 2, 0] - /// set.symmetricDifference(other) // [1, 3, 6, 0] - /// - /// - Parameter other: Another set. - /// - /// - Returns: A new set. - /// - /// - Complexity: Expected to be O(`self.count + other.count`) on average, if - /// `Element` implements high-quality hashing. - @inlinable - public __consuming func symmetricDifference(_ other: __owned Self) -> Self { - _UnsafeBitset.withTemporaryBitset(capacity: self.count) { bitset1 in - _UnsafeBitset.withTemporaryBitset(capacity: other.count) { bitset2 in - bitset1.insertAll(upTo: self.count) - for item in other { - if let index = self._find(item).index { - bitset1.remove(index) - } - } - bitset2.insertAll(upTo: other.count) - for item in self { - if let index = other._find(item).index { - bitset2.remove(index) - } - } - var result = self._extractSubset(using: bitset1, - extraCapacity: bitset2.count) - for offset in bitset2 { - result._appendNew(other._elements[offset]) - } - result._checkInvariants() - return result - } - } - } - - /// Replace this set with the elements contained in this set or the given - /// set, but not both. - /// - /// On return, `self` contains elements originally from `self` followed by - /// elements in `other`, in the same order they appeared in the input values. - /// - /// var set: OrderedSet = [1, 2, 3, 4] - /// let other: OrderedSet = [6, 4, 2, 0] - /// set.formSymmetricDifference(other) - /// // set is now [1, 3, 6, 0] - /// - /// - Parameter other: Another set. - /// - /// - Complexity: Expected to be O(`self.count + other.count`) on average, if - /// `Element` implements high-quality hashing. - @inlinable - public mutating func formSymmetricDifference(_ other: __owned Self) { - self = self.symmetricDifference(other) - } - - // Generalizations - - /// Returns a new set with the elements that are either in this set or in - /// `other`, but not in both. - /// - /// The result contains elements from `self` followed by elements in `other`, - /// in the same order they appeared in the original sets. - /// - /// let set: OrderedSet = [1, 2, 3, 4] - /// let other: OrderedSet = [6, 4, 2, 0] - /// set.symmetricDifference(other.unordered) // [1, 3, 6, 0] - /// - /// - Parameter other: Another set. - /// - /// - Returns: A new set. - /// - /// - Complexity: Expected to be O(`self.count + other.count`) on average, if - /// `Element` implements high-quality hashing. - @inlinable - @inline(__always) - public __consuming func symmetricDifference( - _ other: __owned UnorderedView - ) -> Self { - symmetricDifference(other._base) - } - - /// Replace this set with the elements contained in this set or the given - /// set, but not both. - /// - /// On return, `self` contains elements originally from `self` followed by - /// elements in `other`, in the same order they appeared in the input values. - /// - /// var set: OrderedSet = [1, 2, 3, 4] - /// let other: OrderedSet = [6, 4, 2, 0] - /// set.formSymmetricDifference(other.unordered) - /// // set is now [1, 3, 6, 0] - /// - /// - Parameter other: Another set. - /// - /// - Complexity: Expected to be O(`self.count + other.count`) on average, if - /// `Element` implements high-quality hashing. - @inlinable - @inline(__always) - public mutating func formSymmetricDifference(_ other: __owned UnorderedView) { - formSymmetricDifference(other._base) - } - - /// Returns a new set with the elements that are either in this set or in - /// `other`, but not in both. - /// - /// The result contains elements from `self` followed by elements in `other`, - /// in the same order they appeared in the original input values. - /// - /// let set: OrderedSet = [1, 2, 3, 4] - /// let other: Array = [6, 4, 2, 0] - /// set.symmetricDifference(other) // [1, 3, 6, 0] - /// - /// - Parameter other: A finite sequence of elements. - /// - /// - Returns: A new set. - /// - /// - 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 __consuming func symmetricDifference( - _ other: __owned S - ) -> Self where S.Element == Element { - _UnsafeBitset.withTemporaryBitset(capacity: self.count) { bitset in - var new = Self() - bitset.insertAll(upTo: self.count) - for item in other { - if let index = self._find(item).index { - bitset.remove(index) - } else { - new.append(item) - } - } - var result = _extractSubset(using: bitset, extraCapacity: new.count) - for item in new._elements { - result._appendNew(item) - } - result._checkInvariants() - return result - } - } - - /// Replace this set with the elements contained in this set or the given - /// sequence, but not both. - /// - /// On return, `self` contains elements originally from `self` followed by - /// elements in `other`, in the same order they first appeared in the input - /// values. - /// - /// var set: OrderedSet = [1, 2, 3, 4] - /// set.formSymmetricDifference([6, 4, 2, 0] as Array) - /// // set is now [1, 3, 6, 0] - /// - /// - Parameter other: A finite sequence of elements. - /// - /// - 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 mutating func formSymmetricDifference( - _ other: __owned S - ) where S.Element == Element { - self = self.symmetricDifference(other) - } -} - -extension OrderedSet { - /// Returns a new set containing the elements of this set that do not occur - /// in the given set. - /// - /// The result contains elements in the same order they appear in `self`. - /// - /// let set: OrderedSet = [1, 2, 3, 4] - /// let other: OrderedSet = [6, 4, 2, 0] - /// set.subtracting(other) // [1, 3] - /// - /// - Parameter other: Another set. - /// - /// - Returns: A new set. - /// - /// - Complexity: Expected to be O(`self.count + other.count`) on average, if - /// `Element` implements high-quality hashing. - @inlinable - @inline(__always) - public __consuming func subtracting(_ other: Self) -> Self { - _subtracting(other) - } - - /// Removes the elements of the given set from this set. - /// - /// var set: OrderedSet = [1, 2, 3, 4] - /// let other: OrderedSet = [6, 4, 2, 0] - /// set.subtract(other) - /// // set is now [1, 3] - /// - /// - Parameter other: Another set. - /// - /// - Complexity: Expected to be O(`self.count + other.count`) on average, if - /// `Element` implements high-quality hashing. - @inlinable - @inline(__always) - public mutating func subtract(_ other: Self) { - self = subtracting(other) - } - - // Generalizations - - /// Returns a new set containing the elements of this set that do not occur - /// in the given set. - /// - /// The result contains elements in the same order they appear in `self`. - /// - /// let set: OrderedSet = [1, 2, 3, 4] - /// let other: OrderedSet = [6, 4, 2, 0] - /// set.subtracting(other.unordered) // [1, 3] - /// - /// - Parameter other: Another set. - /// - /// - Returns: A new set. - /// - /// - Complexity: Expected to be O(`self.count + other.count`) on average, if - /// `Element` implements high-quality hashing. - @inlinable - @inline(__always) - public __consuming func subtracting(_ other: UnorderedView) -> Self { - subtracting(other._base) - } - - /// Removes the elements of the given set from this set. - /// - /// var set: OrderedSet = [1, 2, 3, 4] - /// let other: OrderedSet = [6, 4, 2, 0] - /// set.subtract(other.unordered) - /// // set is now [1, 3] - /// - /// - Parameter other: Another set. - /// - /// - Complexity: Expected to be O(`self.count + other.count`) on average, if - /// `Element` implements high-quality hashing. - @inlinable - @inline(__always) - public mutating func subtract(_ other: UnorderedView) { - subtract(other._base) - } - - /// Returns a new set containing the elements of this set that do not occur - /// in the given sequence. - /// - /// The result contains elements in the same order they appear in `self`. - /// - /// let set: OrderedSet = [1, 2, 3, 4] - /// set.subtracting([6, 4, 2, 0] as Array) // [1, 3] - /// - /// - Parameter other: A finite sequence of elements. - /// - /// - Returns: A new set. - /// - /// - Complexity: Expected to be O(`self.count + other.count`) on average, if - /// `Element` implements high-quality hashing. - @inlinable - @inline(__always) - public __consuming func subtracting( - _ other: S - ) -> Self where S.Element == Element { - _subtracting(other) - } - - /// Removes the elements of the given sequence from this set. - /// - /// var set: OrderedSet = [1, 2, 3, 4] - /// set.subtract([6, 4, 2, 0] as Array) - /// // set is now [1, 3] - /// - /// - Parameter other: A finite sequence of elements. - /// - /// - 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 - @inline(__always) - public mutating func subtract( - _ other: S - ) where S.Element == Element { - self = _subtracting(other) - } - - @inlinable - __consuming func _subtracting( - _ other: S - ) -> Self where S.Element == Element { - guard count > 0 else { return Self() } - return _UnsafeBitset.withTemporaryBitset(capacity: count) { difference in - difference.insertAll(upTo: count) - for item in other { - if let index = self._find(item).index { - if difference.remove(index), difference.count == 0 { - return Self() - } - } - } - assert(difference.count > 0) - let result = _extractSubset(using: difference) - result._checkInvariants() - return result - } - } -} - - From 0914e6f546b303450a3d16f883267d4b89ee932c Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 21 Oct 2022 16:32:17 -0700 Subject: [PATCH 10/39] [OrderedSet] More test coverage for set operations; clarify docs --- ...+Partial SetAlgebra formIntersection.swift | 12 ++ ...eredSet+Partial SetAlgebra formUnion.swift | 19 +++ ...dSet+Partial SetAlgebra intersection.swift | 12 ++ ...rtial SetAlgebra symmetricDifference.swift | 3 + .../OrderedSet/OrderedSetTests.swift | 110 ++++++++++++++++++ 5 files changed, 156 insertions(+) diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra formIntersection.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra formIntersection.swift index f27e7455..9fa4d8a0 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra formIntersection.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra formIntersection.swift @@ -26,6 +26,10 @@ extension OrderedSet { /// set.formIntersection(other) /// // set is now [2, 4] /// + /// The result will only contain instances that were originally in `self`. + /// (This matters if equal members can be distinguished by comparing their + /// identities, or by some other means.) + /// /// - Parameter other: A set of elements. /// /// - Complexity: Expected to be O(`self.count`) on average, if `Element` @@ -44,6 +48,10 @@ extension OrderedSet { /// set.formIntersection(other) /// // set is now [2, 4] /// + /// The result will only contain instances that were originally in `self`. + /// (This matters if equal members can be distinguished by comparing their + /// identities, or by some other means.) + /// /// - Parameter other: A set of elements. /// /// - Complexity: Expected to be O(`self.count`) on average, if `Element` @@ -60,6 +68,10 @@ extension OrderedSet { /// set.formIntersection([6, 4, 2, 0] as Array) /// // set is now [2, 4] /// + /// The result will only contain instances that were originally in `self`. + /// (This matters if equal members can be distinguished by comparing their + /// identities, or by some other means.) + /// /// - Parameter other: A finite sequence of elements. /// /// - Complexity: Expected to be O(*n*) on average where *n* is the number of diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra formUnion.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra formUnion.swift index 36f0e567..79dd20c8 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra formUnion.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra formUnion.swift @@ -29,6 +29,11 @@ extension OrderedSet { /// a.formUnion(b) /// // `a` is now `[1, 2, 3, 4, 0, 6]` /// + /// For values that are members of both sets, this operation preserves the + /// instances that were originally in `self`. (This matters if equal members + /// can be distinguished by comparing their identities, or by some other + /// means.) + /// /// - Parameter other: The set of elements to insert. /// /// - Complexity: Expected to be O(`other.count`) on average, if `Element` @@ -50,6 +55,11 @@ extension OrderedSet { /// a.formUnion(b.unordered) /// // a is now [1, 2, 3, 4, 0, 6] /// + /// For values that are members of both inputs, this operation preserves the + /// instances that were originally in `self`. (This matters if equal members + /// can be distinguished by comparing their identities, or by some other + /// means.) + /// /// - Parameter other: The set of elements to add. /// /// - Complexity: Expected to be O(`self.count` + `other.count`) on average, @@ -70,6 +80,15 @@ extension OrderedSet { /// a.formUnion(b) /// // a is now [1, 2, 3, 4, 0, 6] /// + /// For values that are members of both inputs, this operation preserves the + /// instances that were originally in `self`. (This matters if equal members + /// can be distinguished by comparing their identities, or by some other + /// means.) + /// + /// If some of the values that are missing from `self` have multiple copies + /// in `other`, then the result of this function always contains the first + /// instances in the sequence -- the second and subsequent copies are ignored. + /// /// - Parameter other: A finite sequence of elements. /// /// - Complexity: Expected to be O(`self.count` + `other.count`) on average, diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra intersection.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra intersection.swift index 5fb39d9a..983125d0 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra intersection.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra intersection.swift @@ -26,6 +26,10 @@ extension OrderedSet { /// let other: OrderedSet = [6, 4, 2, 0] /// set.intersection(other) // [2, 4] /// + /// The result will only contain instances that were originally in `self`. + /// (This matters if equal members can be distinguished by comparing their + /// identities, or by some other means.) + /// /// - Parameter other: Another set. /// /// - Returns: A new set. @@ -53,6 +57,10 @@ extension OrderedSet { /// let other: OrderedSet = [6, 4, 2, 0] /// set.intersection(other) // [2, 4] /// + /// The result will only contain instances that were originally in `self`. + /// (This matters if equal members can be distinguished by comparing their + /// identities, or by some other means.) + /// /// - Parameter other: Another set. /// /// - Returns: A new set. @@ -71,6 +79,10 @@ extension OrderedSet { /// let set: OrderedSet = [1, 2, 3, 4] /// set.intersection([6, 4, 2, 0] as Array) // [2, 4] /// + /// The result will only contain instances that were originally in `self`. + /// (This matters if equal members can be distinguished by comparing their + /// identities, or by some other means.) + /// /// - Parameter other: A finite sequence of elements. /// /// - Returns: A new set. diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra symmetricDifference.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra symmetricDifference.swift index 9a3da59a..a58d5a55 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra symmetricDifference.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra symmetricDifference.swift @@ -98,6 +98,9 @@ extension OrderedSet { /// let other: Array = [6, 4, 2, 0] /// set.symmetricDifference(other) // [1, 3, 6, 0] /// + /// In case the sequence contains duplicate elements, only the first instance + /// matters -- the second and subsequent instances are ignored by this method. + /// /// - Parameter other: A finite sequence of elements. /// /// - Returns: A new set. diff --git a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift index 02480b78..2c2e9004 100644 --- a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift +++ b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift @@ -952,6 +952,9 @@ class OrderedSetTests: CollectionTestCase { let actual1 = u1.union(u2) expectEqualElements(actual1, expected) + let actual1u = u1.union(u2.unordered) + expectEqualElements(actual1u, expected) + let actual2 = actual1.union(u2).union(u1) expectEqualElements(actual2, expected) } @@ -977,6 +980,26 @@ class OrderedSetTests: CollectionTestCase { } } + func test_formUnion_UnorderedView() { + withSampleRanges { r1, r2 in + let expected = Set(r1).union(r2).sorted() + + var res: OrderedSet = [] + + let u1 = OrderedSet(r1) + res.formUnion(u1.unordered) + expectEqualElements(res, r1) + + let u2 = OrderedSet(r2) + res.formUnion(u2.unordered) + expectEqualElements(res, expected) + + res.formUnion(u1.unordered) + res.formUnion(u2.unordered) + expectEqualElements(res, expected) + } + } + func test_union_generic() { withSampleRanges { r1, r2 in let expected = Set(r1).union(r2).sorted() @@ -986,6 +1009,13 @@ class OrderedSetTests: CollectionTestCase { let u3 = u2.union(r1) expectEqualElements(u3, expected) + + let a = Array(r2) + let actual3 = u1.union(a) + expectEqualElements(actual3, expected) + + let actual4 = u1.union(a + a) + expectEqualElements(actual4, expected) } } @@ -1016,6 +1046,9 @@ class OrderedSetTests: CollectionTestCase { let actual1 = u1.intersection(u2) expectEqualElements(actual1, expected) + let actual1u = u1.intersection(u2.unordered) + expectEqualElements(actual1u, expected) + let actual2 = actual1.intersection(r1) expectEqualElements(actual2, expected) } @@ -1038,6 +1071,23 @@ class OrderedSetTests: CollectionTestCase { } } + func test_formIntersection_UnorderedView() { + withSampleRanges { r1, r2 in + let expected = Set(r1).intersection(r2).sorted() + + let u1 = OrderedSet(r1) + let u2 = OrderedSet(r2) + var res = u1 + res.formIntersection(u2.unordered) + expectEqualElements(res, expected) + expectEqualElements(u1, r1) + + res.formIntersection(u1.unordered) + res.formIntersection(u2.unordered) + expectEqualElements(res, expected) + } + } + func test_intersection_generic() { withSampleRanges { r1, r2 in let expected = Set(r1).intersection(r2).sorted() @@ -1048,6 +1098,13 @@ class OrderedSetTests: CollectionTestCase { let actual2 = actual1.intersection(r1).intersection(r2) expectEqualElements(actual2, expected) + + let a = Array(r2) + let actual3 = u1.intersection(a) + expectEqualElements(actual3, expected) + + let actual4 = u1.intersection(a + a) + expectEqualElements(actual4, expected) } } @@ -1074,6 +1131,9 @@ class OrderedSetTests: CollectionTestCase { let actual1 = u1.symmetricDifference(u2) expectEqualElements(actual1, expected) + let actual1u = u1.symmetricDifference(u2.unordered) + expectEqualElements(actual1u, expected) + let actual2 = actual1.symmetricDifference(u1).symmetricDifference(u2) expectEqual(actual2.count, 0) } @@ -1096,6 +1156,23 @@ class OrderedSetTests: CollectionTestCase { } } + func test_formSymmetricDifference_UnorderedView() { + withSampleRanges { r1, r2 in + let expected = Set(r1).symmetricDifference(r2).sorted() + + let u1 = OrderedSet(r1) + let u2 = OrderedSet(r2) + var res = u1 + res.formSymmetricDifference(u2.unordered) + expectEqualElements(res, expected) + expectEqualElements(u1, r1) + + res.formSymmetricDifference(u1.unordered) + res.formSymmetricDifference(u2.unordered) + expectEqual(res.count, 0) + } + } + func test_symmetricDifference_generic() { withSampleRanges { r1, r2 in let expected = Set(r1).symmetricDifference(r2).sorted() @@ -1106,6 +1183,13 @@ class OrderedSetTests: CollectionTestCase { let actual2 = actual1.symmetricDifference(r1).symmetricDifference(r2) expectEqual(actual2.count, 0) + + let a = Array(r2) + let actual3 = u1.symmetricDifference(a) + expectEqualElements(actual3, expected) + + let actual4 = u1.symmetricDifference(a + a) + expectEqualElements(actual4, expected) } } @@ -1132,6 +1216,9 @@ class OrderedSetTests: CollectionTestCase { let actual1 = u1.subtracting(u2) expectEqualElements(actual1, expected) + let actual1u = u1.subtracting(u2.unordered) + expectEqualElements(actual1u, expected) + let actual2 = actual1.subtracting(u2) expectEqualElements(actual2, expected) } @@ -1153,6 +1240,22 @@ class OrderedSetTests: CollectionTestCase { } } + func test_subtract_UnorderedView() { + withSampleRanges { r1, r2 in + let expected = Set(r1).subtracting(r2).sorted() + + let u1 = OrderedSet(r1) + let u2 = OrderedSet(r2) + var res = u1 + res.subtract(u2.unordered) + expectEqualElements(res, expected) + expectEqualElements(u1, r1) + + res.subtract(u2.unordered) + expectEqualElements(res, expected) + } + } + func test_subtracting_generic() { withSampleRanges { r1, r2 in let expected = Set(r1).subtracting(r2).sorted() @@ -1163,6 +1266,13 @@ class OrderedSetTests: CollectionTestCase { let actual2 = actual1.subtracting(r2) expectEqualElements(actual2, expected) + + let a = Array(r2) + let actual3 = u1.subtracting(a) + expectEqualElements(actual3, expected) + + let actual4 = u1.subtracting(a + a) + expectEqualElements(actual4, expected) } } From 1355d478afc506d2bb9ccb42116534c421d006f9 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 21 Oct 2022 18:23:31 -0700 Subject: [PATCH 11/39] [BitSet] Review, test, extend, and document binary set operations --- .../BitSet/BitSet+Initializers.swift | 17 + .../BitSet+SetAlgebra formIntersection.swift | 43 +- ...t+SetAlgebra formSymmetricDifference.swift | 62 ++- .../BitSet/BitSet+SetAlgebra formUnion.swift | 61 ++- .../BitSet+SetAlgebra intersection.swift | 57 +- .../BitSet/BitSet+SetAlgebra isEqual.swift | 17 +- .../BitSet/BitSet+SetAlgebra subtract.swift | 64 ++- .../BitSet+SetAlgebra subtracting.swift | 58 +- ...itSet+SetAlgebra symmetricDifference.swift | 55 +- .../BitSet/BitSet+SetAlgebra union.swift | 51 +- Tests/BitCollectionsTests/BitSetTests.swift | 518 +++++++++++------- 11 files changed, 613 insertions(+), 390 deletions(-) diff --git a/Sources/BitCollections/BitSet/BitSet+Initializers.swift b/Sources/BitCollections/BitSet/BitSet+Initializers.swift index 3c23994b..0a71cf67 100644 --- a/Sources/BitCollections/BitSet/BitSet+Initializers.swift +++ b/Sources/BitCollections/BitSet/BitSet+Initializers.swift @@ -91,12 +91,25 @@ extension BitSet { self = (elements as! BitSet) return } + if S.self == BitSet.Counted.self { + self = (elements as! BitSet.Counted)._bits + return + } self.init() for value in elements { self.insert(value) } } + /// Create a new bit set containing all the nonnegative elements of a + /// sequence of integers. + /// + /// Items in `elements` that are negative are silently ignored. + /// + /// - Parameters: + /// - elements: The sequence of elements to turn into a bit set. + /// + /// - Complexity: O(*n*), where *n* is the number of elements in the sequence. @inlinable internal init( _validMembersOf elements: __owned S @@ -105,6 +118,10 @@ extension BitSet { self = (elements as! BitSet) return } + if S.self == BitSet.Counted.self { + self = (elements as! BitSet.Counted)._bits + return + } if S.self == Range.self { let r = (elements as! Range) self.init(_range: r._clampedToUInt()) diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra formIntersection.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra formIntersection.swift index 97c32313..7ea633e3 100644 --- a/Sources/BitCollections/BitSet/BitSet+SetAlgebra formIntersection.swift +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra formIntersection.swift @@ -32,26 +32,18 @@ extension BitSet { } } - /// Removes the elements of this set that aren't also in the given sequence. + /// Removes the elements of this set that aren't also in the given one. /// /// var set: BitSet = [1, 2, 3, 4] - /// let other: Set = [6, 4, 2, 0] + /// let other: BitSet.Counted = [0, 2, 4, 6] /// set.formIntersection(other) /// // set is now [2, 4] /// - /// - Parameter other: A sequence of integers. + /// - Parameter other: A bit set. /// - /// - Complexity: O(*max*) + *k*, where *max* is the largest item in `self`, - /// and *k* is the complexity of iterating over all elements in `other`. - @inlinable - public mutating func formIntersection( - _ other: __owned S - ) where S.Element == Int { - if S.self == Range.self { - formIntersection(other as! Range) - return - } - formIntersection(BitSet(_validMembersOf: other)) + /// - Complexity: O(*max*), where *max* is the largest item in either set. + public mutating func formIntersection(_ other: BitSet.Counted) { + formIntersection(other._bits) } /// Removes the elements of this set that aren't also in the given range. @@ -77,4 +69,27 @@ extension BitSet { handle.formIntersection(other) } } + + /// Removes the elements of this set that aren't also in the given sequence. + /// + /// var set: BitSet = [1, 2, 3, 4] + /// let other: Set = [6, 4, 2, 0] + /// set.formIntersection(other) + /// // set is now [2, 4] + /// + /// - Parameter other: A sequence of integers. + /// + /// - Complexity: O(*max*) + *k*, where *max* is the largest item in `self`, + /// and *k* is the complexity of iterating over all elements in `other`. + @inlinable + public mutating func formIntersection( + _ other: __owned S + ) where S.Element == Int { + if S.self == Range.self { + formIntersection(other as! Range) + return + } + // Note: BitSet & BitSet.Counted are handled in the BitSet initializer below + formIntersection(BitSet(_validMembersOf: other)) + } } diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra formSymmetricDifference.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra formSymmetricDifference.swift index 743c79aa..fdc0e116 100644 --- a/Sources/BitCollections/BitSet/BitSet+SetAlgebra formSymmetricDifference.swift +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra formSymmetricDifference.swift @@ -21,7 +21,7 @@ extension BitSet { /// - Parameter other: Another set. /// /// - Complexity: O(*max*), where *max* is the largest item in either set. - public mutating func formSymmetricDifference(_ other: __owned Self) { + public mutating func formSymmetricDifference(_ other: Self) { _ensureCapacity(limit: other._capacity) _updateThenShrink { target, shrink in other._read { source in @@ -31,6 +31,42 @@ extension BitSet { } } + /// Replace this set with the elements contained in this set or the given + /// set, but not both. + /// + /// var set: BitSet = [1, 2, 3, 4] + /// let other: BitSet.Counted = [0, 2, 4, 6] + /// set.formSymmetricDifference(other) + /// // set is now [0, 1, 3, 6] + /// + /// - Parameter other: Another set. + /// + /// - Complexity: O(*max*), where *max* is the largest item in either set. + public mutating func formSymmetricDifference(_ other: BitSet.Counted) { + formSymmetricDifference(other._bits) + } + + /// Replace this set with the elements contained in this set or the given + /// range of integers, but not both. + /// + /// var set: BitSet = [1, 2, 3, 4] + /// set.formSymmetricDifference(3 ..< 7) + /// // set is now [1, 2, 5, 6] + /// + /// - Parameter other: A range of nonnegative integers. + /// + /// - Complexity: O(*max*), where *max* is the largest item in either input. + public mutating func formSymmetricDifference(_ other: Range) { + guard let other = other._toUInt() else { + preconditionFailure("Invalid range") + } + guard !other.isEmpty else { return } + _ensureCapacity(limit: other.upperBound) + _updateThenShrink { handle, shrink in + handle.formSymmetricDifference(other) + } + } + /// Replace this set with the elements contained in this set or the given /// sequence, but not both. /// @@ -52,29 +88,7 @@ extension BitSet { formSymmetricDifference(other as! Range) return } + // Note: BitSet & BitSet.Counted are handled in the BitSet initializer below formSymmetricDifference(BitSet(other)) } } - -extension BitSet { - /// Replace this set with the elements contained in this set or the given - /// range of integers, but not both. - /// - /// var set: BitSet = [1, 2, 3, 4] - /// set.formSymmetricDifference(3 ..< 7) - /// // set is now [1, 2, 5, 6] - /// - /// - Parameter other: A range of nonnegative integers. - /// - /// - Complexity: O(*max*), where *max* is the largest item in either input. - public mutating func formSymmetricDifference(_ other: Range) { - guard let other = other._toUInt() else { - preconditionFailure("Invalid range") - } - guard !other.isEmpty else { return } - _ensureCapacity(limit: other.upperBound) - _updateThenShrink { handle, shrink in - handle.formSymmetricDifference(other) - } - } -} diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra formUnion.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra formUnion.swift index 2826dcac..b8706a53 100644 --- a/Sources/BitCollections/BitSet/BitSet+SetAlgebra formUnion.swift +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra formUnion.swift @@ -20,7 +20,7 @@ extension BitSet { /// - Parameter other: The set of elements to insert. /// /// - Complexity: O(*max*), where *max* is the largest item in either input. - public mutating func formUnion(_ other: __owned Self) { + public mutating func formUnion(_ other: Self) { _ensureCapacity(limit: other._capacity) _update { target in other._read { source in @@ -29,6 +29,40 @@ extension BitSet { } } + /// Adds the elements of the given set to this set. + /// + /// var set: BitSet = [1, 2, 3, 4] + /// let other: BitSet.Counted = [0, 2, 4, 6] + /// set.formUnion(other) + /// // `set` is now `[0, 1, 2, 3, 4, 6]` + /// + /// - Parameter other: The set of elements to insert. + /// + /// - Complexity: O(*max*), where *max* is the largest item in either input. + public mutating func formUnion(_ other: BitSet.Counted) { + formUnion(other._bits) + } + + /// Adds the elements of the given range of integers to this set. + /// + /// var set: BitSet = [1, 2, 3, 4] + /// set.formUnion(3 ..< 7) + /// // `set` is now `[1, 2, 3, 4, 5, 6]` + /// + /// - Parameter other: A range of nonnegative integers. + /// + /// - Complexity: O(*max*), where *max* is the largest item in either input. + public mutating func formUnion(_ other: Range) { + guard let other = other._toUInt() else { + preconditionFailure("Invalid range") + } + guard !other.isEmpty else { return } + _ensureCapacity(limit: other.upperBound) + _update { handle in + handle.formUnion(other) + } + } + /// Adds the elements of the given sequence to this set. /// /// var set: BitSet = [1, 2, 3, 4] @@ -61,29 +95,4 @@ extension BitSet { self.insert(value) } } - - public mutating func formUnion(_ other: __owned BitSet.Counted) { - formUnion(other._bits) - } - - /// Adds the elements of the given range of integers to this set. - /// - /// var set: BitSet = [1, 2, 3, 4] - /// set.formUnion(3 ..< 7) - /// // `set` is now `[1, 2, 3, 4, 5, 6]` - /// - /// - Parameter other: A range of nonnegative integers. - /// - /// - Complexity: O(*max*), where *max* is the largest item in either input. - public mutating func formUnion(_ other: Range) { - guard let other = other._toUInt() else { - preconditionFailure("Invalid range") - } - guard !other.isEmpty else { return } - _ensureCapacity(limit: other.upperBound) - _update { handle in - handle.formUnion(other) - } - } } - diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra intersection.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra intersection.swift index ce5b6edb..a63659b4 100644 --- a/Sources/BitCollections/BitSet/BitSet+SetAlgebra intersection.swift +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra intersection.swift @@ -21,7 +21,7 @@ extension BitSet { /// - Parameter other: A bit set. /// /// - Complexity: O(*max*), where *max* is the largest item in either set. - public __consuming func intersection(_ other: Self) -> Self { + public func intersection(_ other: Self) -> Self { self._read { first in other._read { second in Self( @@ -32,6 +32,38 @@ extension BitSet { } } + /// Returns a new bit set with the elements that are common to both this set + /// and the given set. + /// + /// let a: BitSet = [1, 2, 3, 4] + /// let b: BitSet.Counted = [6, 4, 2, 0] + /// let c = a.intersection(b) + /// // c is now [2, 4] + /// + /// - Parameter other: A bit set. + /// + /// - Complexity: O(*max*), where *max* is the largest item in either set. + public func intersection(_ other: BitSet.Counted) -> Self { + self.intersection(other._bits) + } + + /// Returns a new bit set with the elements that are common to both this set + /// and the given range of integers. + /// + /// let a: BitSet = [1, 2, 3, 4] + /// let c = a.intersection(-10 ..< 3) + /// // c is now [3, 4] + /// + /// - Parameter other: A range of integers. + /// + /// - Complexity: O(*max*) + *k*, where *max* is the largest item in `self`, + /// and *k* is the complexity of iterating over all elements in `other`. + public func intersection(_ other: Range) -> Self { + var result = self + result.formIntersection(other) + return result + } + /// Returns a new bit set with the elements that are common to both this set /// and the given sequence. /// @@ -45,34 +77,15 @@ extension BitSet { /// - Complexity: O(*max*) + *k*, where *max* is the largest item in `self`, /// and *k* is the complexity of iterating over all elements in `other`. @inlinable - public __consuming func intersection( + public func intersection( _ other: __owned S ) -> Self where S.Element == Int { - if S.self == Self.self { - return intersection(other as! BitSet) - } if S.self == Range.self { return intersection(other as! Range) } + // Note: BitSet & BitSet.Counted are handled in the BitSet initializer below return intersection(BitSet(_validMembersOf: other)) } - - /// Returns a new bit set with the elements that are common to both this set - /// and the given range of integers. - /// - /// let a: BitSet = [1, 2, 3, 4] - /// let c = a.intersection(-10 ..< 3) - /// // c is now [3, 4] - /// - /// - Parameter other: A range of integers. - /// - /// - Complexity: O(*max*) + *k*, where *max* is the largest item in `self`, - /// and *k* is the complexity of iterating over all elements in `other`. - public __consuming func intersection(_ other: Range) -> Self { - var result = self - result.formIntersection(other) - return result - } } diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isEqual.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isEqual.swift index 04e58099..2e3d1dbb 100644 --- a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isEqual.swift +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isEqual.swift @@ -22,6 +22,15 @@ extension BitSet { self._storage == other._storage } + /// 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 value of the largest member of + /// either set. + public func isEqual(to other: BitSet.Counted) -> Bool { + self.isEqual(to: other._bits) + } + /// Returns a Boolean value indicating whether a bit set is equal to a range /// of integers, i.e., whether they contain the same values. /// @@ -32,14 +41,6 @@ extension BitSet { 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. /// diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra subtract.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra subtract.swift index 2ec4ef31..06fcbfe9 100644 --- a/Sources/BitCollections/BitSet/BitSet+SetAlgebra subtract.swift +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra subtract.swift @@ -31,12 +31,40 @@ extension BitSet { } } + /// Removes the elements of the given bit set from this set. + /// + /// var set: BitSet = [1, 2, 3, 4] + /// let other: BitSet.Counted = [0, 2, 4, 6] + /// set.subtract(other) + /// // set is now [1, 3] + /// + /// - Parameter other: Another bit set. + /// + /// - Complexity: O(*max*), where *max* is the largest item in either input. + public mutating func subtract(_ other: BitSet.Counted) { + subtract(other._bits) + } + + /// Removes the elements of the given range of integers from this set. + /// + /// var set: BitSet = [1, 2, 3, 4] + /// set.subtract(-10 ..< 3) + /// // set is now [3, 4] + /// + /// - Parameter other: A range of arbitrary integers. + /// + /// - Returns: A new set. + /// + /// - Complexity: O(*max*), where *max* is the largest item in self. + public mutating func subtract(_ other: Range) { + _subtract(other._clampedToUInt()) + } + @usableFromInline - internal mutating func _subtract(_ next: () -> UInt?) { + internal mutating func _subtract(_ other: Range) { + guard !other.isEmpty else { return } _updateThenShrink { handle, shrink in - while let value = next() { - handle.remove(value) - } + handle.subtract(other) } } @@ -53,7 +81,7 @@ extension BitSet { /// and *k* is the complexity of iterating over all elements in `other`. @inlinable public mutating func subtract( - _ other: __owned S + _ other: S ) where S.Element == Int { if S.self == BitSet.self { self.subtract(other as! BitSet) @@ -78,30 +106,12 @@ extension BitSet { } } - public mutating func subtract(_ other: BitSet.Counted) { - subtract(other._bits) - } - @usableFromInline - internal mutating func _subtract(_ other: Range) { - guard !other.isEmpty else { return } + internal mutating func _subtract(_ next: () -> UInt?) { _updateThenShrink { handle, shrink in - handle.subtract(other) + while let value = next() { + handle.remove(value) + } } } - - /// Removes the elements of the given range of integers from this set. - /// - /// var set: BitSet = [1, 2, 3, 4] - /// set.subtract(-10 ..< 3) - /// // set is now [3, 4] - /// - /// - Parameter other: A range of arbitrary integers. - /// - /// - Returns: A new set. - /// - /// - Complexity: O(*max*), where *max* is the largest item in self. - public mutating func subtract(_ other: Range) { - _subtract(other._clampedToUInt()) - } } diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra subtracting.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra subtracting.swift index 36bd3655..a58eee63 100644 --- a/Sources/BitCollections/BitSet/BitSet+SetAlgebra subtracting.swift +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra subtracting.swift @@ -22,7 +22,7 @@ extension BitSet { /// - Returns: A new set. /// /// - Complexity: O(*max*), where *max* is the largest item in either input. - public __consuming func subtracting(_ other: Self) -> Self { + public func subtracting(_ other: Self) -> Self { self._read { first in other._read { second in Self( @@ -33,6 +33,39 @@ extension BitSet { } } + /// Returns a new set containing the elements of this set that do not occur + /// in the given other set. + /// + /// let set: BitSet = [1, 2, 3, 4] + /// let other: BitSet.Counted = [0, 2, 4, 6] + /// set.subtracting(other) // [1, 3] + /// + /// - Parameter other: Another bit set. + /// + /// - Returns: A new set. + /// + /// - Complexity: O(*max*), where *max* is the largest item in either input. + public func subtracting(_ other: BitSet.Counted) -> Self { + subtracting(other._bits) + } + + /// Returns a new set containing the elements of this set that do not occur + /// in the given range of integers. + /// + /// let set: BitSet = [1, 2, 3, 4] + /// set.subtracting(-10 ..< 3) // [3, 4] + /// + /// - Parameter other: A range of arbitrary integers. + /// + /// - Returns: A new set. + /// + /// - Complexity: O(*max*), where *max* is the largest item in self. + public func subtracting(_ other: Range) -> Self { + var result = self + result.subtract(other) + return result + } + /// Returns a new set containing the elements of this set that do not occur /// in the given sequence of integers. /// @@ -47,7 +80,7 @@ extension BitSet { /// - Complexity: O(*max*) + *k*, where *max* is the largest item in `self`, /// and *k* is the complexity of iterating over all elements in `other`. @inlinable - public __consuming func subtracting( + public func subtracting( _ other: __owned S ) -> Self where S.Element == Int @@ -56,25 +89,4 @@ extension BitSet { result.subtract(other) return result } - - public __consuming func subtracting(_ other: BitSet.Counted) -> Self { - subtracting(other._bits) - } - - /// Returns a new set containing the elements of this set that do not occur - /// in the given range of integers. - /// - /// let set: BitSet = [1, 2, 3, 4] - /// set.subtracting(-10 ..< 3) // [3, 4] - /// - /// - Parameter other: A range of arbitrary integers. - /// - /// - Returns: A new set. - /// - /// - Complexity: O(*max*), where *max* is the largest item in self. - public __consuming func subtracting(_ other: Range) -> Self { - var result = self - result.subtract(other) - return result - } } diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra symmetricDifference.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra symmetricDifference.swift index ad3fcf68..79e8cbb8 100644 --- a/Sources/BitCollections/BitSet/BitSet+SetAlgebra symmetricDifference.swift +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra symmetricDifference.swift @@ -22,7 +22,7 @@ extension BitSet { /// - Returns: A new set. /// /// - Complexity: O(*max*), where *max* is the largest item in either set. - public __consuming func symmetricDifference(_ other: __owned Self) -> Self { + public func symmetricDifference(_ other: Self) -> Self { self._read { first in other._read { second in Self( @@ -33,6 +33,39 @@ extension BitSet { } } + /// Returns a new bit set with the elements that are either in this set or in + /// `other`, but not in both. + /// + /// let set: BitSet = [1, 2, 3, 4] + /// let other: BitSet.Counted = [6, 4, 2, 0] + /// set.symmetricDifference(other) // [0, 1, 3, 6] + /// + /// - Parameter other: Another set. + /// + /// - Returns: A new set. + /// + /// - Complexity: O(*max*), where *max* is the largest item in either set. + public func symmetricDifference(_ other: Counted) -> Self { + symmetricDifference(other._bits) + } + + /// Returns a new bit set with the elements that are either in this set or in + /// `other`, but not in both. + /// + /// let set: BitSet = [1, 2, 3, 4] + /// set.formSymmetricDifference(3 ..< 7) // [1, 2, 5, 6] + /// + /// - Parameter other: A range of nonnegative integers. + /// + /// - Returns: A new set. + /// + /// - Complexity: O(*max*), where *max* is the largest item in either input. + public func symmetricDifference(_ other: Range) -> Self { + var result = self + result.formSymmetricDifference(other) + return result + } + /// Returns a new bit set with the elements that are either in this set or in /// `other`, but not in both. /// @@ -46,7 +79,7 @@ extension BitSet { /// input, and *k* is the complexity of iterating over all elements in /// `other`. @inlinable - public __consuming func symmetricDifference( + public func symmetricDifference( _ other: __owned S ) -> Self where S.Element == Int @@ -54,23 +87,7 @@ extension BitSet { if S.self == Range.self { return symmetricDifference(other as! Range) } + // Note: BitSet & BitSet.Counted are handled in the BitSet initializer below return symmetricDifference(BitSet(other)) } - - /// Returns a new bit set with the elements that are either in this set or in - /// `other`, but not in both. - /// - /// let set: BitSet = [1, 2, 3, 4] - /// set.formSymmetricDifference(3 ..< 7) // [1, 2, 5, 6] - /// - /// - Parameter other: A range of nonnegative integers. - /// - /// - Returns: A new set. - /// - /// - Complexity: O(*max*), where *max* is the largest item in either input. - public __consuming func symmetricDifference(_ other: Range) -> Self { - var result = self - result.formSymmetricDifference(other) - return result - } } diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra union.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra union.swift index ed0689a3..21e9187f 100644 --- a/Sources/BitCollections/BitSet/BitSet+SetAlgebra union.swift +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra union.swift @@ -19,7 +19,7 @@ extension BitSet { /// - Parameter other: The set of elements to insert. /// /// - Complexity: O(*max*), where *max* is the largest item in either input. - public __consuming func union(_ other: __owned Self) -> Self { + public func union(_ other: Self) -> Self { self._read { first in other._read { second in Self( @@ -30,6 +30,34 @@ extension BitSet { } } + /// Returns a new set with the elements of both this and the given set. + /// + /// let set: BitSet = [1, 2, 3, 4] + /// let other: BitSet = [0, 2, 4, 6] + /// set.union(other) // [0, 1, 2, 3, 4, 6] + /// + /// - Parameter other: The set of elements to insert. + /// + /// - Complexity: O(*max*), where *max* is the largest item in either input. + public func union(_ other: BitSet.Counted) -> Self { + union(other._bits) + } + + /// Returns a new set with the elements of both this set and the given + /// range of integers. + /// + /// let set: BitSet = [1, 2, 3, 4] + /// set.union(3 ..< 7) // [1, 2, 3, 4, 5, 6] + /// + /// - Parameter other: A range of nonnegative integers. + /// + /// - Complexity: O(*max*), where *max* is the largest item in either input. + public func union(_ other: Range) -> Self { + var result = self + result.formUnion(other) + return result + } + /// Returns a new set with the elements of both this set and the given /// sequence of integers. /// @@ -43,7 +71,7 @@ extension BitSet { /// input, and *k* is the complexity of iterating over all elements in /// `other`. @inlinable - public __consuming func union( + public func union( _ other: __owned S ) -> Self where S.Element == Int @@ -61,23 +89,4 @@ extension BitSet { result.formUnion(other) return result } - - public __consuming func union(_ other: __owned BitSet.Counted) -> Self { - union(other._bits) - } - - /// Returns a new set with the elements of both this set and the given - /// range of integers. - /// - /// let set: BitSet = [1, 2, 3, 4] - /// set.union(3 ..< 7) // [1, 2, 3, 4, 5, 6] - /// - /// - Parameter other: A range of nonnegative integers. - /// - /// - Complexity: O(*max*), where *max* is the largest item in either input. - public __consuming func union(_ other: Range) -> Self { - var result = self - result.formUnion(other) - return result - } } diff --git a/Tests/BitCollectionsTests/BitSetTests.swift b/Tests/BitCollectionsTests/BitSetTests.swift index aceead6a..bd204cc9 100644 --- a/Tests/BitCollectionsTests/BitSetTests.swift +++ b/Tests/BitCollectionsTests/BitSetTests.swift @@ -495,31 +495,27 @@ final class BitSetTest: CollectionTestCase { expectEqual(try MinimalDecoder.decode(v4, as: BitSet.self), b4) } - func test_union_Self() { + func test_union() { withInterestingSets("a", maximum: 200) { a in withInterestingSets("b", maximum: 200) { b in let expected = a.union(b).sorted() - let c = BitSet(a) - let d = BitSet(b) - let actual = c.union(d) - expectEqualElements(actual, expected) - } - } - } + let x = BitSet(a) + let y = BitSet(b) + let z = Array(b) - func test_union_Sequence() { - withInterestingSets("a", maximum: 200) { a in - withInterestingSets("b", maximum: 200) { b in - let expected = a.union(b).sorted() - let c = BitSet(a) - let actual = c.union(b) - expectEqualElements(actual, expected) + expectEqualElements(x.union(b), expected) + expectEqualElements(x.union(y), expected) + expectEqualElements(x.union(y.counted), expected) func union(_ first: BitSet,_ second: S) -> BitSet where S.Element == Int { first.union(second) } - expectEqualElements(union(c, BitSet(b)), expected) + + expectEqualElements(union(x, y), expected) + expectEqualElements(union(x, y.counted), expected) + expectEqualElements(x.union(z), expected) + expectEqualElements(x.union(z + z), expected) } } } @@ -545,38 +541,72 @@ final class BitSetTest: CollectionTestCase { let g = f.union(30*step ..< 30*step) expectEqualElements(g, 0 ..< 30*step) - } - } - func test_formUnion_Self() { - withInterestingSets("a", maximum: 200) { a in - withInterestingSets("b", maximum: 200) { b in - let expected = a.union(b).sorted() - var c = BitSet(a) - let d = BitSet(b) - c.formUnion(d) - expectEqualElements(c, expected) + func union(_ first: BitSet,_ second: S) -> BitSet + where S.Element == Int { + first.union(second) } + + let h = union(f, 20*step ..< 40*step) + expectEqualElements(h, 0 ..< 40*step) } } - func test_formUnion_Sequence() { + func test_formUnion() { withInterestingSets("a", maximum: 200) { a in withInterestingSets("b", maximum: 200) { b in let expected = a.union(b).sorted() - var c = BitSet(a) - c.formUnion(b) - expectEqualElements(c, expected) + let c = BitSet(b) + let d = Array(b) + withEvery("shared", in: [false, true]) { shared in + do { + var x = BitSet(a) + withHiddenCopies(if: shared, of: &x) { x in + x.formUnion(c) + expectEqualElements(x, expected) + } + } + do { + var x = BitSet(a) + withHiddenCopies(if: shared, of: &x) { x in + x.formUnion(c.counted) + expectEqualElements(x, expected) + } + } + func formUnion(_ first: inout BitSet, _ second: S) + where S.Element == Int { + first.formUnion(second) + } + do { + var x = BitSet(a) + withHiddenCopies(if: shared, of: &x) { x in + formUnion(&x, c) + expectEqualElements(x, expected) + } + } + do { + var x = BitSet(a) + withHiddenCopies(if: shared, of: &x) { x in + formUnion(&x, c.counted) + expectEqualElements(x, expected) + } + } - func union(_ first: inout BitSet, _ second: S) - where S.Element == Int { - first.formUnion(second) + do { + var x = BitSet(a) + withHiddenCopies(if: shared, of: &x) { x in + x.formUnion(d) + expectEqualElements(x, expected) + } + } + do { + var x = BitSet(a) + withHiddenCopies(if: shared, of: &x) { x in + x.formUnion(d + d) + expectEqualElements(x, expected) + } + } } - var d = BitSet(a) - union(&d, BitSet(b)) - expectEqualElements(d, expected) - union(&d, 0 ..< 200) - expectEqualElements(d, 0 ..< 200) } } } @@ -602,40 +632,38 @@ final class BitSetTest: CollectionTestCase { a.formUnion(30*step ..< 30*step) expectEqualElements(a, 0 ..< 30*step) - } - } - func test_intersection_Self() { - withInterestingSets("a", maximum: 200) { a in - withInterestingSets("b", maximum: 200) { b in - let expected = a.intersection(b).sorted() - let c = BitSet(a) - let d = BitSet(b) - let actual = c.intersection(d) - expectEqualElements(actual, expected) + func formUnion(_ first: inout BitSet,_ second: S) + where S.Element == Int { + first.formUnion(second) } + + formUnion(&a, 20*step ..< 40*step) + expectEqualElements(a, 0 ..< 40*step) } } - func test_intersection_Sequence() { + func test_intersection() { withInterestingSets("a", maximum: 200) { a in withInterestingSets("b", maximum: 200) { b in let expected = a.intersection(b).sorted() - let c = BitSet(a) - let actual = c.intersection(b) - expectEqualElements(actual, expected) + let x = BitSet(a) + let y = BitSet(b) + let z = Array(b) - expectEqualElements(c.intersection([-100]), []) - expectEqualElements(c.intersection(-100 ..< -10), []) + expectEqualElements(x.intersection(b), expected) + expectEqualElements(x.intersection(y), expected) + expectEqualElements(x.intersection(y.counted), expected) - func intersection(_ first: BitSet, _ second: S) -> BitSet + func intersection(_ first: BitSet,_ second: S) -> BitSet where S.Element == Int { first.intersection(second) } - let d = intersection(c, BitSet(b)) - expectEqualElements(d, expected) - let e = intersection(d, 40 ..< 60) - expectEqualElements(e, expected.filter { (40 ..< 60).contains($0) }) + + expectEqualElements(intersection(x, y), expected) + expectEqualElements(intersection(x, y.counted), expected) + expectEqualElements(x.intersection(z), expected) + expectEqualElements(x.intersection(z + z), expected) } } } @@ -660,55 +688,76 @@ final class BitSetTest: CollectionTestCase { let g = a.intersection(-100*step ..< 10*step) expectEqualElements(g, 0 ..< 10*step) + + func intersection(_ first: BitSet,_ second: S) -> BitSet + where S.Element == Int { + first.intersection(second) + } + + let h = intersection(g, 5*step ..< 15*step) + expectEqualElements(h, 5*step ..< 10*step) } } - func test_formIntersection_Self() { + func test_formIntersection() { withInterestingSets("a", maximum: 200) { a in withInterestingSets("b", maximum: 200) { b in let expected = a.intersection(b).sorted() - var c = BitSet(a) - let d = BitSet(b) - c.formIntersection(d) - expectEqualElements(c, expected) + let c = BitSet(b) + let d = Array(b) + withEvery("shared", in: [false, true]) { shared in + do { + var x = BitSet(a) + withHiddenCopies(if: shared, of: &x) { x in + x.formIntersection(c) + expectEqualElements(x, expected) + } + } + do { + var x = BitSet(a) + withHiddenCopies(if: shared, of: &x) { x in + x.formIntersection(c.counted) + expectEqualElements(x, expected) + } + } + func formIntersection(_ first: inout BitSet, _ second: S) + where S.Element == Int { + first.formIntersection(second) + } + do { + var x = BitSet(a) + withHiddenCopies(if: shared, of: &x) { x in + formIntersection(&x, c) + expectEqualElements(x, expected) + } + } + do { + var x = BitSet(a) + withHiddenCopies(if: shared, of: &x) { x in + formIntersection(&x, c.counted) + expectEqualElements(x, expected) + } + } + + do { + var x = BitSet(a) + withHiddenCopies(if: shared, of: &x) { x in + x.formIntersection(d) + expectEqualElements(x, expected) + } + } + do { + var x = BitSet(a) + withHiddenCopies(if: shared, of: &x) { x in + x.formIntersection(d + d) + expectEqualElements(x, expected) + } + } + } } } } - func test_formIntersection_Sequence() { - func intersection(_ first: inout BitSet, _ second: S) - where S.Element == Int { - first.formIntersection(second) - } - - withInterestingSets("a", maximum: 200) { a in - withInterestingSets("b", maximum: 200) { b in - let expected = a.intersection(b).sorted() - var c = BitSet(a) - c.formIntersection(b) - expectEqualElements(c, expected) - - var d = BitSet(a) - intersection(&d, BitSet(b)) - expectEqualElements(d, expected) - - intersection(&d, 40 ..< 60) - expectEqualElements(d, expected.filter { (40 ..< 60).contains($0) }) - } - } - - var s = BitSet(0 ..< 100) - intersection(&s, [-100, -10, 0, 1, 2]) - expectEqualElements(s, [0, 1, 2]) - - intersection(&s, -100 ..< -10) - expectEqualElements(s, []) - - s = BitSet(0 ..< 100) - intersection(&s, -100 ..< 10) - expectEqualElements(s, 0 ..< 10) - } - func test_formIntersection_Range() { withEvery("step", in: [1, 5, 16, 23, 24, UInt.bitWidth]) { step in var a = BitSet(0 ..< 10*step) @@ -738,43 +787,41 @@ final class BitSetTest: CollectionTestCase { var g = BitSet(0 ..< 100*step) g.formIntersection(-100*step ..< 10*step) expectEqualElements(g, 0 ..< 10 * step) - } - } - func test_symmetricDifference_Self() { - withInterestingSets("a", maximum: 200) { a in - withInterestingSets("b", maximum: 200) { b in - let expected = a.symmetricDifference(b).sorted() - let c = BitSet(a) - let d = BitSet(b) - let actual = c.symmetricDifference(d) - expectEqualElements(actual, expected) + func formIntersection(_ first: inout BitSet,_ second: S) + where S.Element == Int { + first.formIntersection(second) } + + var h = BitSet(0 ..< 100*step) + formIntersection(&h, 20*step ..< 120*step) + expectEqualElements(h, 20*step ..< 100*step) } } - func test_symmetricDifference_Sequence() { + func test_symmetricDifference() { withInterestingSets("a", maximum: 200) { a in withInterestingSets("b", maximum: 200) { b in let expected = a.symmetricDifference(b).sorted() - let c = BitSet(a) - let actual = c.symmetricDifference(b) - expectEqualElements(actual, expected) + let x = BitSet(a) + let y = BitSet(b) + let z = Array(b) + + expectEqualElements(x.symmetricDifference(b), expected) + expectEqualElements(x.symmetricDifference(y), expected) + expectEqualElements(x.symmetricDifference(y.counted), expected) func symmetricDifference( - _ first: BitSet, _ second: S + _ first: BitSet,_ second: S ) -> BitSet where S.Element == Int { first.symmetricDifference(second) } - let d = symmetricDifference(c, BitSet(b)) - expectEqualElements(d, expected) - let e = symmetricDifference(d, 40 ..< 60) - let expected2 = a - .symmetricDifference(b) - .symmetricDifference(40 ..< 60) - .sorted() - expectEqualElements(e, expected2) + + expectEqualElements(symmetricDifference(x, y), expected) + expectEqualElements(symmetricDifference(x, y.counted), expected) + expectEqualElements(x.symmetricDifference(z), expected) + expectEqualElements(x.symmetricDifference(z + z), expected) } } } @@ -797,43 +844,74 @@ final class BitSetTest: CollectionTestCase { let f = e.symmetricDifference(20*step ..< 20*step) expectEqualElements(f, e) - } - } - func test_formSymmetricDifference_Self() { - withInterestingSets("a", maximum: 200) { a in - withInterestingSets("b", maximum: 200) { b in - let expected = a.symmetricDifference(b).sorted() - var c = BitSet(a) - let d = BitSet(b) - c.formSymmetricDifference(d) - expectEqualElements(c, expected) + func symmetricDifference( + _ first: BitSet,_ second: S + ) -> BitSet + where S.Element == Int { + first.symmetricDifference(second) } + let g = symmetricDifference(e, 3*step ..< 7*step) + expectEqualElements(g, 0 ..< 10*step) } } - func test_formSymmetricDifference_Sequence() { + func test_formSymmetricDifference() { withInterestingSets("a", maximum: 200) { a in withInterestingSets("b", maximum: 200) { b in let expected = a.symmetricDifference(b).sorted() - var c = BitSet(a) - c.formSymmetricDifference(b) - expectEqualElements(c, expected) + let c = BitSet(b) + let d = Array(b) - func symmetricDifference( - _ first: inout BitSet, _ second: S - ) where S.Element == Int { - first.formSymmetricDifference(second) + withEvery("shared", in: [false, true]) { shared in + do { + var x = BitSet(a) + withHiddenCopies(if: shared, of: &x) { x in + x.formSymmetricDifference(c) + expectEqualElements(x, expected) + } + } + do { + var x = BitSet(a) + withHiddenCopies(if: shared, of: &x) { x in + x.formSymmetricDifference(c.counted) + expectEqualElements(x, expected) + } + } + func formSymmetricDifference(_ first: inout BitSet, _ second: S) + where S.Element == Int { + first.formSymmetricDifference(second) + } + do { + var x = BitSet(a) + withHiddenCopies(if: shared, of: &x) { x in + formSymmetricDifference(&x, c) + expectEqualElements(x, expected) + } + } + do { + var x = BitSet(a) + withHiddenCopies(if: shared, of: &x) { x in + formSymmetricDifference(&x, c.counted) + expectEqualElements(x, expected) + } + } + + do { + var x = BitSet(a) + withHiddenCopies(if: shared, of: &x) { x in + x.formSymmetricDifference(d) + expectEqualElements(x, expected) + } + } + do { + var x = BitSet(a) + withHiddenCopies(if: shared, of: &x) { x in + x.formSymmetricDifference(d + d) + expectEqualElements(x, expected) + } + } } - var d = BitSet(a) - symmetricDifference(&d, BitSet(b)) - expectEqualElements(d, expected) - symmetricDifference(&d, 40 ..< 60) - let expected2 = a - .symmetricDifference(b) - .symmetricDifference(40 ..< 60) - .sorted() - expectEqualElements(d, expected2) } } } @@ -857,42 +935,38 @@ final class BitSetTest: CollectionTestCase { a.formSymmetricDifference(20*step ..< 20*step) expectEqualElements(a, Array(0 ..< 3*step) + Array(7*step ..< 10*step)) - } - } - func test_subtracting_Self() { - withInterestingSets("a", maximum: 200) { a in - withInterestingSets("b", maximum: 200) { b in - let expected = a.subtracting(b).sorted() - let c = BitSet(a) - let d = BitSet(b) - let actual = c.subtracting(d) - expectEqualElements(actual, expected) + func formSymmetricDifference(_ first: inout BitSet, _ second: S) + where S.Element == Int { + first.formSymmetricDifference(second) } + + formSymmetricDifference(&a, 3*step ..< 7*step) + expectEqualElements(a, 0 ..< 10*step) } } - func test_subtracting_Sequence() { - func subtracting(_ first: BitSet, _ second: S) -> BitSet - where S.Element == Int { - first.subtracting(second) - } - + func test_subtracting() { withInterestingSets("a", maximum: 200) { a in withInterestingSets("b", maximum: 200) { b in let expected = a.subtracting(b).sorted() - let c = BitSet(a) - let actual = c.subtracting(b) - expectEqualElements(actual, expected) + let x = BitSet(a) + let y = BitSet(b) + let z = Array(b) - expectEqual(c.subtracting([-100]), c) - expectEqual(subtracting(c, -100 ..< -10), c) + expectEqualElements(x.subtracting(b), expected) + expectEqualElements(x.subtracting(y), expected) + expectEqualElements(x.subtracting(y.counted), expected) - let d = subtracting(c, BitSet(b)) - expectEqualElements(d, expected) - let e = subtracting(d, 40 ..< 60) - expectEqualElements( - e, expected.filter { !(40 ..< 60).contains($0)}) + func subtracting(_ first: BitSet,_ second: S) -> BitSet + where S.Element == Int { + first.subtracting(second) + } + + expectEqualElements(subtracting(x, y), expected) + expectEqualElements(subtracting(x, y.counted), expected) + expectEqualElements(x.subtracting(z), expected) + expectEqualElements(x.subtracting(z + z), expected) } } } @@ -916,47 +990,72 @@ final class BitSetTest: CollectionTestCase { let f = e.subtracting(-10*step ..< -1*step) expectEqualElements(f, expected) - } - } - func test_subtract_Self() { - withInterestingSets("a", maximum: 200) { a in - withInterestingSets("b", maximum: 200) { b in - let expected = a.subtracting(b).sorted() - var c = BitSet(a) - let d = BitSet(b) - c.subtract(d) - expectEqualElements(c, expected) + func subtracting(_ first: BitSet,_ second: S) -> BitSet + where S.Element == Int { + first.subtracting(second) } + + let g = subtracting(e, 4*step ..< 10*step) + expectEqualElements(g, 1*step ..< 4*step) } } - func test_subtract_Sequence() { - func subtract(_ first: inout BitSet, _ second: S) - where S.Element == Int { - first.subtract(second) - } - + func test_subtract() { withInterestingSets("a", maximum: 200) { a in withInterestingSets("b", maximum: 200) { b in let expected = a.subtracting(b).sorted() - var c = BitSet(a) - c.subtract(b) - expectEqualElements(c, expected) + let c = BitSet(b) + let d = Array(b) + withEvery("shared", in: [false, true]) { shared in + do { + var x = BitSet(a) + withHiddenCopies(if: shared, of: &x) { x in + x.subtract(c) + expectEqualElements(x, expected) + } + } + do { + var x = BitSet(a) + withHiddenCopies(if: shared, of: &x) { x in + x.subtract(c.counted) + expectEqualElements(x, expected) + } + } + func subtract(_ first: inout BitSet, _ second: S) + where S.Element == Int { + first.subtract(second) + } + do { + var x = BitSet(a) + withHiddenCopies(if: shared, of: &x) { x in + subtract(&x, c) + expectEqualElements(x, expected) + } + } + do { + var x = BitSet(a) + withHiddenCopies(if: shared, of: &x) { x in + subtract(&x, c.counted) + expectEqualElements(x, expected) + } + } - subtract(&c, [-100]) - expectEqualElements(c, expected) - - subtract(&c, -100 ..< -10) - expectEqualElements(c, expected) - - var d = BitSet(a) - subtract(&d, BitSet(b)) - expectEqualElements(d, expected) - - subtract(&d, 40 ..< 60) - expectEqualElements( - d, expected.filter { !(40 ..< 60).contains($0)}) + do { + var x = BitSet(a) + withHiddenCopies(if: shared, of: &x) { x in + x.subtract(d) + expectEqualElements(x, expected) + } + } + do { + var x = BitSet(a) + withHiddenCopies(if: shared, of: &x) { x in + x.subtract(d + d) + expectEqualElements(x, expected) + } + } + } } } } @@ -980,6 +1079,13 @@ final class BitSetTest: CollectionTestCase { a.subtract(-10*step ..< -1*step) expectEqualElements(a, expected) + + func subtract(_ first: inout BitSet, _ second: S) + where S.Element == Int { + first.subtract(second) + } + subtract(&a, 3*step ..< 10*step) + expectEqualElements(a, 1*step ..< 3*step) } } From e3cc498060e8891c8754605ecb3ccfad14e1235d Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 21 Oct 2022 19:48:36 -0700 Subject: [PATCH 12/39] [BitSet.Counted] Review, test, fix, and document binary set operations & predicates --- .../BitSet/BitSet.Counted.swift | 832 +++++++++++++++++- .../BitSet.Counted Tests.swift | 249 ++++++ 2 files changed, 1038 insertions(+), 43 deletions(-) create mode 100644 Tests/BitCollectionsTests/BitSet.Counted Tests.swift diff --git a/Sources/BitCollections/BitSet/BitSet.Counted.swift b/Sources/BitCollections/BitSet/BitSet.Counted.swift index 33668076..aa0d2f7e 100644 --- a/Sources/BitCollections/BitSet/BitSet.Counted.swift +++ b/Sources/BitCollections/BitSet/BitSet.Counted.swift @@ -258,10 +258,11 @@ extension BitSet.Counted { // Extras _bits[members: bounds] } - public func sorted() -> BitSet.Counted { self } -} + public mutating func remove(at index: Index) -> Int { + defer { self._count &-= 1 } + return _bits.remove(at: index) + } -extension BitSet.Counted { public func filter( _ isIncluded: (Element) throws -> Bool ) rethrows -> Self { @@ -269,6 +270,41 @@ extension BitSet.Counted { } } +extension BitSet.Counted: _SortedCollection { + /// Returns the current set (already sorted). + /// + /// - Complexity: O(1) + public func sorted() -> BitSet.Counted { 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 + } +} + extension BitSet.Counted { public static func random(upTo limit: Int) -> BitSet.Counted { BitSet.Counted(BitSet.random(upTo: limit)) @@ -310,112 +346,332 @@ extension BitSet.Counted: SetAlgebra { } extension BitSet.Counted { - public func union(_ other: __owned BitSet.Counted) -> BitSet.Counted { - Self(_bits.union(other)) + /// Returns a new set with the elements of both this and the given set. + /// + /// let set: BitSet.Counted = [1, 2, 3, 4] + /// let other: BitSet.Counted = [0, 2, 4, 6] + /// set.union(other) // [0, 1, 2, 3, 4, 6] + /// + /// - Parameter other: The set of elements to insert. + /// + /// - Complexity: O(*max*), where *max* is the largest item in either input. + public func union(_ other: BitSet.Counted) -> BitSet.Counted { + _bits.union(other).counted } - public func union(_ other: __owned BitSet) -> BitSet.Counted { - Self(_bits.union(other)) + /// Returns a new set with the elements of both this and the given set. + /// + /// let set: BitSet.Counted = [1, 2, 3, 4] + /// let other: BitSet = [0, 2, 4, 6] + /// set.union(other) // [0, 1, 2, 3, 4, 6] + /// + /// - Parameter other: The set of elements to insert. + /// + /// - Complexity: O(*max*), where *max* is the largest item in either input. + public func union(_ other: BitSet) -> BitSet.Counted { + _bits.union(other).counted } + /// Returns a new set with the elements of both this set and the given + /// range of integers. + /// + /// let set: BitSet.Counted = [1, 2, 3, 4] + /// set.union(3 ..< 7) // [1, 2, 3, 4, 5, 6] + /// + /// - Parameter other: A range of nonnegative integers. + /// + /// - Complexity: O(*max*), where *max* is the largest item in either input. public func union(_ other: Range) -> BitSet.Counted { - Self(_bits.union(other)) + _bits.union(other).counted } + /// Returns a new set with the elements of both this set and the given + /// sequence of integers. + /// + /// let set: BitSet.Counted = [1, 2, 3, 4] + /// let other = [6, 4, 2, 0, 2, 0] + /// set.union(other) // [0, 1, 2, 3, 4, 6] + /// + /// - Parameter other: A sequence of nonnegative integers. + /// + /// - Complexity: O(*max*) + *k*, where *max* is the largest item in either + /// input, and *k* is the complexity of iterating over all elements in + /// `other`. @inlinable - public __consuming func union( + public func union( _ other: __owned S ) -> Self where S.Element == Int { - Self(_bits.union(other)) + _bits.union(other).counted } } extension BitSet.Counted { + /// Returns a new bit set with the elements that are common to both this set + /// and the given set. + /// + /// let a: BitSet.Counted = [1, 2, 3, 4] + /// let b: BitSet.Counted = [6, 4, 2, 0] + /// let c = a.intersection(b) + /// // c is now [2, 4] + /// + /// - Parameter other: A bit set. + /// + /// - Complexity: O(*max*), where *max* is the largest item in either set. public func intersection(_ other: BitSet.Counted) -> BitSet.Counted { - Self(_bits.intersection(other)) + _bits.intersection(other).counted } - public func intersection(_ other: __owned BitSet) -> BitSet.Counted { - Self(_bits.intersection(other)) + /// Returns a new bit set with the elements that are common to both this set + /// and the given set. + /// + /// let a: BitSet.Counted = [1, 2, 3, 4] + /// let b: BitSet = [6, 4, 2, 0] + /// let c = a.intersection(b) + /// // c is now [2, 4] + /// + /// - Parameter other: A bit set. + /// + /// - Complexity: O(*max*), where *max* is the largest item in either set. + public func intersection(_ other: BitSet) -> BitSet.Counted { + _bits.intersection(other).counted } + /// Returns a new bit set with the elements that are common to both this set + /// and the given range of integers. + /// + /// let a: BitSet.Counted = [1, 2, 3, 4] + /// let c = a.intersection(-10 ..< 3) + /// // c is now [3, 4] + /// + /// - Parameter other: A range of integers. + /// + /// - Complexity: O(*max*) + *k*, where *max* is the largest item in `self`, + /// and *k* is the complexity of iterating over all elements in `other`. public func intersection(_ other: Range) -> BitSet.Counted { - Self(_bits.intersection(other)) + _bits.intersection(other).counted } + /// Returns a new bit set with the elements that are common to both this set + /// and the given sequence. + /// + /// let a: BitSet.Counted = [1, 2, 3, 4] + /// let b = [6, 4, 2, 0] + /// let c = a.intersection(b) + /// // c is now [2, 4] + /// + /// - Parameter other: A sequence of integer values. + /// + /// - Complexity: O(*max*) + *k*, where *max* is the largest item in `self`, + /// and *k* is the complexity of iterating over all elements in `other`. @inlinable - public __consuming func intersection( + public func intersection( _ other: __owned S ) -> Self where S.Element == Int { - Self(_bits.intersection(other)) + _bits.intersection(other).counted } } extension BitSet.Counted { - public func symmetricDifference(_ other: __owned BitSet.Counted) -> BitSet.Counted { - Self(_bits.symmetricDifference(other)) + /// Returns a new bit set with the elements that are either in this set or in + /// `other`, but not in both. + /// + /// let set: BitSet.Counted = [1, 2, 3, 4] + /// let other: BitSet.Counted = [6, 4, 2, 0] + /// set.symmetricDifference(other) // [0, 1, 3, 6] + /// + /// - Parameter other: Another set. + /// + /// - Returns: A new set. + /// + /// - Complexity: O(*max*), where *max* is the largest item in either set. + public func symmetricDifference(_ other: BitSet.Counted) -> BitSet.Counted { + _bits.symmetricDifference(other).counted } - public func symmetricDifference(_ other: __owned BitSet) -> BitSet.Counted { - Self(_bits.symmetricDifference(other)) + /// Returns a new bit set with the elements that are either in this set or in + /// `other`, but not in both. + /// + /// let set: BitSet.Counted = [1, 2, 3, 4] + /// let other: BitSet = [6, 4, 2, 0] + /// set.symmetricDifference(other) // [0, 1, 3, 6] + /// + /// - Parameter other: Another set. + /// + /// - Returns: A new set. + /// + /// - Complexity: O(*max*), where *max* is the largest item in either set. + public func symmetricDifference(_ other: BitSet) -> BitSet.Counted { + _bits.symmetricDifference(other).counted } + /// Returns a new bit set with the elements that are either in this set or in + /// `other`, but not in both. + /// + /// let set: BitSet.Counted = [1, 2, 3, 4] + /// set.formSymmetricDifference(3 ..< 7) // [1, 2, 5, 6] + /// + /// - Parameter other: A range of nonnegative integers. + /// + /// - Returns: A new set. + /// + /// - Complexity: O(*max*), where *max* is the largest item in either input. public func symmetricDifference(_ other: Range) -> BitSet.Counted { - Self(_bits.symmetricDifference(other)) + _bits.symmetricDifference(other).counted } + /// Returns a new bit set with the elements that are either in this set or in + /// `other`, but not in both. + /// + /// let set: BitSet.Counted = [1, 2, 3, 4] + /// let other = [6, 4, 2, 0, 2, 0] + /// set.formSymmetricDifference(other) // [0, 1, 3, 6] + /// + /// - Parameter other: A sequence of nonnegative integers. + /// + /// - Complexity: O(*max*) + *k*, where *max* is the largest item in either + /// input, and *k* is the complexity of iterating over all elements in + /// `other`. @inlinable - public __consuming func symmetricDifference( + public func symmetricDifference( _ other: __owned S ) -> Self where S.Element == Int { - Self(_bits.symmetricDifference(other)) + _bits.symmetricDifference(other).counted } } extension BitSet.Counted { - public func subtracting(_ other: __owned BitSet.Counted) -> BitSet.Counted { - Self(_bits.subtracting(other)) + /// Returns a new set containing the elements of this set that do not occur + /// in the given other set. + /// + /// let set: BitSet.Counted = [1, 2, 3, 4] + /// let other: BitSet.Counted = [0, 2, 4, 6] + /// set.subtracting(other) // [1, 3] + /// + /// - Parameter other: Another bit set. + /// + /// - Returns: A new set. + /// + /// - Complexity: O(*max*), where *max* is the largest item in either input. + public func subtracting(_ other: BitSet.Counted) -> BitSet.Counted { + _bits.subtracting(other).counted } - public func subtracting(_ other: __owned BitSet) -> BitSet.Counted { - Self(_bits.subtracting(other)) + /// Returns a new set containing the elements of this set that do not occur + /// in the given other set. + /// + /// let set: BitSet.Counted = [1, 2, 3, 4] + /// let other: BitSet = [0, 2, 4, 6] + /// set.subtracting(other) // [1, 3] + /// + /// - Parameter other: Another bit set. + /// + /// - Returns: A new set. + /// + /// - Complexity: O(*max*), where *max* is the largest item in either input. + public func subtracting(_ other: BitSet) -> BitSet.Counted { + _bits.subtracting(other).counted } + /// Returns a new set containing the elements of this set that do not occur + /// in the given range of integers. + /// + /// let set: BitSet.Counted = [1, 2, 3, 4] + /// set.subtracting(-10 ..< 3) // [3, 4] + /// + /// - Parameter other: A range of arbitrary integers. + /// + /// - Returns: A new set. + /// + /// - Complexity: O(*max*), where *max* is the largest item in self. public func subtracting(_ other: Range) -> BitSet.Counted { - Self(_bits.subtracting(other)) + _bits.subtracting(other).counted } + /// Returns a new set containing the elements of this set that do not occur + /// in the given sequence of integers. + /// + /// let set: BitSet.Counted = [1, 2, 3, 4] + /// let other = [6, 4, 2, 0, -2, -4] + /// set.subtracting(other) // [1, 3] + /// + /// - Parameter other: A sequence of arbitrary integers. + /// + /// - Returns: A new set. + /// + /// - Complexity: O(*max*) + *k*, where *max* is the largest item in `self`, + /// and *k* is the complexity of iterating over all elements in `other`. @inlinable - public __consuming func subtracting( + public func subtracting( _ other: __owned S ) -> Self where S.Element == Int { - Self(_bits.subtracting(other)) + _bits.subtracting(other).counted } } extension BitSet.Counted { - public mutating func formUnion(_ other: __owned BitSet.Counted) { + /// Adds the elements of the given set to this set. + /// + /// var set: BitSet.Counted = [1, 2, 3, 4] + /// let other: BitSet.Counted = [0, 2, 4, 6] + /// set.formUnion(other) + /// // `set` is now `[0, 1, 2, 3, 4, 6]` + /// + /// - Parameter other: The set of elements to insert. + /// + /// - Complexity: O(*max*), where *max* is the largest item in either input. + public mutating func formUnion(_ other: BitSet.Counted) { _bits.formUnion(other._bits) _count = _bits.count _checkInvariants() } - public mutating func formUnion(_ other: __owned BitSet) { + /// Adds the elements of the given set to this set. + /// + /// var set: BitSet.Counted = [1, 2, 3, 4] + /// let other: BitSet = [0, 2, 4, 6] + /// set.formUnion(other) + /// // `set` is now `[0, 1, 2, 3, 4, 6]` + /// + /// - Parameter other: The set of elements to insert. + /// + /// - Complexity: O(*max*), where *max* is the largest item in either input. + public mutating func formUnion(_ other: BitSet) { _bits.formUnion(other) _count = _bits.count _checkInvariants() } + /// Adds the elements of the given range of integers to this set. + /// + /// var set: BitSet.Counted = [1, 2, 3, 4] + /// set.formUnion(3 ..< 7) + /// // `set` is now `[1, 2, 3, 4, 5, 6]` + /// + /// - Parameter other: A range of nonnegative integers. + /// + /// - Complexity: O(*max*), where *max* is the largest item in either input. public mutating func formUnion(_ other: Range) { _bits.formUnion(other) _count = _bits.count _checkInvariants() } + /// Adds the elements of the given sequence to this set. + /// + /// var set: BitSet.Counted = [1, 2, 3, 4] + /// let other = [6, 4, 2, 0, 2, 0] + /// set.formUnion(other) + /// // `set` is now `[0, 1, 2, 3, 4, 6]` + /// + /// - Parameter other: A sequence of nonnegative integers. + /// + /// - Complexity: O(*max*) + *k*, where *max* is the largest item in either + /// input, and *k* is the complexity of iterating over all elements in + /// `other`. @inlinable public mutating func formUnion( _ other: __owned S @@ -427,24 +683,64 @@ extension BitSet.Counted { } extension BitSet.Counted { + /// Removes the elements of this set that aren't also in the given one. + /// + /// var set: BitSet.Counted = [1, 2, 3, 4] + /// let other: BitSet.Counted = [0, 2, 4, 6] + /// set.formIntersection(other) + /// // set is now [2, 4] + /// + /// - Parameter other: A bit set. + /// + /// - Complexity: O(*max*), where *max* is the largest item in either set. public mutating func formIntersection(_ other: BitSet.Counted) { _bits.formIntersection(other._bits) _count = _bits.count _checkInvariants() } - public mutating func formIntersection(_ other: __owned BitSet) { + /// Removes the elements of this set that aren't also in the given one. + /// + /// var set: BitSet.Counted = [1, 2, 3, 4] + /// let other: BitSet = [0, 2, 4, 6] + /// set.formIntersection(other) + /// // set is now [2, 4] + /// + /// - Parameter other: A bit set. + /// + /// - Complexity: O(*max*), where *max* is the largest item in either set. + public mutating func formIntersection(_ other: BitSet) { _bits.formIntersection(other) _count = _bits.count _checkInvariants() } + /// Removes the elements of this set that aren't also in the given range. + /// + /// var set: BitSet.Counted = [1, 2, 3, 4] + /// set.formIntersection(-10 ..< 3) + /// // set is now [3, 4] + /// + /// - Parameter other: A range of integers. + /// + /// - Complexity: O(*max*), where *max* is the largest item in `self`. public mutating func formIntersection(_ other: Range) { _bits.formIntersection(other) _count = _bits.count _checkInvariants() } + /// Removes the elements of this set that aren't also in the given sequence. + /// + /// var set: BitSet.Counted = [1, 2, 3, 4] + /// let other: Set = [6, 4, 2, 0] + /// set.formIntersection(other) + /// // set is now [2, 4] + /// + /// - Parameter other: A sequence of integers. + /// + /// - Complexity: O(*max*) + *k*, where *max* is the largest item in `self`, + /// and *k* is the complexity of iterating over all elements in `other`. @inlinable public mutating func formIntersection( _ other: __owned S @@ -456,24 +752,69 @@ extension BitSet.Counted { } extension BitSet.Counted { - public mutating func formSymmetricDifference(_ other: __owned BitSet.Counted) { + /// Replace this set with the elements contained in this set or the given + /// set, but not both. + /// + /// var set: BitSet.Counted = [1, 2, 3, 4] + /// let other: BitSet.Counted = [0, 2, 4, 6] + /// set.formSymmetricDifference(other) + /// // set is now [0, 1, 3, 6] + /// + /// - Parameter other: Another set. + /// + /// - Complexity: O(*max*), where *max* is the largest item in either set. + public mutating func formSymmetricDifference(_ other: BitSet.Counted) { _bits.formSymmetricDifference(other._bits) _count = _bits.count _checkInvariants() } - public mutating func formSymmetricDifference(_ other: __owned BitSet) { + /// Replace this set with the elements contained in this set or the given + /// set, but not both. + /// + /// var set: BitSet.Counted = [1, 2, 3, 4] + /// let other: BitSet = [0, 2, 4, 6] + /// set.formSymmetricDifference(other) + /// // set is now [0, 1, 3, 6] + /// + /// - Parameter other: Another set. + /// + /// - Complexity: O(*max*), where *max* is the largest item in either set. + public mutating func formSymmetricDifference(_ other: BitSet) { _bits.formSymmetricDifference(other) _count = _bits.count _checkInvariants() } + /// Replace this set with the elements contained in this set or the given + /// range of integers, but not both. + /// + /// var set: BitSet.Counted = [1, 2, 3, 4] + /// set.formSymmetricDifference(3 ..< 7) + /// // set is now [1, 2, 5, 6] + /// + /// - Parameter other: A range of nonnegative integers. + /// + /// - Complexity: O(*max*), where *max* is the largest item in either input. public mutating func formSymmetricDifference(_ other: Range) { _bits.formSymmetricDifference(other) _count = _bits.count _checkInvariants() } + /// Replace this set with the elements contained in this set or the given + /// sequence, but not both. + /// + /// var set: BitSet.Counted = [1, 2, 3, 4] + /// let other = [6, 4, 2, 0, 2, 0] + /// set.formSymmetricDifference(other) + /// // set is now [0, 1, 3, 6] + /// + /// - Parameter other: A sequence of nonnegative integers. + /// + /// - Complexity: O(*max*) + *k*, where *max* is the largest item in either + /// input, and *k* is the complexity of iterating over all elements in + /// `other`. @inlinable public mutating func formSymmetricDifference( _ other: __owned S @@ -485,24 +826,66 @@ extension BitSet.Counted { } extension BitSet.Counted { - public mutating func subtract(_ other: __owned BitSet.Counted) { + /// Removes the elements of the given bit set from this set. + /// + /// var set: BitSet.Counted = [1, 2, 3, 4] + /// let other: BitSet.Counted = [0, 2, 4, 6] + /// set.subtract(other) + /// // set is now [1, 3] + /// + /// - Parameter other: Another bit set. + /// + /// - Complexity: O(*max*), where *max* is the largest item in either input. + public mutating func subtract(_ other: BitSet.Counted) { _bits.subtract(other._bits) _count = _bits.count _checkInvariants() } - public mutating func subtract(_ other: __owned BitSet) { + /// Removes the elements of the given bit set from this set. + /// + /// var set: BitSet.Counted = [1, 2, 3, 4] + /// let other: BitSet = [0, 2, 4, 6] + /// set.subtract(other) + /// // set is now [1, 3] + /// + /// - Parameter other: Another bit set. + /// + /// - Complexity: O(*max*), where *max* is the largest item in either input. + public mutating func subtract(_ other: BitSet) { _bits.subtract(other) _count = _bits.count _checkInvariants() } + /// Removes the elements of the given range of integers from this set. + /// + /// var set: BitSet.Counted = [1, 2, 3, 4] + /// set.subtract(-10 ..< 3) + /// // set is now [3, 4] + /// + /// - Parameter other: A range of arbitrary integers. + /// + /// - Returns: A new set. + /// + /// - Complexity: O(*max*), where *max* is the largest item in self. public mutating func subtract(_ other: Range) { _bits.subtract(other) _count = _bits.count _checkInvariants() } + /// Removes the elements of the given sequence of integers from this set. + /// + /// var set: BitSet.Counted = [1, 2, 3, 4] + /// let other = [6, 4, 2, 0, -2, -4] + /// set.subtract(other) + /// // set is now [1, 3] + /// + /// - Parameter other: A sequence of arbitrary integers. + /// + /// - Complexity: O(*max*) + *k*, where *max* is the largest item in `self`, + /// and *k* is the complexity of iterating over all elements in `other`. @inlinable public mutating func subtract( _ other: __owned S @@ -514,65 +897,311 @@ extension BitSet.Counted { } extension BitSet.Counted { + /// 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 { + guard self.count == other.count else { return false } + return self._bits.isEqual(to: other._bits) + } + + /// 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 value of the largest member of + /// either set. + public func isEqual(to other: BitSet) -> Bool { + self._bits.isEqual(to: other) + } + + /// 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 self.count == other.count else { return false } + return _bits.isEqual(to: other) + } + + /// 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`. + @inlinable + public func isEqual(to other: S) -> Bool + where S.Element == Int + { + guard self.count >= other.underestimatedCount else { return false } + return _bits.isEqual(to: other) + } +} + +extension BitSet.Counted { + /// 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*. + /// + /// let a: BitSet.Counted = [1, 2, 3, 4] + /// let b: BitSet.Counted = [1, 2, 4] + /// let c: BitSet.Counted = [0, 1] + /// a.isSubset(of: a) // true + /// b.isSubset(of: a) // true + /// c.isSubset(of: a) // false + /// + /// - Parameter other: Another bit set. + /// + /// - 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: Self) -> Bool { if self.count > other.count { return false } return self._bits.isSubset(of: other._bits) } + /// 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*. + /// + /// - Parameter other: Another bit set. + /// + /// - 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: BitSet) -> Bool { self._bits.isSubset(of: other) } + /// 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.Counted = [0, 1, 2] + /// let c: BitSet.Counted = [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 { - guard !isEmpty else { return true } - return _bits.isSubset(of: other) + _bits.isSubset(of: other) } + /// Returns a Boolean value that indicates whether this set is a subset of + /// the values in a given sequence of integers. + /// + /// Set *A* is a subset of another set *B* if every member of *A* is also a + /// member of *B*. + /// + /// let a = [1, 2, 3, 4, -10] + /// let b: BitSet.Counted = [1, 2, 4] + /// let c: BitSet.Counted = [0, 1] + /// b.isSubset(of: a) // true + /// c.isSubset(of: a) // false + /// + /// - Parameter other: A sequence of arbitrary integers. + /// + /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. + /// + /// - Complexity: O(*max*) + *k*, where *max* is the largest item in `self`, + /// and *k* is the complexity of iterating over all elements in `other`. @inlinable public func isSubset(of other: S) -> Bool where S.Element == Int { - guard !isEmpty else { return true } - return _bits.isSubset(of: other) + _bits.isSubset(of: other) } } extension BitSet.Counted { + /// 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*. + /// + /// let a: BitSet.Counted = [1, 2, 3, 4] + /// let b: BitSet.Counted = [1, 2, 4] + /// let c: BitSet.Counted = [0, 1] + /// a.isSuperset(of: a) // true + /// a.isSuperset(of: b) // true + /// a.isSuperset(of: c) // false + /// + /// - Parameter other: Another 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 isSuperset(of other: Self) -> Bool { other.isSubset(of: self) } + /// 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*. + /// + /// - Parameter other: Another 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 isSuperset(of other: BitSet) -> Bool { other.isSubset(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 isSuperset(of other: Range) -> Bool { - return _bits.isSuperset(of: other) + _bits.isSuperset(of: other) } + /// 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 { - return _bits.isSubset(of: other) + _bits.isSuperset(of: other) } } extension BitSet.Counted { + /// 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*. + /// + /// let a: BitSet.Counted = [1, 2, 3, 4] + /// let b: BitSet.Counted = [1, 2, 4] + /// let c: BitSet.Counted = [0, 1] + /// a.isStrictSubset(of: a) // false + /// b.isStrictSubset(of: a) // true + /// c.isStrictSubset(of: a) // false + /// + /// - Parameter other: Another 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: Self) -> Bool { guard self.count < other.count else { return false } return _bits.isStrictSubset(of: other._bits) } + /// 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: Another 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) -> Bool { _bits.isStrictSubset(of: other) } + /// 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.Counted = [0, 1, 2] + /// let c: BitSet.Counted = [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 { guard self.count < other.count else { return false } return _bits.isStrictSubset(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. + /// + /// 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 a = [1, 2, 3, 4, -10] + /// let b: BitSet.Counted = [1, 2, 4] + /// let c: BitSet.Counted = [0, 1] + /// b.isStrictSubset(of: a) // true + /// c.isStrictSubset(of: a) // false + /// + /// - Parameter other: A sequence of arbitrary integers. + /// + /// - Returns: `true` if the set is a strict subset of `other`; + /// otherwise, `false`. + /// + /// - Complexity: O(*max*) + *k*, where *max* is the largest item in `self`, + /// and *k* is the complexity of iterating over all elements in `other`. @inlinable public func isStrictSubset(of other: S) -> Bool where S.Element == Int @@ -582,18 +1211,83 @@ extension BitSet.Counted { } extension BitSet.Counted { + /// 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*. + /// + /// let a: BitSet.Counted = [1, 2, 3, 4] + /// let b: BitSet.Counted = [1, 2, 4] + /// let c: BitSet.Counted = [0, 1] + /// a.isStrictSuperset(of: a) // false + /// a.isStrictSuperset(of: b) // true + /// a.isStrictSuperset(of: c) // false + /// + /// - Parameter other: Another 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: Self) -> Bool { 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: Another 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) -> Bool { other.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.Counted = [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 { _bits.isStrictSuperset(of: other) } + /// 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.Counted = [0, 1, 2, 3, 4] + /// let c: BitSet.Counted = [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: O(*max*) + *k*, where *max* is the largest item in `other`, + /// and *k* is the complexity of iterating over all elements in `other`. @inlinable public func isStrictSuperset(of other: S) -> Bool where S.Element == Int @@ -603,18 +1297,70 @@ extension BitSet.Counted { } extension BitSet.Counted { + /// Returns a Boolean value that indicates whether the set has no members in + /// common with the given set. + /// + /// let a: BitSet.Counted = [1, 2, 3, 4] + /// let b: BitSet.Counted = [5, 6] + /// a.isDisjoint(with: b) // true + /// + /// - Parameter other: Another 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: Self) -> Bool { _bits.isDisjoint(with: other._bits) } + /// Returns a Boolean value that indicates whether the set has no members in + /// common with the given set. + /// + /// let a: BitSet.Counted = [1, 2, 3, 4] + /// let b: BitSet = [5, 6] + /// a.isDisjoint(with: b) // true + /// + /// - Parameter other: Another 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) -> Bool { _bits.isDisjoint(with: other) } + /// 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 { _bits.isDisjoint(with: other) } + /// Returns a Boolean value that indicates whether the set has no members in + /// common with the given sequence of integers. + /// + /// let a: BitSet = [1, 2, 3, 4] + /// let b: BitSet = [5, 6, -10, 42] + /// a.isDisjoint(with: b) // true + /// + /// - Parameter other: A sequence of arbitrary integers. + /// + /// - Returns: `true` if `self` has no elements in common with `other`; + /// otherwise, `false`. + /// + /// - Complexity: O(*max*) + *k*, where *max* is the largest item in `self`, + /// and *k* is the complexity of iterating over all elements in `other`. @inlinable public func isDisjoint(with other: S) -> Bool where S.Element == Int diff --git a/Tests/BitCollectionsTests/BitSet.Counted Tests.swift b/Tests/BitCollectionsTests/BitSet.Counted Tests.swift new file mode 100644 index 00000000..a68e511e --- /dev/null +++ b/Tests/BitCollectionsTests/BitSet.Counted Tests.swift @@ -0,0 +1,249 @@ +//===----------------------------------------------------------------------===// +// +// 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 +import BitCollections +import OrderedCollections + +extension BitSet.Counted: SetAPIExtras { + public mutating func update(_ member: Int, at index: Index) -> Int { + fatalError("Not this one though") + } +} + +extension BitSet.Counted: SortedCollectionAPIChecker {} + +final class BitSetCountedTests: CollectionTestCase { + func test_union() { + let a: BitSet.Counted = [1, 2, 3, 4] + + let b = 3 ..< 7 + let exp = 1 ..< 7 + expectEqualElements(a.union(BitSet.Counted(b)), exp) + expectEqualElements(a.union(BitSet(b)), exp) + expectEqualElements(a.union(b), exp) + expectEqualElements(a.union(Set(b)), exp) + } + + func test_intersection() { + let a: BitSet.Counted = [1, 2, 3, 4] + + let b = 3 ..< 7 + let exp = 3 ..< 5 + expectEqualElements(a.intersection(BitSet.Counted(b)), exp) + expectEqualElements(a.intersection(BitSet(b)), exp) + expectEqualElements(a.intersection(b), exp) + expectEqualElements(a.intersection(Set(b)), exp) + } + + func test_symmetricDifference() { + let a: BitSet.Counted = [1, 2, 3, 4] + + let b = 3 ..< 7 + let exp = [1, 2, 5, 6] + expectEqualElements(a.symmetricDifference(BitSet.Counted(b)), exp) + expectEqualElements(a.symmetricDifference(BitSet(b)), exp) + expectEqualElements(a.symmetricDifference(b), exp) + expectEqualElements(a.symmetricDifference(Set(b)), exp) + } + + func test_subtracting() { + let a: BitSet.Counted = [1, 2, 3, 4] + + let b = 3 ..< 7 + let exp = [1, 2] + expectEqualElements(a.subtracting(BitSet.Counted(b)), exp) + expectEqualElements(a.subtracting(BitSet(b)), exp) + expectEqualElements(a.subtracting(b), exp) + expectEqualElements(a.subtracting(Set(b)), exp) + } + + func test_formUnion() { + func check( + _ expected: S, + _ body: (inout BitSet.Counted) -> Void, + file: StaticString = #file, + line: UInt = #line + ) where S.Element == Int { + var a: BitSet.Counted = [1, 2, 3, 4] + + body(&a) + expectEqualElements(a, expected, file: file, line: line) + } + + let b = 3 ..< 7 + let exp = 1 ..< 7 + check(exp) { $0.formUnion(BitSet.Counted(b)) } + check(exp) { $0.formUnion(BitSet(b)) } + check(exp) { $0.formUnion(b) } + check(exp) { $0.formUnion(Set(b)) } + } + + func test_formIntersection() { + func check( + _ expected: S, + _ body: (inout BitSet.Counted) -> Void, + file: StaticString = #file, + line: UInt = #line + ) where S.Element == Int { + var a: BitSet.Counted = [1, 2, 3, 4] + + body(&a) + expectEqualElements(a, expected, file: file, line: line) + } + + let b = 3 ..< 7 + let exp = 3 ..< 5 + check(exp) { $0.formIntersection(BitSet.Counted(b)) } + check(exp) { $0.formIntersection(BitSet(b)) } + check(exp) { $0.formIntersection(b) } + check(exp) { $0.formIntersection(Set(b)) } + } + + func test_formSymmetricDifference() { + func check( + _ expected: S, + _ body: (inout BitSet.Counted) -> Void, + file: StaticString = #file, + line: UInt = #line + ) where S.Element == Int { + var a: BitSet.Counted = [1, 2, 3, 4] + + body(&a) + expectEqualElements(a, expected, file: file, line: line) + } + + let b = 3 ..< 7 + let exp = [1, 2, 5, 6] + check(exp) { $0.formSymmetricDifference(BitSet.Counted(b)) } + check(exp) { $0.formSymmetricDifference(BitSet(b)) } + check(exp) { $0.formSymmetricDifference(b) } + check(exp) { $0.formSymmetricDifference(Set(b)) } + } + + func test_subtract() { + func check( + _ expected: S, + _ body: (inout BitSet.Counted) -> Void, + file: StaticString = #file, + line: UInt = #line + ) where S.Element == Int { + var a: BitSet.Counted = [1, 2, 3, 4] + + body(&a) + expectEqualElements(a, expected, file: file, line: line) + } + + let b = 3 ..< 7 + let exp = [1, 2] + check(exp) { $0.subtract(BitSet.Counted(b)) } + check(exp) { $0.subtract(BitSet(b)) } + check(exp) { $0.subtract(b) } + check(exp) { $0.subtract(Set(b)) } + } + + func test_isEqual() { + let a: BitSet.Counted = [1, 2, 3, 4] + + let b = 1 ..< 5 + expectTrue(a.isEqual(to: BitSet.Counted(b))) + expectTrue(a.isEqual(to: BitSet(b))) + expectTrue(a.isEqual(to: b)) + expectTrue(a.isEqual(to: Set(b))) + + let c = 2 ..< 7 + expectFalse(a.isEqual(to: BitSet.Counted(c))) + expectFalse(a.isEqual(to: BitSet(c))) + expectFalse(a.isEqual(to: c)) + expectFalse(a.isEqual(to: Set(c))) + } + + func test_isSubset() { + let a: BitSet.Counted = [1, 2, 3, 4] + + let b = 1 ..< 6 + expectTrue(a.isSubset(of: BitSet.Counted(b))) + expectTrue(a.isSubset(of: BitSet(b))) + expectTrue(a.isSubset(of: b)) + expectTrue(a.isSubset(of: Set(b))) + + let c = 2 ..< 4 + expectFalse(a.isSubset(of: BitSet.Counted(c))) + expectFalse(a.isSubset(of: BitSet(c))) + expectFalse(a.isSubset(of: c)) + expectFalse(a.isSubset(of: Set(c))) + } + + func test_isSuperset() { + let a: BitSet.Counted = [1, 2, 3, 4] + + let b = 2 ..< 5 + expectTrue(a.isSuperset(of: BitSet.Counted(b))) + expectTrue(a.isSuperset(of: BitSet(b))) + expectTrue(a.isSuperset(of: b)) + expectTrue(a.isSuperset(of: Set(b))) + + let c = 2 ..< 8 + expectFalse(a.isSuperset(of: BitSet.Counted(c))) + expectFalse(a.isSuperset(of: BitSet(c))) + expectFalse(a.isSuperset(of: c)) + expectFalse(a.isSuperset(of: Set(c))) + } + + func test_isStrictSubset() { + let a: BitSet.Counted = [1, 2, 3, 4] + + let b = 1 ..< 6 + expectTrue(a.isStrictSubset(of: BitSet.Counted(b))) + expectTrue(a.isStrictSubset(of: BitSet(b))) + expectTrue(a.isStrictSubset(of: b)) + expectTrue(a.isStrictSubset(of: Set(b))) + + let c = 1 ..< 5 + expectFalse(a.isStrictSubset(of: BitSet.Counted(c))) + expectFalse(a.isStrictSubset(of: BitSet(c))) + expectFalse(a.isStrictSubset(of: c)) + expectFalse(a.isStrictSubset(of: Set(c))) + } + + func test_isStrictSuperset() { + let a: BitSet.Counted = [1, 2, 3, 4] + + let b = 2 ..< 5 + expectTrue(a.isStrictSuperset(of: BitSet.Counted(b))) + expectTrue(a.isStrictSuperset(of: BitSet(b))) + expectTrue(a.isStrictSuperset(of: b)) + expectTrue(a.isStrictSuperset(of: Set(b))) + + let c = 1 ..< 5 + expectFalse(a.isStrictSuperset(of: BitSet.Counted(c))) + expectFalse(a.isStrictSuperset(of: BitSet(c))) + expectFalse(a.isStrictSuperset(of: c)) + expectFalse(a.isStrictSuperset(of: Set(c))) + } + + func test_isDisjoint() { + let a: BitSet.Counted = [1, 2, 3, 4] + + let b = 5 ..< 10 + expectTrue(a.isDisjoint(with: BitSet.Counted(b))) + expectTrue(a.isDisjoint(with: BitSet(b))) + expectTrue(a.isDisjoint(with: b)) + expectTrue(a.isDisjoint(with: Set(b))) + + let c = 4 ..< 10 + expectFalse(a.isDisjoint(with: BitSet.Counted(c))) + expectFalse(a.isDisjoint(with: BitSet(c))) + expectFalse(a.isDisjoint(with: c)) + expectFalse(a.isDisjoint(with: Set(c))) + } +} From 4fcb37f6ac04a18cf73f0240ebf5c6f050664c83 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 21 Oct 2022 19:48:56 -0700 Subject: [PATCH 13/39] [_CollectionsUtilities] Adjust DictionaryAPIChecker --- .../Utilities/DictionaryAPIChecker.swift | 8 ++++++-- .../_CollectionsTestSupport/Utilities/SetAPIChecker.swift | 1 - 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/Sources/_CollectionsTestSupport/Utilities/DictionaryAPIChecker.swift b/Sources/_CollectionsTestSupport/Utilities/DictionaryAPIChecker.swift index 6882b712..936e219e 100644 --- a/Sources/_CollectionsTestSupport/Utilities/DictionaryAPIChecker.swift +++ b/Sources/_CollectionsTestSupport/Utilities/DictionaryAPIChecker.swift @@ -21,13 +21,17 @@ public protocol DictionaryAPIChecker { typealias Element = (key: Key, value: Value) - associatedtype Keys: Collection where Keys.Element == Key + associatedtype Keys: Collection + where Keys.Element == Key, Keys.Index == Index + var keys: Keys { get } // `Values` ought to be a `MutableCollection` when possible, with `values` // providing a setter. Unfortunately, tree-based dictionaries need to // invalidate indices when mutating keys. - associatedtype Values: Collection where Values.Element == Value + associatedtype Values: Collection + where Values.Element == Value, Values.Index == Index + var values: Values { get } var isEmpty: Bool { get } diff --git a/Sources/_CollectionsTestSupport/Utilities/SetAPIChecker.swift b/Sources/_CollectionsTestSupport/Utilities/SetAPIChecker.swift index fede96d9..ef65f56f 100644 --- a/Sources/_CollectionsTestSupport/Utilities/SetAPIChecker.swift +++ b/Sources/_CollectionsTestSupport/Utilities/SetAPIChecker.swift @@ -70,7 +70,6 @@ public protocol SetAPIChecker { extension Set: SetAPIChecker {} - public protocol SetAPIExtras: SetAPIChecker { // Non-standard extensions From 72e2df59e3ea600f4d5e67a324bd6df1a7acbd41 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 21 Oct 2022 18:23:53 -0700 Subject: [PATCH 14/39] Update gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index f0e519a2..397ae000 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,4 @@ xcuserdata/ .*.sw? /Benchmarks/.swiftpm /Benchmarks/.build +.docc-build From 3d807118ba1c1b7529fb75d2ea327e539aa21720 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 27 Oct 2022 17:50:49 -0700 Subject: [PATCH 15/39] [PersistentCollections] Start working on DocC support --- .../Extensions/PersistentSet.md | 70 +++++++++++++++++++ .../PersistentCollectons.md | 20 ++++++ 2 files changed, 90 insertions(+) create mode 100644 Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentSet.md create mode 100644 Sources/PersistentCollections/PersistentCollections.docc/PersistentCollectons.md diff --git a/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentSet.md b/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentSet.md new file mode 100644 index 00000000..7853d576 --- /dev/null +++ b/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentSet.md @@ -0,0 +1,70 @@ +# ``Collections/PersistentSet`` + +Summary + +## Overview + +Text + +## Topics + +### Binary Set Operations + +- ``intersection(_:)-9dx2a`` +- ``intersection(_:)-5z4my`` +- ``intersection(_:)-1d4e0`` + +- ``union(_:)-1nk1t`` +- ``union(_:)-8otnp`` +- ``union(_:)-6eysm`` + +- ``subtracting(_:)-8sczx`` +- ``subtracting(_:)-2iv0a`` +- ``subtracting(_:)-63bfb`` + +- ``symmetricDifference(_:)-76bw`` +- ``symmetricDifference(_:)-92ha9`` +- ``symmetricDifference(_:)-1n89g`` + +- ``formIntersection(_:)-4s0od`` +- ``formIntersection(_:)-7dqfx`` +- ``formIntersection(_:)-8i59p`` + +- ``formUnion(_:)-68pog`` +- ``formUnion(_:)-82rrc`` +- ``formUnion(_:)-4r7qz`` + +- ``subtract(_:)-7rmd3`` +- ``subtract(_:)-47r93`` +- ``subtract(_:)-3v8ms`` + +- ``formSymmetricDifference(_:)-499uq`` +- ``formSymmetricDifference(_:)-8wue8`` +- ``formSymmetricDifference(_:)-4t8jr`` + +### Binary Set Predicates + +- ``==(_:_:)`` +- ``isEqual(to:)-3m3in`` +- ``isEqual(to:)-7mkn1`` +- ``isEqual(to:)-5px5r`` + +- ``isSubset(of:)-9mp7l`` +- ``isSubset(of:)-2jlh`` +- ``isSubset(of:)-8vn0j`` + +- ``isSuperset(of:)-5af8o`` +- ``isSuperset(of:)-6mvxj`` +- ``isSuperset(of:)-864jy`` + +- ``isStrictSubset(of:)-48nx2`` +- ``isStrictSubset(of:)-2j680`` +- ``isStrictSubset(of:)-1s6n9`` + +- ``isStrictSuperset(of:)-nd5j`` +- ``isStrictSuperset(of:)-5z263`` +- ``isStrictSuperset(of:)-ivbh`` + +- ``isDisjoint(with:)-12irx`` +- ``isDisjoint(with:)-1hhyf`` +- ``isDisjoint(with:)-61lde`` diff --git a/Sources/PersistentCollections/PersistentCollections.docc/PersistentCollectons.md b/Sources/PersistentCollections/PersistentCollections.docc/PersistentCollectons.md new file mode 100644 index 00000000..36f3a571 --- /dev/null +++ b/Sources/PersistentCollections/PersistentCollections.docc/PersistentCollectons.md @@ -0,0 +1,20 @@ +# ``PersistentCollections`` + +**Swift Collections** is an open-source package of data structure implementations for the Swift programming language. + +## Overview + + + +#### Additional Resources + +- [`Swift Collections` on GitHub](https://github.com/apple/swift-collections/) +- [`Swift Collections` on the Swift Forums](https://forums.swift.org/c/related-projects/collections/72) + + +## Topics + +### Persistent Collections + +- ``PersistentSet`` +- ``PersistentDictionary`` From 82b7a5396086809b68347be98b58498c083ef3ca Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 24 Oct 2022 17:38:55 -0700 Subject: [PATCH 16/39] [PersistentCollections] Categorize member APIs --- .../Extensions/PersistentSet.md | 41 +++++++++++++++---- .../PersistentSet/PersistentSet.swift | 1 + 2 files changed, 35 insertions(+), 7 deletions(-) diff --git a/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentSet.md b/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentSet.md index 7853d576..0213e64a 100644 --- a/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentSet.md +++ b/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentSet.md @@ -1,14 +1,41 @@ # ``Collections/PersistentSet`` -Summary - ## Overview -Text - ## Topics -### Binary Set Operations +### Creating a Set + +- ``init()`` +- ``init(_:)-6nn9e`` +- ``init(_:)-6qbps`` +- ``init(_:)-30nei`` + +### Finding Elements + +- ``contains(_:)`` +- ``firstIndex(of:)`` +- ``lastIndex(of:)`` + +### Adding and Updating Elements + +- ``insert(_:)`` +- ``update(with:)`` +- ``update(_:at:)`` + +### Removing Elements + +- ``filter(_:)`` +- ``remove(_:)`` +- ``remove(at:)`` + +### Non-mutating Set Operations + +- ``inserting(_:)`` +- ``updating(with:)`` +- ``removing(_:)`` + +### Combining Sets - ``intersection(_:)-9dx2a`` - ``intersection(_:)-5z4my`` @@ -42,7 +69,7 @@ - ``formSymmetricDifference(_:)-8wue8`` - ``formSymmetricDifference(_:)-4t8jr`` -### Binary Set Predicates +### Comparing Sets - ``==(_:_:)`` - ``isEqual(to:)-3m3in`` @@ -67,4 +94,4 @@ - ``isDisjoint(with:)-12irx`` - ``isDisjoint(with:)-1hhyf`` -- ``isDisjoint(with:)-61lde`` +- ``isDisjoint(with:)-61lde`` diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet.swift index e90aab25..231af51c 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet.swift @@ -9,6 +9,7 @@ // //===----------------------------------------------------------------------===// +/// An unordered collection of unique elements. @frozen // Not really -- this package is not at all ABI stable public struct PersistentSet { @usableFromInline From 84356e58c75abbcc4de4de1c641ec568bbc890fd Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 26 Oct 2022 15:50:53 -0700 Subject: [PATCH 17/39] [PersistentCollection] Back out BidirectionalCollection conformance MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit BidirectionalCollection has the connotation that the ordering of elements is meaningful, which isn’t the case for PersistentSet and PersistentDictionary. --- .../PersistentDictionary+Collection.swift | 51 ++++++---- .../PersistentDictionary+Keys.swift | 26 +++--- .../PersistentDictionary+Values.swift | 26 +++--- .../PersistentSet+Collection.swift | 51 ++++++---- .../CheckBidirectionalCollection.swift | 92 ++++++++++++------- .../Utilities/DictionaryAPIChecker.swift | 8 +- .../PersistentCollections Fixtures.swift | 12 +-- .../PersistentDictionary Tests.swift | 12 ++- .../PersistentDictionary.Keys Tests.swift | 8 +- .../PersistentDictionary.Values Tests.swift | 8 +- .../PersistentSet Tests.swift | 9 +- .../Utilities.swift | 3 +- 12 files changed, 196 insertions(+), 110 deletions(-) diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Collection.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Collection.swift index 0f71e296..a8968aab 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Collection.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Collection.swift @@ -77,7 +77,7 @@ extension PersistentDictionary.Index: CustomDebugStringConvertible { } } -extension PersistentDictionary: BidirectionalCollection { +extension PersistentDictionary: Collection { @inlinable public var isEmpty: Bool { _root.count == 0 @@ -130,14 +130,6 @@ extension PersistentDictionary: BidirectionalCollection { } } - @inlinable - public func formIndex(before i: inout Index) { - precondition(_isValid(i), "Invalid index") - guard i._path.findPredecessorItem(under: _root.raw) else { - preconditionFailure("The start index has no predecessor") - } - } - @inlinable @inline(__always) public func index(after i: Index) -> Index { var i = i @@ -145,13 +137,6 @@ extension PersistentDictionary: BidirectionalCollection { return i } - @inlinable @inline(__always) - public func index(before i: Index) -> Index { - var i = i - formIndex(before: &i) - return i - } - @inlinable public func distance(from start: Index, to end: Index) -> Int { precondition(_isValid(start) && _isValid(end), "Invalid index") @@ -182,3 +167,37 @@ extension PersistentDictionary: BidirectionalCollection { return nil } } + +#if false +// Note: Let's not do this. `BidirectionalCollection` would imply that +// the ordering of elements would be meaningful, which isn't true for +// `PersistentDictionary`. +extension PersistentDictionary: BidirectionalCollection { + /// Replaces the given index with its predecessor. + /// + /// - Parameter i: A valid index of the collection. + /// `i` must be greater than `startIndex`. + /// + /// - Complexity: O(1) + @inlinable + public func formIndex(before i: inout Index) { + precondition(_isValid(i), "Invalid index") + guard i._path.findPredecessorItem(under: _root.raw) else { + preconditionFailure("The start index has no predecessor") + } + } + + /// Returns the position immediately before the given index. + /// + /// - Parameter i: A valid index of the collection. + /// `i` must be greater than `startIndex`. + /// + /// - Complexity: O(1) + @inlinable @inline(__always) + public func index(before i: Index) -> Index { + var i = i + formIndex(before: &i) + return i + } +} +#endif diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Keys.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Keys.swift index abc5da0f..f973ed5c 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Keys.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Keys.swift @@ -102,7 +102,7 @@ extension PersistentDictionary.Keys.Iterator: Sendable where Key: Sendable, Value: Sendable {} #endif -extension PersistentDictionary.Keys: BidirectionalCollection { +extension PersistentDictionary.Keys: Collection { public typealias Index = PersistentDictionary.Index @inlinable @@ -127,21 +127,11 @@ extension PersistentDictionary.Keys: BidirectionalCollection { _base.formIndex(after: &i) } - @inlinable - public func formIndex(before i: inout Index) { - _base.formIndex(before: &i) - } - @inlinable public func index(after i: Index) -> Index { _base.index(after: i) } - @inlinable - public func index(before i: Index) -> Index { - _base.index(before: i) - } - @inlinable public func index(_ i: Index, offsetBy distance: Int) -> Index { _base.index(i, offsetBy: distance) @@ -159,3 +149,17 @@ extension PersistentDictionary.Keys: BidirectionalCollection { _base.distance(from: start, to: end) } } + +#if false +extension PersistentDictionary.Keys: BidirectionalCollection { + @inlinable + public func formIndex(before i: inout Index) { + _base.formIndex(before: &i) + } + + @inlinable + public func index(before i: Index) -> Index { + _base.index(before: i) + } +} +#endif diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Values.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Values.swift index 454e8544..cf8b48a2 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Values.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Values.swift @@ -106,7 +106,7 @@ where Key: Sendable, Value: Sendable {} // Note: This cannot be a MutableCollection because its subscript setter // needs to invalidate indices. -extension PersistentDictionary.Values: BidirectionalCollection { +extension PersistentDictionary.Values: Collection { public typealias Index = PersistentDictionary.Index @inlinable @@ -153,21 +153,11 @@ extension PersistentDictionary.Values: BidirectionalCollection { _base.formIndex(after: &i) } - @inlinable - public func formIndex(before i: inout Index) { - _base.formIndex(before: &i) - } - @inlinable public func index(after i: Index) -> Index { _base.index(after: i) } - @inlinable - public func index(before i: Index) -> Index { - _base.index(before: i) - } - @inlinable public func index(_ i: Index, offsetBy distance: Int) -> Index { _base.index(i, offsetBy: distance) @@ -185,3 +175,17 @@ extension PersistentDictionary.Values: BidirectionalCollection { _base.distance(from: start, to: end) } } + +#if false +extension PersistentDictionary.Values: BidirectionalCollection { + @inlinable + public func formIndex(before i: inout Index) { + _base.formIndex(before: &i) + } + + @inlinable + public func index(before i: Index) -> Index { + _base.index(before: i) + } +} +#endif diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+Collection.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+Collection.swift index 0d832613..0a9eff11 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+Collection.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+Collection.swift @@ -78,7 +78,7 @@ extension PersistentSet.Index: CustomDebugStringConvertible { } } -extension PersistentSet: BidirectionalCollection { +extension PersistentSet: Collection { @inlinable public var isEmpty: Bool { _root.count == 0 @@ -130,14 +130,6 @@ extension PersistentSet: BidirectionalCollection { } } - @inlinable - public func formIndex(before i: inout Index) { - precondition(_isValid(i), "Invalid index") - guard i._path.findPredecessorItem(under: _root.raw) else { - preconditionFailure("The start index has no predecessor") - } - } - @inlinable @inline(__always) public func index(after i: Index) -> Index { var i = i @@ -145,13 +137,6 @@ extension PersistentSet: BidirectionalCollection { return i } - @inlinable @inline(__always) - public func index(before i: Index) -> Index { - var i = i - formIndex(before: &i) - return i - } - @inlinable public func distance(from start: Index, to end: Index) -> Int { precondition(_isValid(start) && _isValid(end), "Invalid index") @@ -221,3 +206,37 @@ extension PersistentSet: BidirectionalCollection { precondition(_isValid(range.lowerBound) && _isValid(range.upperBound)) } } + +#if false +// Note: Let's not do this. `BidirectionalCollection` would imply that +// the ordering of elements would be meaningful, which isn't true for +// `PersistentSet`. +extension PersistentSet: BidirectionalCollection { + /// Replaces the given index with its predecessor. + /// + /// - Parameter i: A valid index of the collection. + /// `i` must be greater than `startIndex`. + /// + /// - Complexity: O(1) + @inlinable + public func formIndex(before i: inout Index) { + precondition(_isValid(i), "Invalid index") + guard i._path.findPredecessorItem(under: _root.raw) else { + preconditionFailure("The start index has no predecessor") + } + } + + /// Returns the position immediately before the given index. + /// + /// - Parameter i: A valid index of the collection. + /// `i` must be greater than `startIndex`. + /// + /// - Complexity: O(1) + @inlinable @inline(__always) + public func index(before i: Index) -> Index { + var i = i + formIndex(before: &i) + return i + } +} +#endif diff --git a/Sources/_CollectionsTestSupport/ConformanceCheckers/CheckBidirectionalCollection.swift b/Sources/_CollectionsTestSupport/ConformanceCheckers/CheckBidirectionalCollection.swift index e0fe1596..34e11bc7 100644 --- a/Sources/_CollectionsTestSupport/ConformanceCheckers/CheckBidirectionalCollection.swift +++ b/Sources/_CollectionsTestSupport/ConformanceCheckers/CheckBidirectionalCollection.swift @@ -80,6 +80,61 @@ public func checkBidirectionalCollection( + _ collection: C, + expectedContents: [C.Element], + by areEquivalent: (C.Element, C.Element) -> Bool, + maxSamples: Int? = nil, + file: StaticString = #file, + line: UInt = #line +) { + var allIndices = collection._indicesByIndexAfter() + allIndices.append(collection.endIndex) + + withSomeRanges( + "range", + in: 0 ..< allIndices.count - (1 as Int), + maxSamples: maxSamples + ) { range in + let i = range.lowerBound + let j = range.upperBound + + // Check `index(_,offsetBy:)` with negative offsets + let a = collection.index(allIndices[j], offsetBy: i - j) + expectEqual(a, allIndices[i]) + if i < expectedContents.count { + expectEquivalent( + collection[a], expectedContents[i], + by: areEquivalent) + } + + // Check `distance(from:to:)` with decreasing indices + let d = collection.distance(from: allIndices[j], to: allIndices[i]) + expectEqual(d, i - j) + } + + // Check `index(_,offsetBy:limitedBy:)` + let limits = + Set([0, allIndices.count - 1, allIndices.count / 2]) + .sorted() + withEvery("limit", in: limits) { limit in + withEvery("i", in: 0 ..< allIndices.count) { i in + let min = -i - (limit <= i ? 2 : 0) + withEvery("delta", in: stride(from: 0, through: min, by: -1)) { delta in + let actual = collection.index( + allIndices[i], + offsetBy: delta, + limitedBy: allIndices[limit]) + let j = i + delta + let expected = i < limit || j >= limit ? allIndices[j] : nil + expectEqual(actual, expected) + } + } + } +} + public func _checkBidirectionalCollection( _ collection: C, expectedContents: S, @@ -112,6 +167,11 @@ public func _checkBidirectionalCollection= limit ? allIndices[j] : nil - expectEqual(actual, expected) - } - } - } - // Check the Indices associated type if C.self != C.Indices.self && C.self != DefaultIndices.self { TestContext.current.withTrace("Indices") { diff --git a/Sources/_CollectionsTestSupport/Utilities/DictionaryAPIChecker.swift b/Sources/_CollectionsTestSupport/Utilities/DictionaryAPIChecker.swift index 936e219e..dc16bfc6 100644 --- a/Sources/_CollectionsTestSupport/Utilities/DictionaryAPIChecker.swift +++ b/Sources/_CollectionsTestSupport/Utilities/DictionaryAPIChecker.swift @@ -107,10 +107,10 @@ public protocol DictionaryAPIExtras: DictionaryAPIChecker { uniqueKeysWithValues keysAndValues: S ) where S.Element == Element - init( - uniqueKeys keys: Keys, - values: Values - ) where Keys.Element == Key, Values.Element == Value +// init( +// uniqueKeys keys: Keys, +// values: Values +// ) where Keys.Element == Key, Values.Element == Value init( _ keysAndValues: S, diff --git a/Tests/PersistentCollectionsTests/PersistentCollections Fixtures.swift b/Tests/PersistentCollectionsTests/PersistentCollections Fixtures.swift index db219e48..8920eef7 100644 --- a/Tests/PersistentCollectionsTests/PersistentCollections Fixtures.swift +++ b/Tests/PersistentCollectionsTests/PersistentCollections Fixtures.swift @@ -38,9 +38,9 @@ extension LifetimeTracker { keyTransform: (C.Element) -> Key, valueTransform: (C.Element) -> Value ) -> PersistentDictionary, LifetimeTracked> { - PersistentDictionary( - uniqueKeys: instances(for: items, by: keyTransform), - values: instances(for: items, by: valueTransform)) + let keys = instances(for: items, by: keyTransform) + let values = instances(for: items, by: valueTransform) + return PersistentDictionary(uniqueKeysWithValues: zip(keys, values)) } func persistentDictionary( @@ -48,9 +48,9 @@ extension LifetimeTracker { by valueTransform: (C.Element) -> Value ) -> PersistentDictionary, LifetimeTracked> where C.Element: Hashable { - PersistentDictionary( - uniqueKeys: instances(for: keys), - values: instances(for: keys, by: valueTransform)) + let k = instances(for: keys) + let v = instances(for: keys, by: valueTransform) + return PersistentDictionary(uniqueKeysWithValues: zip(k, v)) } func dictionary( diff --git a/Tests/PersistentCollectionsTests/PersistentDictionary Tests.swift b/Tests/PersistentCollectionsTests/PersistentDictionary Tests.swift index 738734f5..baa2a30d 100644 --- a/Tests/PersistentCollectionsTests/PersistentDictionary Tests.swift +++ b/Tests/PersistentCollectionsTests/PersistentDictionary Tests.swift @@ -254,14 +254,20 @@ class PersistentDictionaryTests: CollectionTestCase { withEachFixture { fixture in withLifetimeTracking { tracker in let (d, ref) = tracker.persistentDictionary(for: fixture) - checkBidirectionalCollection(d, expectedContents: ref, by: ==) + checkCollection(d, expectedContents: ref, by: ==) + _checkBidirectionalCollection_indexOffsetBy( + d, expectedContents: ref, by: ==) } } } func test_BidirectionalCollection_random100() { - let d = PersistentDictionary(uniqueKeys: 0 ..< 100, values: 0 ..< 100) - checkBidirectionalCollection(d, expectedContents: Array(d), by: ==) + let d = PersistentDictionary( + uniqueKeysWithValues: (0 ..< 100).map { ($0, $0) }) + let ref = Array(d) + checkCollection(d, expectedContents: ref, by: ==) + _checkBidirectionalCollection_indexOffsetBy( + d, expectedContents: ref, by: ==) } #if swift(>=5.6) diff --git a/Tests/PersistentCollectionsTests/PersistentDictionary.Keys Tests.swift b/Tests/PersistentCollectionsTests/PersistentDictionary.Keys Tests.swift index 2a49a413..6fc4784e 100644 --- a/Tests/PersistentCollectionsTests/PersistentDictionary.Keys Tests.swift +++ b/Tests/PersistentCollectionsTests/PersistentDictionary.Keys Tests.swift @@ -18,10 +18,10 @@ class PersistentDictionaryKeysTests: CollectionTestCase { withEachFixture { fixture in withLifetimeTracking { tracker in let (d, ref) = tracker.persistentDictionary(for: fixture) - checkBidirectionalCollection( - d.keys, - expectedContents: ref.map { $0.key }, - by: ==) + let k = ref.map { $0.key } + checkCollection(d.keys, expectedContents: k, by: ==) + _checkBidirectionalCollection_indexOffsetBy( + d.keys, expectedContents: k, by: ==) } } } diff --git a/Tests/PersistentCollectionsTests/PersistentDictionary.Values Tests.swift b/Tests/PersistentCollectionsTests/PersistentDictionary.Values Tests.swift index 76265e4d..e3d93368 100644 --- a/Tests/PersistentCollectionsTests/PersistentDictionary.Values Tests.swift +++ b/Tests/PersistentCollectionsTests/PersistentDictionary.Values Tests.swift @@ -18,10 +18,10 @@ class PersistentDictionaryValuesTests: CollectionTestCase { withEachFixture { fixture in withLifetimeTracking { tracker in let (d, ref) = tracker.persistentDictionary(for: fixture) - checkBidirectionalCollection( - d.values, - expectedContents: ref.map { $0.value }, - by: ==) + let v = ref.map { $0.value } + checkCollection(d.values, expectedContents: v, by: ==) + _checkBidirectionalCollection_indexOffsetBy( + d.values, expectedContents: v, by: ==) } } } diff --git a/Tests/PersistentCollectionsTests/PersistentSet Tests.swift b/Tests/PersistentCollectionsTests/PersistentSet Tests.swift index adce7d93..29785f2d 100644 --- a/Tests/PersistentCollectionsTests/PersistentSet Tests.swift +++ b/Tests/PersistentCollectionsTests/PersistentSet Tests.swift @@ -26,14 +26,19 @@ class PersistentSetTests: CollectionTestCase { withEachFixture { fixture in withLifetimeTracking { tracker in let (set, ref) = tracker.persistentSet(for: fixture) - checkBidirectionalCollection(set, expectedContents: ref, by: ==) + checkCollection(set, expectedContents: ref, by: ==) + _checkBidirectionalCollection_indexOffsetBy( + set, expectedContents: ref, by: ==) } } } func test_BidirectionalCollection_random100() { let s = PersistentSet(0 ..< 100) - checkBidirectionalCollection(s, expectedContents: Array(s)) + let ref = Array(s) + checkCollection(s, expectedContents: ref) + _checkBidirectionalCollection_indexOffsetBy( + s, expectedContents: ref, by: ==) } func test_basics() { diff --git a/Tests/PersistentCollectionsTests/Utilities.swift b/Tests/PersistentCollectionsTests/Utilities.swift index 428ee13a..e5354529 100644 --- a/Tests/PersistentCollectionsTests/Utilities.swift +++ b/Tests/PersistentCollectionsTests/Utilities.swift @@ -25,7 +25,8 @@ extension LifetimeTracker { let k = Array(keys) let keys = self.instances(for: k) let values = self.instances(for: k.map { $0 + 100 }) - let dictionary = PersistentDictionary(uniqueKeys: keys, values: values) + let dictionary = PersistentDictionary( + uniqueKeysWithValues: zip(keys, values)) return (dictionary, keys, values) } } From 1d2a52779cf45b6301b73ddc8c3aa44612eff2f3 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 26 Oct 2022 15:52:12 -0700 Subject: [PATCH 18/39] [PersistentSet] Add missing docs --- .../PersistentSet/PersistentSet+Codable.swift | 4 +- .../PersistentSet+Collection.swift | 140 +++++++++++++++++- .../PersistentSet/PersistentSet+Extras.swift | 15 +- .../PersistentSet/PersistentSet+Filter.swift | 2 +- .../PersistentSet+Sequence.swift | 8 + .../PersistentSet+SetAlgebra basics.swift | 32 ++-- ...rsistentSet+SetAlgebra fluent basics.swift | 41 ++++- ...ersistentSet+SetAlgebra intersection.swift | 7 +- ...PersistentSet+SetAlgebra subtracting.swift | 7 +- .../PersistentSet/PersistentSet.swift | 48 +++++- 10 files changed, 261 insertions(+), 43 deletions(-) diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+Codable.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+Codable.swift index d4a41b77..c8b87f10 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+Codable.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+Codable.swift @@ -10,7 +10,7 @@ //===----------------------------------------------------------------------===// extension PersistentSet: Encodable where Element: Encodable { - /// Encodes the elements of this ordered set into the given encoder. + /// Encodes the elements of this set into the given encoder. /// /// - Parameter encoder: The encoder to write data to. @inlinable @@ -21,7 +21,7 @@ extension PersistentSet: Encodable where Element: Encodable { } extension PersistentSet: Decodable where Element: Decodable { - /// Creates a new ordered set by decoding from the given decoder. + /// Creates a new set by decoding from the given decoder. /// /// This initializer throws an error if reading from the decoder fails, or /// if the decoded contents contain duplicate values. diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+Collection.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+Collection.swift index 0a9eff11..37dfe0f7 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+Collection.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+Collection.swift @@ -10,6 +10,12 @@ //===----------------------------------------------------------------------===// extension PersistentSet { + /// The position of an element in a persistent set. + /// + /// An index in a persistent set is a compact encoding of a path in the + /// underlying prefix tree. Such indices are valid until the tree structure + /// is changed; hence, indices are usually invalidated every time the set + /// gets mutated. @frozen public struct Index { @usableFromInline @@ -38,6 +44,12 @@ where Element: Sendable {} #endif extension PersistentSet.Index: Equatable { + /// Returns a Boolean value indicating whether two index values are equal. + /// + /// Note that comparing two indices that do not belong to the same tree + /// leads to a runtime error. + /// + /// - Complexity: O(1) @inlinable public static func ==(left: Self, right: Self) -> Bool { precondition( @@ -48,6 +60,13 @@ extension PersistentSet.Index: Equatable { } extension PersistentSet.Index: Comparable { + /// Returns a Boolean value indicating whether the value of the first argument + /// is less than the second argument. + /// + /// Note that comparing two indices that do not belong to the same tree + /// leads to a runtime error. + /// + /// - Complexity: O(1) @inlinable public static func <(left: Self, right: Self) -> Bool { precondition( @@ -58,6 +77,10 @@ extension PersistentSet.Index: Comparable { } extension PersistentSet.Index: Hashable { + /// Hashes the essential components of this value by feeding them into the + /// given hasher. + /// + /// - Complexity: O(1) @inlinable public func hash(into hasher: inout Hasher) { hasher.combine(_path) @@ -79,22 +102,36 @@ extension PersistentSet.Index: CustomDebugStringConvertible { } extension PersistentSet: Collection { + /// A Boolean value indicating whether the collection is empty. + /// + /// - Complexity: O(1) @inlinable public var isEmpty: Bool { _root.count == 0 } + /// The number of elements in the collection. + /// + /// - Complexity: O(1) @inlinable public var count: Int { _root.count } + /// The position of the first element in a nonempty collection, or `endIndex` + /// if the collection is empty. + /// + /// - Complexity: O(1) public var startIndex: Index { var path = _UnsafePath(root: _root.raw) path.descendToLeftMostItem() return Index(_root: _root.unmanaged, version: _version, path: path) } + /// The collection’s “past the end” position—that is, the position one greater + /// than the last valid subscript argument. + /// + /// - Complexity: O(1) @inlinable public var endIndex: Index { var path = _UnsafePath(root: _root.raw) @@ -113,15 +150,27 @@ extension PersistentSet: Collection { } /// Accesses the key-value pair at the specified position. + /// + /// - Parameter position: The position of the element to access. `position` + /// must be a valid index of the collection that is not equal to + /// `endIndex`. + /// + /// - Complexity: O(1) @inlinable - public subscript(i: Index) -> Element { - precondition(_isValid(i), "Invalid index") - precondition(i._path.isOnItem, "Can't get element at endIndex") - return _UnsafeHandle.read(i._path.node) { - $0[item: i._path.currentItemSlot].key + public subscript(position: Index) -> Element { + precondition(_isValid(position), "Invalid index") + precondition(position._path.isOnItem, "Can't get element at endIndex") + return _UnsafeHandle.read(position._path.node) { + $0[item: position._path.currentItemSlot].key } } + /// Replaces the given index with its successor. + /// + /// - Parameter i: A valid index of the collection. + /// `i` must be less than `endIndex`. + /// + /// - Complexity: O(1) @inlinable public func formIndex(after i: inout Index) { precondition(_isValid(i), "Invalid index") @@ -130,6 +179,12 @@ extension PersistentSet: Collection { } } + /// Returns the position immediately after the given index. + /// + /// - Parameter i: A valid index of the collection. + /// `i` must be less than `endIndex`. + /// + /// - Complexity: O(1) @inlinable @inline(__always) public func index(after i: Index) -> Index { var i = i @@ -137,12 +192,38 @@ extension PersistentSet: Collection { return i } + /// Returns the distance between two arbitrary valid indices in this + /// collection. + /// + /// - Parameter start: A valid index of the collection. + /// - Parameter end: Another valid index of the collection. + /// - Returns: The distance between `start` and `end`. + /// (The result can be negative, even though `PersistentSet` is not a + /// bidirectional collection.) + /// - Complexity: O(log(`count`)) @inlinable public func distance(from start: Index, to end: Index) -> Int { precondition(_isValid(start) && _isValid(end), "Invalid index") return _root.raw.distance(.top, from: start._path, to: end._path) } + /// Returns an index that is the specified distance from the given index. + /// + /// The value passed as `distance` must not offset `i` beyond the bounds of + /// the collection. + /// + /// - Parameters: + /// - i: A valid index of the collection. + /// - distance: The distance to offset `i`. As a special exception, + /// `distance` is allowed to be negative even though `PersistentSet` + /// isn't a bidirectional collection. + /// - Returns: An index offset by `distance` from the index `i`. If + /// `distance` is positive, this is the same value as the result of + /// `distance` calls to `index(after:)`. If distance is negative, then + /// `distance` calls to `index(after:)` on the returned value will be the + /// same as `start`. + /// + /// - Complexity: O(log(`distance`)) @inlinable public func index(_ i: Index, offsetBy distance: Int) -> Index { precondition(_isValid(i), "Invalid index") @@ -152,6 +233,27 @@ extension PersistentSet: Collection { return i } + /// Returns an index that is the specified distance from the given index, + /// unless that distance is beyond a given limiting index. + /// + /// The value passed as `distance` must not offset `i` beyond the bounds of + /// the collection, unless the index passed as `limit` prevents offsetting + /// beyond those bounds. + /// + /// - Parameters: + /// - i: A valid index of the collection. + /// - distance: The distance to offset `i`. As a special exception, + /// `distance` is allowed to be negative even though `PersistentSet` + /// isn't a bidirectional collection. + /// - limit: A valid index of the collection to use as a limit. If + /// `distance > 0`, a limit that is less than `i` has no effect. + /// Likewise, if `distance < 0`, a limit that is greater than `i` has no + /// effect. + /// - Returns: An index offset by `distance` from the index `i`, unless that + /// index would be beyond `limit` in the direction of movement. In that + /// case, the method returns `nil`. + /// + /// - Complexity: O(log(`distance`)) @inlinable public func index( _ i: Index, offsetBy distance: Int, limitedBy limit: Index @@ -181,6 +283,34 @@ extension PersistentSet: Collection { _index(of: element) } + /// Returns the index of the specified member of the collection, or `nil` if + /// the value isn't a member. + /// + /// - Parameter element: An element to search for in the collection. + /// - Returns: The index where `element` is found. If `element` is not + /// found in the collection, returns `nil`. + /// + /// - Complexity: The expected complexity is O(1) hashing/comparison + /// operations, as long as `Element` properly implements `Hashable`. + @inlinable + public func firstIndex(of element: Element) -> Index? { + _index(of: element) + } + + /// Returns the index of the specified member of the collection, or `nil` if + /// the value isn't a member. + /// + /// - Parameter element: An element to search for in the collection. + /// - Returns: The index where `element` is found. If `element` is not + /// found in the collection, returns `nil`. + /// + /// - Complexity: The expected complexity is O(1) hashing/comparison + /// operations, as long as `Element` properly implements `Hashable`. + @inlinable + public func lastIndex(of element: Element) -> Index? { + _index(of: element) + } + @inlinable internal func _index(of element: Element) -> Index? { let hash = _Hash(element) diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+Extras.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+Extras.swift index bd9ff73b..9166654d 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+Extras.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+Extras.swift @@ -14,6 +14,16 @@ import _CollectionsUtilities extension PersistentSet: _UniqueCollection {} extension PersistentSet { + /// Removes the element at the given valid index. + /// + /// Calling this method invalidates all existing indices of the collection. + /// + /// - Parameter position: The index of the member to remove. `position` must + /// be a valid index of the set, and it must not be equal to the set’s + /// end index. + /// - Returns: The element that was removed from the set. + /// - Complexity: O(log(`count`)) if set storage might be shared; O(1) + /// otherwise. @discardableResult public mutating func remove(at position: Index) -> Element { precondition(_isValid(position)) @@ -30,7 +40,7 @@ extension PersistentSet { /// comparison or some other means. Updating a member through this method /// does not require any hashing operations. /// - /// Calling this method invalidates all existing indices. + /// Calling this method invalidates all existing indices of the collection. /// /// - Parameter item: The new value that should replace the original element. /// `item` must compare equal to the original value. @@ -39,7 +49,8 @@ extension PersistentSet { /// /// - Returns: The original element that was replaced. /// - /// - Complexity: Amortized O(1). + /// - Complexity: O(log(`count`)) if set storage might be shared; O(1) + /// otherwise. 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") diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+Filter.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+Filter.swift index 31d02a48..8e520aae 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+Filter.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+Filter.swift @@ -10,7 +10,7 @@ //===----------------------------------------------------------------------===// extension PersistentSet { - /// Returns a new persistent set containing the values pairs of the ordered + /// Returns a new persistent set containing all the members of this persistent /// set that satisfy the given predicate. /// /// - Parameter isIncluded: A closure that takes a value as its diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+Sequence.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+Sequence.swift index e4a50be9..782defc2 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+Sequence.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+Sequence.swift @@ -10,6 +10,7 @@ //===----------------------------------------------------------------------===// extension PersistentSet: Sequence { + /// An iterator over the members of a `PersistentSet`. @frozen public struct Iterator: IteratorProtocol { @usableFromInline @@ -23,12 +24,19 @@ extension PersistentSet: Sequence { _it = _HashTreeIterator(root: _root) } + /// Advances to the next element and returns it, or `nil` if no next element + /// exists. + /// + /// Once `nil` has been returned, all subsequent calls return `nil`. + /// + /// - Complexity: O(1) public mutating func next() -> Element? { guard let (node, slot) = _it.next() else { return nil } return _UnsafeHandle.read(node) { $0[item: slot].key } } } + /// Returns an iterator over the members of the set. @inlinable public func makeIterator() -> Iterator { Iterator(_root: _root.raw) diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra basics.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra basics.swift index 9d62afe6..ec2cfd27 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra basics.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra basics.swift @@ -17,7 +17,7 @@ extension PersistentSet: SetAlgebra { /// /// - Parameter element: An element to look for in the set. /// - /// - Returns: `true` if `member` exists in the set; otherwise, `false`. + /// - Returns: `true` if `element` 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 @@ -29,6 +29,8 @@ extension PersistentSet: SetAlgebra { /// Insert a new member to this set, if the set doesn't already contain it. /// + /// Inserting a new member invalidates all existing indices of the collection. + /// /// - Parameter newMember: The element to insert into the set. /// /// - Returns: `(true, newMember)` if `newMember` was not contained in the @@ -38,13 +40,10 @@ extension PersistentSet: SetAlgebra { /// 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.) + /// - Complexity: This operation is expected to copy at most O(log(`count`)) + /// existing members and to perform at most O(1) hashing/comparison + /// operations on the `Element` type, as long as `Element` properly + /// implements hashing. @discardableResult @inlinable public mutating func insert( @@ -71,6 +70,9 @@ extension PersistentSet: SetAlgebra { /// Removes the given element from the set. /// + /// Removing an existing member invalidates all existing indices of the + /// collection. + /// /// - Parameter member: The element of the set to remove. /// /// - Returns: The element equal to `member` if `member` is contained in the @@ -78,9 +80,10 @@ extension PersistentSet: SetAlgebra { /// 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. + /// - Complexity: This operation is expected to copy at most O(log(`count`)) + /// existing members and to perform at most O(1) hashing/comparison + /// operations on the `Element` type, as long as `Element` properly + /// implements hashing. @discardableResult @inlinable public mutating func remove(_ member: Element) -> Element? { @@ -105,9 +108,10 @@ extension PersistentSet: SetAlgebra { /// 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. + /// - Complexity: This operation is expected to copy at most O(log(`count`)) + /// existing members and to perform at most O(1) hashing/comparison + /// operations on the `Element` type, as long as `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 45cf7d26..796ee066 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra fluent basics.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra fluent basics.swift @@ -13,20 +13,17 @@ 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. + /// 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.) + /// - Complexity: This operation is expected to copy at most O(log(`count`)) + /// existing members and to perform at most O(1) hashing/comparison + /// operations on the `Element` type, as long as `Element` properly + /// implements hashing. @inlinable public func inserting(_ newMember: __owned Element) -> Self { let hash = _Hash(newMember) @@ -34,6 +31,18 @@ extension PersistentSet { return PersistentSet(_new: r.node) } + /// Return a new set that contains all members of this set except `member`. + /// + /// If `self` does not contain `member`, then this simply returns `self`. + /// + /// - Parameter member: The element to remove. + /// + /// - Returns: A new set with all existing members of `self` except `member`. + /// + /// - Complexity: This operation is expected to copy at most O(log(`count`)) + /// existing members and to perform at most O(1) hashing/comparison + /// operations on the `Element` type, as long as `Element` properly + /// implements hashing. @inlinable public func removing(_ member: Element) -> Self { let hash = _Hash(member) @@ -43,6 +52,22 @@ extension PersistentSet { return PersistentSet(_new: root) } + /// Return a new set that contains `newMember` in addition to all members of + /// this set. + /// + /// If an element equal to `newMember` is already contained in this set, + /// then `newMember` replaces the existing element in the returned result. + /// In some cases, the original element may be distinguishable from + /// `newMember` by identity comparison or some other means. + /// + /// - Parameter newMember: An element to update in the set. + /// + /// - Returns: A new set containing all existing members and `newMember`. + /// + /// - Complexity: This operation is expected to copy at most O(log(`count`)) + /// existing members and to perform at most O(1) hashing/comparison + /// operations on the `Element` type, as long as `Element` properly + /// implements hashing. @inlinable public func updating(with newMember: __owned Element) -> Self { var copy = self diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra intersection.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra intersection.swift index e45c3a5f..3d6bab5a 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra intersection.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra intersection.swift @@ -64,11 +64,8 @@ extension PersistentSet { internal func _intersection( _ other: PersistentCollections._Node ) -> Self { - let builder = _root.intersection(.top, other) - guard let builder = builder else { return self } - let root = builder.finalize(.top) - root._fullInvariantCheck() - return Self(_new: root) + guard let r = _root.intersection(.top, other) else { return self } + return Self(_new: r) } /// Returns a new set with the elements that are common to both this set and diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra subtracting.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra subtracting.swift index 15ced7ff..3d1ef5ff 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra subtracting.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra subtracting.swift @@ -56,11 +56,8 @@ extension PersistentSet { internal __consuming func _subtracting( _ other: PersistentCollections._Node ) -> Self { - let builder = _root.subtracting(.top, other) - guard let builder = builder else { return self } - let root = builder.finalize(.top) - root._fullInvariantCheck() - return Self(_new: root) + guard let r = _root.subtracting(.top, other) else { return self } + return Self(_new: r) } /// Returns a new set containing the elements of this set that do not occur diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet.swift index 231af51c..8a99be1b 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet.swift @@ -9,7 +9,53 @@ // //===----------------------------------------------------------------------===// -/// An unordered collection of unique elements. +/// An unordered collection of unique elements, optimized for mutating shared +/// copies and comparing different snapshots of the same collection. +/// +/// `PersistentSet` has the same functionality as a standard `Set`, and +/// it largely implements the same APIs: both are hashed collection +/// types that conform to `SetAlgebra`, and both are unordered -- neither type +/// provides any guarantees about the ordering of their members. +/// +/// However, `PersistentSet` is optimizing specifically for use cases that +/// need to mutate shared copies or to compare a set value to one of its older +/// snapshots. +/// +/// The standard `Set` stores its members in a single, flat hash table, and it +/// implements value semantics with all-or-nothing copy-on-write behavior: every +/// time a shared copy of a set is mutated, the mutation needs to make a full +/// copy of the set's storage. `PersistentSet` takes a different approach: it +/// organizes its members into a tree structure, the nodes of which can be +/// freely shared across collection values. When mutating a shared copy of a set +/// value, `PersistentSet` is able to simply link the unchanged parts of the +/// tree directly into the result, saving both time and memory. +/// +/// This structural sharing also makes it more efficient to compare mutated set +/// values to earlier versions of themselves. When comparing or combining sets, +/// parts that are shared across both inputs can typically be handled in +/// constant time, leading to a dramatic performance boost when the two inputs +/// are still largely unchanged: +/// +/// var set = PersistentSet(0 ..< 10_000) +/// let copy = set +/// set.insert(20_000) // Expected to be an O(log(n)) operation +/// let diff = set.subtracting(copy) // Also O(log(n))! +/// // `diff` now holds the single item 20_000. +/// +/// The tree structure also eliminates the need to reserve capacity in advance: +/// `PersistentSet` creates, destroys and resizes individual nodes as needed, +/// always consuming just enough memory to store its contents. As of Swift 5.7, +/// the standard collection types never shrink their storage, so temporary +/// storage spikes can linger as unused but still allocated memory long after +/// the collection has shrunk back to its usual size. +/// +/// Of course, switching to a tree structure comes with some trade offs. In +/// particular, inserting new items, removing existing ones, and iterating over +/// a `PersistentSet` is expected to be a constant factor slower than a standard +/// `Set` -- allocating/deallocating nodes isn't free, and navigating the tree +/// structure requires more pointer dereferences than accessing a flat hash +/// table. However the algorithmic improvements above usually more than make up +/// for this, as long as the use case can make use of them. @frozen // Not really -- this package is not at all ABI stable public struct PersistentSet { @usableFromInline From 16687d78afa9754b7b9062e4c3077e7fca989efd Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 26 Oct 2022 18:08:25 -0700 Subject: [PATCH 19/39] [PersistentSet] Add more tests --- .../PersistentSet+CustomReflectable.swift | 2 +- .../PersistentSet Tests.swift | 135 ++++++++++++++++++ 2 files changed, 136 insertions(+), 1 deletion(-) diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+CustomReflectable.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+CustomReflectable.swift index 1a22473c..9f97b071 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+CustomReflectable.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+CustomReflectable.swift @@ -12,6 +12,6 @@ extension PersistentSet: CustomReflectable { /// The custom mirror for this instance. public var customMirror: Mirror { - Mirror(self, unlabeledChildren: self, displayStyle: .collection) + Mirror(self, unlabeledChildren: self, displayStyle: .set) } } diff --git a/Tests/PersistentCollectionsTests/PersistentSet Tests.swift b/Tests/PersistentCollectionsTests/PersistentSet Tests.swift index 29785f2d..f2552165 100644 --- a/Tests/PersistentCollectionsTests/PersistentSet Tests.swift +++ b/Tests/PersistentCollectionsTests/PersistentSet Tests.swift @@ -111,7 +111,11 @@ class PersistentSetTests: CollectionTestCase { let end = a.endIndex expectEqual(end.description, "@.end(1)") expectEqual(end.debugDescription, "@.end(1)") + } + func test_index_hashing() { + let s = PersistentSet(0 ..< 100) + checkHashable(s.indices, equalityOracle: ==) } func test_insert_fixtures() { @@ -138,6 +142,26 @@ class PersistentSetTests: CollectionTestCase { } } + func test_remove_at() { + withEachFixture { fixture in + withEvery("isShared", in: [false, true]) { isShared in + withLifetimeTracking { tracker in + withEvery("offset", in: 0 ..< fixture.count) { offset in + let f = tracker.persistentSet(for: fixture) + var s = f.map + var ref = Set(f.ref) + withHiddenCopies(if: isShared, of: &s) { s in + let i = s.index(s.startIndex, offsetBy: offset) + let old = s.remove(at: i) + expectNotNil(ref.remove(old)) + expectEqualSets(s, ref) + } + } + } + } + } + } + func test_intersection_Self_basics() { let a = RawCollider(1, "A") let b = RawCollider(2, "B") @@ -617,4 +641,115 @@ class PersistentSetTests: CollectionTestCase { } } } + + func test_Hashable() { + let classes: [[PersistentSet]] = [ + [ + [] + ], + [ + ["a"] + ], + [ + ["b"] + ], + [ + ["c"] + ], + [ + ["d"] + ], + [ + ["e"] + ], + [ + ["a", "b"], ["b", "a"], + ], + [ + ["a", "d"], ["d", "a"], + ], + [ + ["a", "b", "c"], ["a", "c", "b"], + ["b", "a", "c"], ["b", "c", "a"], + ["c", "a", "b"], ["c", "b", "a"], + ], + [ + ["a", "d", "e"], ["a", "e", "d"], + ["d", "a", "e"], ["d", "e", "a"], + ["e", "a", "d"], ["e", "d", "a"], + ], + ] + checkHashable(equivalenceClasses: classes) + } + + func test_Codable() throws { + let s1: PersistentSet = [] + let v1: MinimalEncoder.Value = .array([]) + expectEqual(try MinimalEncoder.encode(s1), v1) + + let s2: PersistentSet = [3] + let v2: MinimalEncoder.Value = .array([.int(3)]) + expectEqual(try MinimalEncoder.encode(s2), v2) + + let s3: PersistentSet = [0, 1, 2, 3] + let v3: MinimalEncoder.Value = .array(s3.map { .int($0) }) + expectEqual(try MinimalEncoder.encode(s3), v3) + + let s4 = PersistentSet(0 ..< 100) + let v4: MinimalEncoder.Value = .array(s4.map { .int($0) }) + expectEqual(try MinimalEncoder.encode(s4), v4) + } + + func test_Decodable() throws { + let s1: PersistentSet = [] + let v1: MinimalEncoder.Value = .array([]) + expectEqual(try MinimalDecoder.decode(v1, as: PersistentSet.self), s1) + + let s2: PersistentSet = [3] + let v2: MinimalEncoder.Value = .array([.int(3)]) + expectEqual(try MinimalDecoder.decode(v2, as: PersistentSet.self), s2) + + let s3: PersistentSet = [0, 1, 2, 3] + let v3: MinimalEncoder.Value = .array([.int(0), .int(1), .int(2), .int(3)]) + expectEqual(try MinimalDecoder.decode(v3, as: PersistentSet.self), s3) + + let s4 = PersistentSet(0 ..< 100) + let v4: MinimalEncoder.Value = .array((0 ..< 100).map { .int($0) }) + expectEqual(try MinimalDecoder.decode(v4, as: PersistentSet.self), s4) + + let v5: MinimalEncoder.Value = .array([.int(0), .int(1), .int(0)]) + expectThrows( + try MinimalDecoder.decode(v5, as: PersistentSet.self) + ) { error in + expectNotNil(error as? DecodingError) { error in + guard case .dataCorrupted(let context) = error else { + expectFailure("Unexpected error \(error)") + return + } + expectEqual(context.debugDescription, + "Decoded elements aren't unique (first duplicate at offset 2)") + } + } + + let v6: MinimalEncoder.Value = .array([.int16(42)]) + expectThrows( + try MinimalDecoder.decode(v6, as: PersistentSet.self) + ) { error in + expectNotNil(error as? DecodingError) { error in + guard case .typeMismatch(_, _) = error else { + expectFailure("Unexpected error \(error)") + return + } + } + } + } + + func test_CustomReflectable() { + let s: PersistentSet = [0, 1, 2, 3] + let mirror = Mirror(reflecting: s) + expectEqual(mirror.displayStyle, .set) + expectNil(mirror.superclassMirror) + expectTrue(mirror.children.compactMap { $0.label }.isEmpty) + expectEqualElements(mirror.children.map { $0.value as? Int }, s.map { $0 }) + } } From 7dd47aa336078eb04e879749bfc93c6aa6f4a420 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 26 Oct 2022 18:09:50 -0700 Subject: [PATCH 20/39] [Benchmark] Work on PeristentSet and PersistentDictionary benchmarks --- ...ections.json => PersistentDictionary.json} | 7 +- Benchmarks/Libraries/PersistentSet.json | 748 ++++++++++++++++++ .../Benchmarks/PersistentSetBenchmarks.swift | 436 ++++++++++ .../Sources/Benchmarks/SetBenchmarks.swift | 58 +- Benchmarks/Sources/benchmark-tool/main.swift | 1 + 5 files changed, 1243 insertions(+), 7 deletions(-) rename Benchmarks/Libraries/{PersistentCollections.json => PersistentDictionary.json} (98%) create mode 100644 Benchmarks/Libraries/PersistentSet.json create mode 100644 Benchmarks/Sources/Benchmarks/PersistentSetBenchmarks.swift diff --git a/Benchmarks/Libraries/PersistentCollections.json b/Benchmarks/Libraries/PersistentDictionary.json similarity index 98% rename from Benchmarks/Libraries/PersistentCollections.json rename to Benchmarks/Libraries/PersistentDictionary.json index 91a32753..2457a4d0 100644 --- a/Benchmarks/Libraries/PersistentCollections.json +++ b/Benchmarks/Libraries/PersistentDictionary.json @@ -1,6 +1,6 @@ { "kind": "group", - "title": "PersistentCollections Benchmarks", + "title": "PersistentDictionary Benchmarks", "directory": "Results", "contents": [ { @@ -41,11 +41,6 @@ } ] }, - { - "kind": "group", - "title": "HashSet Operations", - "contents": [] - }, { "kind": "group", "title": "Comparisons against reference implementations", diff --git a/Benchmarks/Libraries/PersistentSet.json b/Benchmarks/Libraries/PersistentSet.json new file mode 100644 index 00000000..5dd857be --- /dev/null +++ b/Benchmarks/Libraries/PersistentSet.json @@ -0,0 +1,748 @@ +{ + "kind": "group", + "title": "PersistentSet Benchmarks", + "directory": "Results", + "contents": [ + { + "kind": "chart", + "title": "operations", + "tasks": [ + "PersistentSet init from range", + "PersistentSet init from unsafe buffer", + "PersistentSet sequential iteration", + "PersistentSet successful contains", + "PersistentSet unsuccessful contains", + "PersistentSet insert", + "PersistentSet remove" + ] + }, + { + "kind": "chart", + "title": "initializers", + "tasks": [ + "PersistentSet init from range", + "PersistentSet init from unsafe buffer", + ] + }, + { + "kind": "variants", + "charts": [ + { + "kind": "chart", + "title": "union with Self", + "tasks": [ + "PersistentSet union with Self (0% overlap)", + "PersistentSet union with Self (25% overlap)", + "PersistentSet union with Self (50% overlap)", + "PersistentSet union with Self (75% overlap)", + "PersistentSet union with Self (100% overlap)", + ] + }, + { + "kind": "chart", + "title": "union with Array", + "tasks": [ + "PersistentSet union with Array (0% overlap)", + "PersistentSet union with Array (25% overlap)", + "PersistentSet union with Array (50% overlap)", + "PersistentSet union with Array (75% overlap)", + "PersistentSet union with Array (100% overlap)", + ] + }, + { + "kind": "chart", + "title": "formUnion with Self", + "tasks": [ + "PersistentSet formUnion with Self (0% overlap)", + "PersistentSet formUnion with Self (25% overlap)", + "PersistentSet formUnion with Self (50% overlap)", + "PersistentSet formUnion with Self (75% overlap)", + "PersistentSet formUnion with Self (100% overlap)", + ] + }, + { + "kind": "chart", + "title": "formUnion with Array", + "tasks": [ + "PersistentSet formUnion with Array (0% overlap)", + "PersistentSet formUnion with Array (25% overlap)", + "PersistentSet formUnion with Array (50% overlap)", + "PersistentSet formUnion with Array (75% overlap)", + "PersistentSet formUnion with Array (100% overlap)", + ] + }, + ] + }, + { + "kind": "variants", + "charts": [ + { + "kind": "chart", + "title": "intersection with Self", + "tasks": [ + "PersistentSet intersection with Self (0% overlap)", + "PersistentSet intersection with Self (25% overlap)", + "PersistentSet intersection with Self (50% overlap)", + "PersistentSet intersection with Self (75% overlap)", + "PersistentSet intersection with Self (100% overlap)", + ] + }, + { + "kind": "chart", + "title": "intersection with Array", + "tasks": [ + "PersistentSet intersection with Array (0% overlap)", + "PersistentSet intersection with Array (25% overlap)", + "PersistentSet intersection with Array (50% overlap)", + "PersistentSet intersection with Array (75% overlap)", + "PersistentSet intersection with Array (100% overlap)", + ] + }, + { + "kind": "chart", + "title": "formIntersection with Self", + "tasks": [ + "PersistentSet formIntersection with Self (0% overlap)", + "PersistentSet formIntersection with Self (25% overlap)", + "PersistentSet formIntersection with Self (50% overlap)", + "PersistentSet formIntersection with Self (75% overlap)", + "PersistentSet formIntersection with Self (100% overlap)", + ] + }, + { + "kind": "chart", + "title": "formIntersection with Array", + "tasks": [ + "PersistentSet formIntersection with Array (0% overlap)", + "PersistentSet formIntersection with Array (25% overlap)", + "PersistentSet formIntersection with Array (50% overlap)", + "PersistentSet formIntersection with Array (75% overlap)", + "PersistentSet formIntersection with Array (100% overlap)", + ] + }, + ] + }, + { + "kind": "variants", + "charts": [ + { + "kind": "chart", + "title": "symmetricDifference with Self", + "tasks": [ + "PersistentSet symmetricDifference with Self (0% overlap)", + "PersistentSet symmetricDifference with Self (25% overlap)", + "PersistentSet symmetricDifference with Self (50% overlap)", + "PersistentSet symmetricDifference with Self (75% overlap)", + "PersistentSet symmetricDifference with Self (100% overlap)", + ] + }, + { + "kind": "chart", + "title": "symmetricDifference with Array", + "tasks": [ + "PersistentSet symmetricDifference with Array (0% overlap)", + "PersistentSet symmetricDifference with Array (25% overlap)", + "PersistentSet symmetricDifference with Array (50% overlap)", + "PersistentSet symmetricDifference with Array (75% overlap)", + "PersistentSet symmetricDifference with Array (100% overlap)", + ] + }, + { + "kind": "chart", + "title": "formSymmetricDifference with Self", + "tasks": [ + "PersistentSet formSymmetricDifference with Self (0% overlap)", + "PersistentSet formSymmetricDifference with Self (25% overlap)", + "PersistentSet formSymmetricDifference with Self (50% overlap)", + "PersistentSet formSymmetricDifference with Self (75% overlap)", + "PersistentSet formSymmetricDifference with Self (100% overlap)", + ] + }, + { + "kind": "chart", + "title": "formSymmetricDifference with Array", + "tasks": [ + "PersistentSet formSymmetricDifference with Array (0% overlap)", + "PersistentSet formSymmetricDifference with Array (25% overlap)", + "PersistentSet formSymmetricDifference with Array (50% overlap)", + "PersistentSet formSymmetricDifference with Array (75% overlap)", + "PersistentSet formSymmetricDifference with Array (100% overlap)", + ] + }, + ] + }, + { + "kind": "variants", + "charts": [ + { + "kind": "chart", + "title": "subtracting Self", + "tasks": [ + "PersistentSet subtracting Self (0% overlap)", + "PersistentSet subtracting Self (25% overlap)", + "PersistentSet subtracting Self (50% overlap)", + "PersistentSet subtracting Self (75% overlap)", + "PersistentSet subtracting Self (100% overlap)", + ] + }, + { + "kind": "chart", + "title": "subtracting Array", + "tasks": [ + "PersistentSet subtracting Array (0% overlap)", + "PersistentSet subtracting Array (25% overlap)", + "PersistentSet subtracting Array (50% overlap)", + "PersistentSet subtracting Array (75% overlap)", + "PersistentSet subtracting Array (100% overlap)", + ] + }, + { + "kind": "chart", + "title": "subtract Self", + "tasks": [ + "PersistentSet subtract Self (0% overlap)", + "PersistentSet subtract Self (25% overlap)", + "PersistentSet subtract Self (50% overlap)", + "PersistentSet subtract Self (75% overlap)", + "PersistentSet subtract Self (100% overlap)", + ] + }, + { + "kind": "chart", + "title": "subtract with Array", + "tasks": [ + "PersistentSet subtract Array (0% overlap)", + "PersistentSet subtract Array (25% overlap)", + "PersistentSet subtract Array (50% overlap)", + "PersistentSet subtract Array (75% overlap)", + "PersistentSet subtract Array (100% overlap)", + ] + }, + ] + }, + { + "kind": "group", + "title": "Reference comparisons", + "directory": "versus", + "contents": [ + { + "kind": "chart", + "title": "init from buffer of integers", + "tasks": [ + "PersistentSet init from unsafe buffer", + "Set init from unsafe buffer", + ] + }, + { + "kind": "chart", + "title": "init from range of integers", + "tasks": [ + "PersistentSet init from range", + "Set init from range", + ] + }, + { + "kind": "chart", + "title": "sequential iteration", + "tasks": [ + "PersistentSet sequential iteration", + "Set sequential iteration", + ] + }, + { + "kind": "chart", + "title": "sequential iteration using indices", + "tasks": [ + "PersistentSet sequential iteration, indices", + "Set sequential iteration, indices", + ] + }, + { + "kind": "chart", + "title": "successful random lookups", + "tasks": [ + "PersistentSet successful contains", + "Set successful contains", + ] + }, + { + "kind": "chart", + "title": "unsuccessful random lookups", + "tasks": [ + "PersistentSet unsuccessful contains", + "Set unsuccessful contains", + ] + }, + { + "kind": "chart", + "title": "insert", + "tasks": [ + "PersistentSet insert", + "PersistentSet insert, shared", + "Set insert", + "Set insert, reserving capacity", + "Set insert, shared", + ] + }, + { + "kind": "chart", + "title": "diffing", + "tasks": [ + "PersistentSet insert one + subtract, shared", + "Set insert one + subtract, shared", + ] + }, + { + "kind": "chart", + "title": "remove", + "tasks": [ + "PersistentSet remove", + "PersistentSet remove, shared", + "Set remove", + "Set remove, shared", + ] + }, + { + "kind": "variants", + "charts": [ + { + "kind": "chart", + "title": "union (0% overlap)", + "tasks": [ + "OrderedSet union with Self (0% overlap)", + "OrderedSet union with Array (0% overlap)", + "Set union with Self (0% overlap)", + "Set union with Array (0% overlap)", + ] + }, + { + "kind": "chart", + "title": "union (25% overlap)", + "tasks": [ + "OrderedSet union with Self (25% overlap)", + "OrderedSet union with Array (25% overlap)", + "Set union with Self (25% overlap)", + "Set union with Array (25% overlap)", + ] + }, + { + "kind": "chart", + "title": "union (50% overlap)", + "tasks": [ + "OrderedSet union with Self (50% overlap)", + "OrderedSet union with Array (50% overlap)", + "Set union with Self (50% overlap)", + "Set union with Array (50% overlap)", + ] + }, + { + "kind": "chart", + "title": "union (75% overlap)", + "tasks": [ + "OrderedSet union with Self (75% overlap)", + "OrderedSet union with Array (75% overlap)", + "Set union with Self (75% overlap)", + "Set union with Array (75% overlap)", + ] + }, + { + "kind": "chart", + "title": "union (100% overlap)", + "tasks": [ + "OrderedSet union with Self (100% overlap)", + "OrderedSet union with Array (100% overlap)", + "Set union with Self (100% overlap)", + "Set union with Array (100% overlap)", + ] + }, + ] + }, + { + "kind": "variants", + "charts": [ + { + "kind": "chart", + "title": "formUnion (0% overlap)", + "tasks": [ + "OrderedSet formUnion with Self (0% overlap)", + "OrderedSet formUnion with Array (0% overlap)", + "Set formUnion with Self (0% overlap)", + "Set formUnion with Array (0% overlap)", + ] + }, + { + "kind": "chart", + "title": "formUnion (25% overlap)", + "tasks": [ + "OrderedSet formUnion with Self (25% overlap)", + "OrderedSet formUnion with Array (25% overlap)", + "Set formUnion with Self (25% overlap)", + "Set formUnion with Array (25% overlap)", + ] + }, + { + "kind": "chart", + "title": "formUnion (50% overlap)", + "tasks": [ + "OrderedSet formUnion with Self (50% overlap)", + "OrderedSet formUnion with Array (50% overlap)", + "Set formUnion with Self (50% overlap)", + "Set formUnion with Array (50% overlap)", + ] + }, + { + "kind": "chart", + "title": "formUnion (75% overlap)", + "tasks": [ + "OrderedSet formUnion with Self (75% overlap)", + "OrderedSet formUnion with Array (75% overlap)", + "Set formUnion with Self (75% overlap)", + "Set formUnion with Array (75% overlap)", + ] + }, + { + "kind": "chart", + "title": "formUnion (100% overlap)", + "tasks": [ + "OrderedSet formUnion with Self (100% overlap)", + "OrderedSet formUnion with Array (100% overlap)", + "Set formUnion with Self (100% overlap)", + "Set formUnion with Array (100% overlap)", + ] + }, + ] + }, + { + "kind": "variants", + "charts": [ + { + "kind": "chart", + "title": "intersection (0% overlap)", + "tasks": [ + "OrderedSet intersection with Self (0% overlap)", + "OrderedSet intersection with Array (0% overlap)", + "Set intersection with Self (0% overlap)", + "Set intersection with Array (0% overlap)", + ] + }, + { + "kind": "chart", + "title": "intersection (25% overlap)", + "tasks": [ + "OrderedSet intersection with Self (25% overlap)", + "OrderedSet intersection with Array (25% overlap)", + "Set intersection with Self (25% overlap)", + "Set intersection with Array (25% overlap)", + ] + }, + { + "kind": "chart", + "title": "intersection (50% overlap)", + "tasks": [ + "OrderedSet intersection with Self (50% overlap)", + "OrderedSet intersection with Array (50% overlap)", + "Set intersection with Self (50% overlap)", + "Set intersection with Array (50% overlap)", + ] + }, + { + "kind": "chart", + "title": "intersection (75% overlap)", + "tasks": [ + "OrderedSet intersection with Self (75% overlap)", + "OrderedSet intersection with Array (75% overlap)", + "Set intersection with Self (75% overlap)", + "Set intersection with Array (75% overlap)", + ] + }, + { + "kind": "chart", + "title": "intersection (100% overlap)", + "tasks": [ + "OrderedSet intersection with Self (100% overlap)", + "OrderedSet intersection with Array (100% overlap)", + "Set intersection with Self (100% overlap)", + "Set intersection with Array (100% overlap)", + ] + }, + ] + }, + { + "kind": "variants", + "charts": [ + { + "kind": "chart", + "title": "formIntersection (0% overlap)", + "tasks": [ + "OrderedSet formIntersection with Self (0% overlap)", + "OrderedSet formIntersection with Array (0% overlap)", + "Set formIntersection with Self (0% overlap)", + "Set formIntersection with Array (0% overlap)", + ] + }, + { + "kind": "chart", + "title": "formIntersection (25% overlap)", + "tasks": [ + "OrderedSet formIntersection with Self (25% overlap)", + "OrderedSet formIntersection with Array (25% overlap)", + "Set formIntersection with Self (25% overlap)", + "Set formIntersection with Array (25% overlap)", + ] + }, + { + "kind": "chart", + "title": "formIntersection (50% overlap)", + "tasks": [ + "OrderedSet formIntersection with Self (50% overlap)", + "OrderedSet formIntersection with Array (50% overlap)", + "Set formIntersection with Self (50% overlap)", + "Set formIntersection with Array (50% overlap)", + ] + }, + { + "kind": "chart", + "title": "formIntersection (75% overlap)", + "tasks": [ + "OrderedSet formIntersection with Self (75% overlap)", + "OrderedSet formIntersection with Array (75% overlap)", + "Set formIntersection with Self (75% overlap)", + "Set formIntersection with Array (75% overlap)", + ] + }, + { + "kind": "chart", + "title": "formIntersection (100% overlap)", + "tasks": [ + "OrderedSet formIntersection with Self (100% overlap)", + "OrderedSet formIntersection with Array (100% overlap)", + "Set formIntersection with Self (100% overlap)", + "Set formIntersection with Array (100% overlap)", + ] + }, + ] + }, + { + "kind": "variants", + "charts": [ + { + "kind": "chart", + "title": "symmetricDifference (0% overlap)", + "tasks": [ + "OrderedSet symmetricDifference with Self (0% overlap)", + "OrderedSet symmetricDifference with Array (0% overlap)", + "Set symmetricDifference with Self (0% overlap)", + "Set symmetricDifference with Array (0% overlap)", + ] + }, + { + "kind": "chart", + "title": "symmetricDifference (25% overlap)", + "tasks": [ + "OrderedSet symmetricDifference with Self (25% overlap)", + "OrderedSet symmetricDifference with Array (25% overlap)", + "Set symmetricDifference with Self (25% overlap)", + "Set symmetricDifference with Array (25% overlap)", + ] + }, + { + "kind": "chart", + "title": "symmetricDifference (50% overlap)", + "tasks": [ + "OrderedSet symmetricDifference with Self (50% overlap)", + "OrderedSet symmetricDifference with Array (50% overlap)", + "Set symmetricDifference with Self (50% overlap)", + "Set symmetricDifference with Array (50% overlap)", + ] + }, + { + "kind": "chart", + "title": "symmetricDifference (75% overlap)", + "tasks": [ + "OrderedSet symmetricDifference with Self (75% overlap)", + "OrderedSet symmetricDifference with Array (75% overlap)", + "Set symmetricDifference with Self (75% overlap)", + "Set symmetricDifference with Array (75% overlap)", + ] + }, + { + "kind": "chart", + "title": "symmetricDifference (100% overlap)", + "tasks": [ + "OrderedSet symmetricDifference with Self (100% overlap)", + "OrderedSet symmetricDifference with Array (100% overlap)", + "Set symmetricDifference with Self (100% overlap)", + "Set symmetricDifference with Array (100% overlap)", + ] + }, + ] + }, + { + "kind": "variants", + "charts": [ + { + "kind": "chart", + "title": "formSymmetricDifference (0% overlap)", + "tasks": [ + "OrderedSet formSymmetricDifference with Self (0% overlap)", + "OrderedSet formSymmetricDifference with Array (0% overlap)", + "Set formSymmetricDifference with Self (0% overlap)", + "Set formSymmetricDifference with Array (0% overlap)", + ] + }, + { + "kind": "chart", + "title": "formSymmetricDifference (25% overlap)", + "tasks": [ + "OrderedSet formSymmetricDifference with Self (25% overlap)", + "OrderedSet formSymmetricDifference with Array (25% overlap)", + "Set formSymmetricDifference with Self (25% overlap)", + "Set formSymmetricDifference with Array (25% overlap)", + ] + }, + { + "kind": "chart", + "title": "formSymmetricDifference (50% overlap)", + "tasks": [ + "OrderedSet formSymmetricDifference with Self (50% overlap)", + "OrderedSet formSymmetricDifference with Array (50% overlap)", + "Set formSymmetricDifference with Self (50% overlap)", + "Set formSymmetricDifference with Array (50% overlap)", + ] + }, + { + "kind": "chart", + "title": "formSymmetricDifference (75% overlap)", + "tasks": [ + "OrderedSet formSymmetricDifference with Self (75% overlap)", + "OrderedSet formSymmetricDifference with Array (75% overlap)", + "Set formSymmetricDifference with Self (75% overlap)", + "Set formSymmetricDifference with Array (75% overlap)", + ] + }, + { + "kind": "chart", + "title": "formSymmetricDifference (100% overlap)", + "tasks": [ + "OrderedSet formSymmetricDifference with Self (100% overlap)", + "OrderedSet formSymmetricDifference with Array (100% overlap)", + "Set formSymmetricDifference with Self (100% overlap)", + "Set formSymmetricDifference with Array (100% overlap)", + ] + }, + ] + }, + { + "kind": "variants", + "charts": [ + { + "kind": "chart", + "title": "subtracting (0% overlap)", + "tasks": [ + "OrderedSet subtracting Self (0% overlap)", + "OrderedSet subtracting Array (0% overlap)", + "Set subtracting Self (0% overlap)", + "Set subtracting Array (0% overlap)", + ] + }, + { + "kind": "chart", + "title": "subtracting (25% overlap)", + "tasks": [ + "OrderedSet subtracting Self (25% overlap)", + "OrderedSet subtracting Array (25% overlap)", + "Set subtracting Self (25% overlap)", + "Set subtracting Array (25% overlap)", + ] + }, + { + "kind": "chart", + "title": "subtracting (50% overlap)", + "tasks": [ + "OrderedSet subtracting Self (50% overlap)", + "OrderedSet subtracting Array (50% overlap)", + "Set subtracting Self (50% overlap)", + "Set subtracting Array (50% overlap)", + ] + }, + { + "kind": "chart", + "title": "subtracting (75% overlap)", + "tasks": [ + "OrderedSet subtracting Self (75% overlap)", + "OrderedSet subtracting Array (75% overlap)", + "Set subtracting Self (75% overlap)", + "Set subtracting Array (75% overlap)", + ] + }, + { + "kind": "chart", + "title": "subtracting (100% overlap)", + "tasks": [ + "OrderedSet subtracting Self (100% overlap)", + "OrderedSet subtracting Array (100% overlap)", + "Set subtracting Self (100% overlap)", + "Set subtracting Array (100% overlap)", + ] + }, + ] + }, + { + "kind": "variants", + "charts": [ + { + "kind": "chart", + "title": "subtract (0% overlap)", + "tasks": [ + "OrderedSet subtract Self (0% overlap)", + "OrderedSet subtract Array (0% overlap)", + "Set subtract Self (0% overlap)", + "Set subtract Array (0% overlap)", + ] + }, + { + "kind": "chart", + "title": "subtract (25% overlap)", + "tasks": [ + "OrderedSet subtract Self (25% overlap)", + "OrderedSet subtract Array (25% overlap)", + "Set subtract Self (25% overlap)", + "Set subtract Array (25% overlap)", + ] + }, + { + "kind": "chart", + "title": "subtract (50% overlap)", + "tasks": [ + "OrderedSet subtract Self (50% overlap)", + "OrderedSet subtract Array (50% overlap)", + "Set subtract Self (50% overlap)", + "Set subtract Array (50% overlap)", + ] + }, + { + "kind": "chart", + "title": "subtract (75% overlap)", + "tasks": [ + "OrderedSet subtract Self (75% overlap)", + "OrderedSet subtract Array (75% overlap)", + "Set subtract Self (75% overlap)", + "Set subtract Array (75% overlap)", + ] + }, + { + "kind": "chart", + "title": "subtract (100% overlap)", + "tasks": [ + "OrderedSet subtract Self (100% overlap)", + "OrderedSet subtract Array (100% overlap)", + "Set subtract Self (100% overlap)", + "Set subtract Array (100% overlap)", + ] + }, + ] + }, + ] + }, + ] +} diff --git a/Benchmarks/Sources/Benchmarks/PersistentSetBenchmarks.swift b/Benchmarks/Sources/Benchmarks/PersistentSetBenchmarks.swift new file mode 100644 index 00000000..15db530c --- /dev/null +++ b/Benchmarks/Sources/Benchmarks/PersistentSetBenchmarks.swift @@ -0,0 +1,436 @@ +//===----------------------------------------------------------------------===// +// +// 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 CollectionsBenchmark +import PersistentCollections + +extension Benchmark { + public mutating func addPersistentSetBenchmarks() { + self.addSimple( + title: "PersistentSet init from range", + input: Int.self + ) { size in + blackHole(PersistentSet(0 ..< size)) + } + + self.addSimple( + title: "PersistentSet init from unsafe buffer", + input: [Int].self + ) { input in + input.withUnsafeBufferPointer { buffer in + blackHole(PersistentSet(buffer)) + } + } + + self.add( + title: "PersistentSet sequential iteration", + input: Int.self + ) { size in + let set = PersistentSet(0 ..< size) + return { timer in + for i in set { + blackHole(i) + } + } + } + + self.add( + title: "PersistentSet sequential iteration, indices", + input: Int.self + ) { size in + let set = PersistentSet(0 ..< size) + return { timer in + for i in set.indices { + blackHole(set[i]) + } + } + } + + self.add( + title: "PersistentSet successful contains", + input: ([Int], [Int]).self + ) { input, lookups in + let set = PersistentSet(input) + return { timer in + for i in lookups { + precondition(set.contains(i)) + } + } + } + + self.add( + title: "PersistentSet unsuccessful contains", + input: ([Int], [Int]).self + ) { input, lookups in + let set = PersistentSet(input) + let lookups = lookups.map { $0 + input.count } + return { timer in + for i in lookups { + precondition(!set.contains(i)) + } + } + } + + self.addSimple( + title: "PersistentSet insert", + input: [Int].self + ) { input in + var set: PersistentSet = [] + for i in input { + set.insert(i) + } + precondition(set.count == input.count) + blackHole(set) + } + + self.addSimple( + title: "PersistentSet insert, shared", + input: [Int].self + ) { input in + var set: PersistentSet = [] + for i in input { + let copy = set + set.insert(i) + blackHole(copy) + } + precondition(set.count == input.count) + blackHole(set) + } + + self.add( + title: "PersistentSet insert one + subtract, shared", + input: [Int].self + ) { input in + let original = PersistentSet(input) + let newMember = input.count + return { timer in + var copy = original + copy.insert(newMember) + let diff = copy.subtracting(original) + precondition(diff.count == 1 && diff.first == newMember) + blackHole(copy) + } + } + + do { + var timer = Timer() + let input = 0 ..< 1_000 + let newMember = input.count + + let original = PersistentSet(input) + timer.measure { + var copy = original + copy.insert(newMember) + let diff = copy.subtracting(original) + precondition(diff.count == 1 && diff.first == newMember) + blackHole(copy) + } + } + + self.add( + title: "PersistentSet remove", + input: ([Int], [Int]).self + ) { input, removals in + return { timer in + var set = PersistentSet(input) + for i in removals { + set.remove(i) + } + precondition(set.isEmpty) + blackHole(set) + } + } + + self.add( + title: "PersistentSet remove, shared", + input: ([Int], [Int]).self + ) { input, removals in + return { timer in + var set = PersistentSet(input) + for i in removals { + let copy = set + set.remove(i) + blackHole(copy) + } + precondition(set.isEmpty) + blackHole(set) + } + } + + let overlaps: [(String, (Int) -> Int)] = [ + ("0%", { c in c }), + ("25%", { c in 3 * c / 4 }), + ("50%", { c in c / 2 }), + ("75%", { c in c / 4 }), + ("100%", { c in 0 }), + ] + + // SetAlgebra operations with Self + do { + for (percentage, start) in overlaps { + self.add( + title: "PersistentSet union with Self (\(percentage) overlap)", + input: [Int].self + ) { input in + let start = start(input.count) + let a = PersistentSet(input) + let b = PersistentSet(start ..< start + input.count) + return { timer in + blackHole(a.union(identity(b))) + } + } + } + + for (percentage, start) in overlaps { + self.add( + title: "PersistentSet intersection with Self (\(percentage) overlap)", + input: [Int].self + ) { input in + let start = start(input.count) + let a = PersistentSet(input) + let b = PersistentSet(start ..< start + input.count) + return { timer in + blackHole(a.intersection(identity(b))) + } + } + } + + for (percentage, start) in overlaps { + self.add( + title: "PersistentSet symmetricDifference with Self (\(percentage) overlap)", + input: [Int].self + ) { input in + let start = start(input.count) + let a = PersistentSet(input) + let b = PersistentSet(start ..< start + input.count) + return { timer in + blackHole(a.symmetricDifference(identity(b))) + } + } + } + + for (percentage, start) in overlaps { + self.add( + title: "PersistentSet subtracting Self (\(percentage) overlap)", + input: [Int].self + ) { input in + let start = start(input.count) + let a = PersistentSet(input) + let b = PersistentSet(start ..< start + input.count) + return { timer in + blackHole(a.subtracting(identity(b))) + } + } + } + } + + // SetAlgebra operations with Array + do { + for (percentage, start) in overlaps { + self.add( + title: "PersistentSet union with Array (\(percentage) overlap)", + input: [Int].self + ) { input in + let start = start(input.count) + let a = PersistentSet(input) + let b = Array(start ..< start + input.count) + return { timer in + blackHole(a.union(identity(b))) + } + } + } + + for (percentage, start) in overlaps { + self.add( + title: "PersistentSet intersection with Array (\(percentage) overlap)", + input: [Int].self + ) { input in + let start = start(input.count) + let a = PersistentSet(input) + let b = Array(start ..< start + input.count) + return { timer in + blackHole(a.intersection(identity(b))) + } + } + } + + for (percentage, start) in overlaps { + self.add( + title: "PersistentSet symmetricDifference with Array (\(percentage) overlap)", + input: [Int].self + ) { input in + let start = start(input.count) + let a = PersistentSet(input) + let b = Array(start ..< start + input.count) + return { timer in + blackHole(a.symmetricDifference(identity(b))) + } + } + } + + for (percentage, start) in overlaps { + self.add( + title: "PersistentSet subtracting Array (\(percentage) overlap)", + input: [Int].self + ) { input in + let start = start(input.count) + let a = PersistentSet(input) + let b = Array(start ..< start + input.count) + return { timer in + blackHole(a.subtracting(identity(b))) + } + } + } + } + + // SetAlgebra mutations with Self + do { + for (percentage, start) in overlaps { + self.add( + title: "PersistentSet formUnion with Self (\(percentage) overlap)", + input: [Int].self + ) { input in + let start = start(input.count) + let b = PersistentSet(start ..< start + input.count) + return { timer in + var a = PersistentSet(input) + timer.measure { + a.formUnion(identity(b)) + } + blackHole(a) + } + } + } + + for (percentage, start) in overlaps { + self.add( + title: "PersistentSet formIntersection with Self (\(percentage) overlap)", + input: [Int].self + ) { input in + let start = start(input.count) + let b = PersistentSet(start ..< start + input.count) + return { timer in + var a = PersistentSet(input) + timer.measure { + a.formIntersection(identity(b)) + } + blackHole(a) + } + } + } + + for (percentage, start) in overlaps { + self.add( + title: "PersistentSet formSymmetricDifference with Self (\(percentage) overlap)", + input: [Int].self + ) { input in + let start = start(input.count) + let b = PersistentSet(start ..< start + input.count) + return { timer in + var a = PersistentSet(input) + timer.measure { + a.formSymmetricDifference(identity(b)) + } + blackHole(a) + } + } + } + + for (percentage, start) in overlaps { + self.add( + title: "PersistentSet subtract Self (\(percentage) overlap)", + input: [Int].self + ) { input in + let start = start(input.count) + let b = PersistentSet(start ..< start + input.count) + return { timer in + var a = PersistentSet(input) + timer.measure { + a.subtract(identity(b)) + } + blackHole(a) + } + } + } + } + + // SetAlgebra mutations with Array + do { + for (percentage, start) in overlaps { + self.add( + title: "PersistentSet formUnion with Array (\(percentage) overlap)", + input: [Int].self + ) { input in + let start = start(input.count) + let b = Array(start ..< start + input.count) + return { timer in + var a = PersistentSet(input) + timer.measure { + a.formUnion(identity(b)) + } + blackHole(a) + } + } + } + + for (percentage, start) in overlaps { + self.add( + title: "PersistentSet formIntersection with Array (\(percentage) overlap)", + input: [Int].self + ) { input in + let start = start(input.count) + let b = Array(start ..< start + input.count) + return { timer in + var a = PersistentSet(input) + timer.measure { + a.formIntersection(identity(b)) + } + blackHole(a) + } + } + } + + for (percentage, start) in overlaps { + self.add( + title: "PersistentSet formSymmetricDifference with Array (\(percentage) overlap)", + input: [Int].self + ) { input in + let start = start(input.count) + let b = Array(start ..< start + input.count) + return { timer in + var a = PersistentSet(input) + timer.measure { + a.formSymmetricDifference(identity(b)) + } + blackHole(a) + } + } + } + + for (percentage, start) in overlaps { + self.add( + title: "PersistentSet subtract Array (\(percentage) overlap)", + input: [Int].self + ) { input in + let start = start(input.count) + let b = Array(start ..< start + input.count) + return { timer in + var a = PersistentSet(input) + timer.measure { + a.subtract(identity(b)) + } + blackHole(a) + } + } + } + } + } +} diff --git a/Benchmarks/Sources/Benchmarks/SetBenchmarks.swift b/Benchmarks/Sources/Benchmarks/SetBenchmarks.swift index 3a853b6a..776ba4a4 100644 --- a/Benchmarks/Sources/Benchmarks/SetBenchmarks.swift +++ b/Benchmarks/Sources/Benchmarks/SetBenchmarks.swift @@ -61,6 +61,18 @@ extension Benchmark { } } + self.add( + title: "Set sequential iteration, indices", + input: Int.self + ) { size in + let set = Set(0 ..< size) + return { timer in + for i in set.indices { + blackHole(set[i]) + } + } + } + self.add( title: "Set successful contains", input: ([Int], [Int]).self @@ -111,6 +123,35 @@ extension Benchmark { blackHole(set) } + self.addSimple( + title: "Set insert, shared", + input: [Int].self + ) { input in + var set: Set = [] + for i in input { + let copy = set + set.insert(i) + blackHole(copy) + } + precondition(set.count == input.count) + blackHole(set) + } + + self.add( + title: "Set insert one + subtract, shared", + input: [Int].self + ) { input in + let original = Set(input) + let newMember = input.count + return { timer in + var copy = original + copy.insert(newMember) + let diff = copy.subtracting(original) + precondition(diff.count == 1 && diff.first == newMember) + blackHole(copy) + } + } + self.add( title: "Set remove", input: ([Int], [Int]).self @@ -125,6 +166,22 @@ extension Benchmark { } } + self.add( + title: "Set remove, shared", + input: ([Int], [Int]).self + ) { input, removals in + return { timer in + var set = Set(input) + for i in removals { + let copy = set + set.remove(i) + blackHole(copy) + } + precondition(set.isEmpty) + blackHole(set) + } + } + let overlaps: [(String, (Int) -> Int)] = [ ("0%", { c in c }), ("25%", { c in 3 * c / 4 }), @@ -392,6 +449,5 @@ extension Benchmark { } } } - } } diff --git a/Benchmarks/Sources/benchmark-tool/main.swift b/Benchmarks/Sources/benchmark-tool/main.swift index 11594f5a..9231fb25 100644 --- a/Benchmarks/Sources/benchmark-tool/main.swift +++ b/Benchmarks/Sources/benchmark-tool/main.swift @@ -35,6 +35,7 @@ benchmark.addOrderedSetBenchmarks() benchmark.addOrderedDictionaryBenchmarks() benchmark.addHeapBenchmarks() benchmark.addBitSetBenchmarks() +benchmark.addPersistentSetBenchmarks() benchmark.addCppBenchmarks() #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) benchmark.addFoundationBenchmarks() From d8e8f5cc1950bd5c38b57253435ffbe099d6df54 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 27 Oct 2022 17:59:31 -0700 Subject: [PATCH 21/39] [PersistentDictionary] Tweak docs --- .../Extensions/PersistentDictionary.Keys.md | 10 +++ .../Extensions/PersistentDictionary.Values.md | 10 +++ .../Extensions/PersistentDictionary.md | 71 +++++++++++++++++++ ...Collectons.md => PersistentCollections.md} | 0 4 files changed, 91 insertions(+) create mode 100644 Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentDictionary.Keys.md create mode 100644 Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentDictionary.Values.md create mode 100644 Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentDictionary.md rename Sources/PersistentCollections/PersistentCollections.docc/{PersistentCollectons.md => PersistentCollections.md} (100%) diff --git a/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentDictionary.Keys.md b/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentDictionary.Keys.md new file mode 100644 index 00000000..c9c0b4e9 --- /dev/null +++ b/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentDictionary.Keys.md @@ -0,0 +1,10 @@ +# ``PersistentCollections/PersistentDictionary/Keys-swift.struct`` + +Summary + +## Overview + +Text + +## Topics + diff --git a/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentDictionary.Values.md b/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentDictionary.Values.md new file mode 100644 index 00000000..21acbd0b --- /dev/null +++ b/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentDictionary.Values.md @@ -0,0 +1,10 @@ +# ``PersistentCollections/PersistentDictionary/Values-swift.struct`` + +Summary + +## Overview + +Text + +## Topics + diff --git a/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentDictionary.md b/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentDictionary.md new file mode 100644 index 00000000..f39254ce --- /dev/null +++ b/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentDictionary.md @@ -0,0 +1,71 @@ +# ``Collections/PersistentDictionary`` + +## Overview + +## Topics + +### Collection Views + +- ``Keys-swift.struct`` +- ``Values-swift.struct`` +- ``keys-swift.property`` +- ``values-swift.property`` + +### Creating a Dictionary + +- ``init()`` +- ``init(_:)-7jshe`` +- ``init(_:)-8ls8p`` +- ``init(uniqueKeysWithValues:)-65ax0`` +- ``init(uniqueKeysWithValues:)-5ok18`` +- ``init(_:uniquingKeysWith:)-7fuzu`` +- ``init(_:uniquingKeysWith:)-4jee3`` +- ``init(grouping:by:)-8ntzv`` +- ``init(grouping:by:)-7cu86`` +- ``init(keys:valueGenerator:)`` + + +### Inspecting a Dictionary + +- ``isEmpty`` +- ``count`` + +### Accessing Keys and Values + +- ``subscript(_:)-g0oi`` +- ``subscript(_:default:)`` +- ``contains(_:)`` +- ``index(forKey:)`` + +### Adding or Updating Keys and Values + +- ``updateValue(_:forKey:)`` +- ``updateValue(forKey:with:)`` +- ``updateValue(forKey:default:with:)`` +- ``merge(_:uniquingKeysWith:)-853bf`` +- ``merge(_:uniquingKeysWith:)-19xxn`` +- ``merge(_:uniquingKeysWith:)-2osh`` +- ``merging(_:uniquingKeysWith:)-2a7cl`` +- ``merging(_:uniquingKeysWith:)-1tq3e`` +- ``merging(_:uniquingKeysWith:)-2kjqq`` + +### Removing Keys and Values + +- ``removeValue(forKey:)`` +- ``remove(at:)`` + +### Non-mutating Dictionary Operations + +- ``updatingValue(_:forKey:)`` +- ``removingValue(forKey:)`` + +### Comparing Dictionaries + +- ``==(_:_:)`` + +### Transforming a Dictionary + +- ``filter(_:)`` +- ``mapValues(_:)`` +- ``compactMapValues(_:)`` + diff --git a/Sources/PersistentCollections/PersistentCollections.docc/PersistentCollectons.md b/Sources/PersistentCollections/PersistentCollections.docc/PersistentCollections.md similarity index 100% rename from Sources/PersistentCollections/PersistentCollections.docc/PersistentCollectons.md rename to Sources/PersistentCollections/PersistentCollections.docc/PersistentCollections.md From 1e1decfa6efdd848690d0a6b044c41d19af243a1 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 27 Oct 2022 17:59:54 -0700 Subject: [PATCH 22/39] [PersistentCollections] Tweak DocC docs --- .../Extensions/PersistentDictionary.Keys.md | 6 ++---- .../Extensions/PersistentDictionary.Values.md | 6 ++---- .../Extensions/PersistentDictionary.md | 6 ++++-- .../PersistentCollections.docc/Extensions/PersistentSet.md | 6 ++++-- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentDictionary.Keys.md b/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentDictionary.Keys.md index c9c0b4e9..20dd1333 100644 --- a/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentDictionary.Keys.md +++ b/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentDictionary.Keys.md @@ -1,10 +1,8 @@ # ``PersistentCollections/PersistentDictionary/Keys-swift.struct`` -Summary + -## Overview - -Text + ## Topics diff --git a/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentDictionary.Values.md b/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentDictionary.Values.md index 21acbd0b..fa533287 100644 --- a/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentDictionary.Values.md +++ b/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentDictionary.Values.md @@ -1,10 +1,8 @@ # ``PersistentCollections/PersistentDictionary/Values-swift.struct`` -Summary + -## Overview - -Text + ## Topics diff --git a/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentDictionary.md b/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentDictionary.md index f39254ce..4fee9a68 100644 --- a/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentDictionary.md +++ b/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentDictionary.md @@ -1,6 +1,8 @@ -# ``Collections/PersistentDictionary`` +# ``PersistentCollections/PersistentDictionary`` -## Overview + + + ## Topics diff --git a/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentSet.md b/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentSet.md index 0213e64a..99966d05 100644 --- a/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentSet.md +++ b/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentSet.md @@ -1,6 +1,8 @@ -# ``Collections/PersistentSet`` +# ``PersistentCollections/PersistentSet`` -## Overview + + + ## Topics From 8a1b16229ba39afa7eed7aac6639115f804547ba Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 27 Oct 2022 10:55:24 -0700 Subject: [PATCH 23/39] [PersistentDictionary] Add initializer taking Self --- .../PersistentDictionary+Initializers.swift | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Initializers.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Initializers.swift index e8dedf1e..9e4dcc01 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Initializers.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Initializers.swift @@ -20,6 +20,11 @@ extension PersistentDictionary { self = other } + @inlinable + public init(_ other: Dictionary) { + self.init(uniqueKeysWithValues: other) + } + // FIXME: This is a non-standard addition @inlinable public init( From 6dd3756609011243f88007cb250c4899e85c725d Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 27 Oct 2022 10:56:36 -0700 Subject: [PATCH 24/39] [PersistentDictionary] Remove init(uniqueKeys:values:) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This initializer was interesting for OrderedDictionary, where it made for more efficient initialization of storage, but it’s less useful for other dictionary types. --- .../PersistentDictionary+Initializers.swift | 8 -------- .../PersistentDictionary Tests.swift | 13 ------------- 2 files changed, 21 deletions(-) diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Initializers.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Initializers.swift index 9e4dcc01..456868fc 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Initializers.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Initializers.swift @@ -61,14 +61,6 @@ extension PersistentDictionary { uniqueKeysWithValues: keysAndValues.lazy.map { ($0.key, $0.value ) }) } - @inlinable - public init( - uniqueKeys keys: Keys, - values: Values - ) where Keys.Element == Key, Values.Element == Value { - self.init(uniqueKeysWithValues: zip(keys, values)) - } - public init( _ keysAndValues: S, uniquingKeysWith combine: (Value, Value) throws -> Value ) rethrows where S.Element == (Key, Value) { diff --git a/Tests/PersistentCollectionsTests/PersistentDictionary Tests.swift b/Tests/PersistentCollectionsTests/PersistentDictionary Tests.swift index baa2a30d..b366f088 100644 --- a/Tests/PersistentCollectionsTests/PersistentDictionary Tests.swift +++ b/Tests/PersistentCollectionsTests/PersistentDictionary Tests.swift @@ -1589,19 +1589,6 @@ class PersistentDictionaryTests: CollectionTestCase { expectEqualElements(d.sorted(by: <), items.sorted(by: <)) } - func test_uniqueKeys_values() { - let items: [(key: String, value: Int)] = [ - (key: "zero", value: 0), - (key: "one", value: 1), - (key: "two", value: 2), - (key: "three", value: 3) - ] - let d = PersistentDictionary( - uniqueKeys: ["zero", "one", "two", "three"], - values: [0, 1, 2, 3]) - expectEqualElements(d.sorted(by: <), items.sorted(by: <)) - } - // func test_uniquing_initializer_labeled_tuples() { // let items: KeyValuePairs = [ // "a": 1, From 57554c65c259f1c14db0083c4b7f96bd1f7bc3b2 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 27 Oct 2022 10:57:16 -0700 Subject: [PATCH 25/39] [PersistentDictionary] Add an argument label for init(keys:valueGenerator:) --- .../PersistentDictionary+Initializers.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Initializers.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Initializers.swift index 456868fc..fb912d84 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Initializers.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Initializers.swift @@ -29,7 +29,7 @@ extension PersistentDictionary { @inlinable public init( keys: PersistentSet, - _ valueTransform: (Key) throws -> Value + valueGenerator valueTransform: (Key) throws -> Value ) rethrows { let root = try keys._root.mapValues { try valueTransform($0.key) } self.init(_new: root) From 18a01247a3c5162954a5e5c2794b67251d5e8f66 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 27 Oct 2022 18:00:34 -0700 Subject: [PATCH 26/39] [PersistentDictionary] Add missing documentation comments --- .../Node/_Node+Structural intersection.swift | 19 +- .../Node/_Node+Structural subtracting.swift | 19 +- .../Extensions/PersistentDictionary.Keys.md | 8 - .../Extensions/PersistentDictionary.Values.md | 8 - .../Extensions/PersistentDictionary.md | 5 +- .../Extensions/PersistentSet.md | 66 ++++- .../PersistentDictionary+Codable.swift | 3 + .../PersistentDictionary+Collection.swift | 116 +++++++- ...rsistentDictionary+CustomReflectable.swift | 1 + .../PersistentDictionary+Equatable.swift | 6 + ...onary+ExpressibleByDictionaryLiteral.swift | 17 ++ .../PersistentDictionary+Filter.swift | 10 + ...rsistentDictionary+Fluent Operations.swift | 61 ++++ .../PersistentDictionary+Hashable.swift | 4 + .../PersistentDictionary+Initializers.swift | 192 ++++++++++++- .../PersistentDictionary+Keys.swift | 33 ++- .../PersistentDictionary+MapValues.swift | 36 +++ .../PersistentDictionary+Merge.swift | 186 ++++++++++++ .../PersistentDictionary+Sequence.swift | 18 ++ .../PersistentDictionary.swift | 266 +++++++++++++----- .../PersistentDictionary Smoke Tests.swift | 6 + 21 files changed, 978 insertions(+), 102 deletions(-) delete mode 100644 Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentDictionary.Keys.md delete mode 100644 Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentDictionary.Values.md create mode 100644 Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Fluent Operations.swift diff --git a/Sources/PersistentCollections/Node/_Node+Structural intersection.swift b/Sources/PersistentCollections/Node/_Node+Structural intersection.swift index 4fbebcbc..72adda82 100644 --- a/Sources/PersistentCollections/Node/_Node+Structural intersection.swift +++ b/Sources/PersistentCollections/Node/_Node+Structural intersection.swift @@ -14,6 +14,19 @@ extension _Node { internal func intersection( _ level: _Level, _ other: _Node + ) -> _Node? { + assert(level.isAtRoot) + let builder = _intersection(level, other) + guard let builder = builder else { return nil } + let root = builder.finalize(.top) + root._fullInvariantCheck() + return root + } + + @inlinable + internal func _intersection( + _ level: _Level, + _ other: _Node ) -> Builder? { if self.raw.storage === other.raw.storage { return nil } @@ -68,7 +81,7 @@ extension _Node { else if r.childMap.contains(bucket) { let rslot = r.childMap.slot(of: bucket) let branch = l[child: lslot] - .intersection(level.descend(), r[child: rslot]) + ._intersection(level.descend(), r[child: rslot]) if let branch = branch { assert(branch.count < self.count) if !removing { @@ -143,7 +156,7 @@ extension _Node { } if r.childMap.contains(bucket) { let rslot = r.childMap.slot(of: bucket) - return intersection(level.descend(), r[child: rslot]) + return _intersection(level.descend(), r[child: rslot]) .map { .childBranch(level, $0, at: bucket) } } return .empty(level) @@ -166,7 +179,7 @@ extension _Node { } if l.childMap.contains(bucket) { let lslot = l.childMap.slot(of: bucket) - let branch = l[child: lslot].intersection(level.descend(), 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) diff --git a/Sources/PersistentCollections/Node/_Node+Structural subtracting.swift b/Sources/PersistentCollections/Node/_Node+Structural subtracting.swift index 498447d0..4540974b 100644 --- a/Sources/PersistentCollections/Node/_Node+Structural subtracting.swift +++ b/Sources/PersistentCollections/Node/_Node+Structural subtracting.swift @@ -14,6 +14,19 @@ extension _Node { internal func subtracting( _ level: _Level, _ other: _Node + ) -> _Node? { + assert(level.isAtRoot) + let builder = _subtracting(level, other) + guard let builder = builder else { return nil } + let root = builder.finalize(.top) + root._fullInvariantCheck() + return root + } + + @inlinable + internal func _subtracting( + _ level: _Level, + _ other: _Node ) -> Builder? { if self.raw.storage === other.raw.storage { return .empty(level) } @@ -73,7 +86,7 @@ extension _Node { else if r.childMap.contains(bucket) { let rslot = r.childMap.slot(of: bucket) let child = l[child: lslot] - .subtracting(level.descend(), r[child: rslot]) + ._subtracting(level.descend(), r[child: rslot]) if let child = child { assert(child.count < self.count) if !removing { @@ -149,7 +162,7 @@ extension _Node { } else if r.childMap.contains(bucket) { let rslot = r.childMap.slot(of: bucket) - return subtracting(level.descend(), r[child: rslot]) + return _subtracting(level.descend(), r[child: rslot]) .map { .childBranch(level, $0, at: bucket) } } return nil @@ -173,7 +186,7 @@ extension _Node { } if l.childMap.contains(bucket) { let lslot = l.childMap.slot(of: bucket) - let branch = l[child: lslot].subtracting(level.descend(), other) + let branch = l[child: lslot]._subtracting(level.descend(), other) guard let branch = branch else { return nil } var result = self._removingChild(level, at: bucket, lslot) result.addNewChildBranch(level, branch, at: bucket) diff --git a/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentDictionary.Keys.md b/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentDictionary.Keys.md deleted file mode 100644 index 20dd1333..00000000 --- a/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentDictionary.Keys.md +++ /dev/null @@ -1,8 +0,0 @@ -# ``PersistentCollections/PersistentDictionary/Keys-swift.struct`` - - - - - -## Topics - diff --git a/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentDictionary.Values.md b/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentDictionary.Values.md deleted file mode 100644 index fa533287..00000000 --- a/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentDictionary.Values.md +++ /dev/null @@ -1,8 +0,0 @@ -# ``PersistentCollections/PersistentDictionary/Values-swift.struct`` - - - - - -## Topics - diff --git a/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentDictionary.md b/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentDictionary.md index 4fee9a68..cd20ab78 100644 --- a/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentDictionary.md +++ b/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentDictionary.md @@ -29,14 +29,13 @@ ### Inspecting a Dictionary -- ``isEmpty`` -- ``count`` +- ``isEmpty-65s43`` +- ``count-9cdqd`` ### Accessing Keys and Values - ``subscript(_:)-g0oi`` - ``subscript(_:default:)`` -- ``contains(_:)`` - ``index(forKey:)`` ### Adding or Updating Keys and Values diff --git a/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentSet.md b/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentSet.md index 99966d05..d0c03d00 100644 --- a/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentSet.md +++ b/Sources/PersistentCollections/PersistentCollections.docc/Extensions/PersistentSet.md @@ -1,6 +1,70 @@ # ``PersistentCollections/PersistentSet`` - +### Implementation Details + +`PersistentSet` and `PersistentDictionary` are based on a Swift adaptation +of the *Compressed Hash-Array Mapped Prefix Tree* (CHAMP) data structure. + +- Michael J Steindorfer and Jurgen J Vinju. Optimizing Hash-Array Mapped + Tries for Fast and Lean Immutable JVM Collections. In *Proc. + International Conference on Object-Oriented Programming, Systems, + Languages, and Applications,* pp. 783-800, 2015. + https://doi.org/10.1145/2814270.2814312 + +In this setup, the members of such a collection are organized into a tree +data structure based on their hash values. For example, assuming 16 bit hash +values sliced into 4-bit chunks, each node in the prefix tree would have +sixteen slots (one for each digit), each of which may contain a member, a +child node reference, or it may be empty. A `PersistentSet` containing the +tree items `Maximo`, `Julia` and `Don Pablo` (with hash values of `0x2B65`, +`0xA69F` and `0xADA1`, respectively) may be organized into a prefix tree of +two nodes: + +``` +┌0┬1┬2───────┬3┬4┬5┬6┬7┬8┬9┬A──┬B┬C┬D┬E┬F┐ +│ │ │ Maximo │ │ │ │ │ │ │ │ • │ │ │ │ │ │ +└─┴─┴────────┴─┴─┴─┴─┴─┴─┴─┴─┼─┴─┴─┴─┴─┴─┘ + ╎ + ╎ + ┌0┬1┬2┬3┬4┬5┬6───┴──┬7┬8┬9┬A┬B┬C┬D──────────┬E┬F┐ + │ │ │ │ │ │ │ Julia │ │ │ │ │ │ │ Don Pablo │ │ │ + └─┴─┴─┴─┴─┴─┴───────┴─┴─┴─┴─┴─┴─┴───────────┴─┴─┘ +``` + +The root node directly contains `Maximo`, because it is the only set member +whose hash value starts with `8`. However, the first digits of the hashes of +`Julia` and `Don Pablo` are both `A`, so these items reside in a separate +node, one level below the root. + +(To save space, nodes are actually stored in a more compact form, with just +enough space allocated to store their contents: empty slots do not take up +any room. Hence the term "compressed" in "Compressed Hash-Array Mapped +Prefix Tree".) + +The resulting tree structure lends itself well to sharing nodes across +multiple collection values. Inserting or removing an item in a completely +shared tree requires copying at most log(n) nodes -- every node along the +path to the item needs to be uniqued, but all other nodes can remain shared. +While the cost of copying this many nodes isn't trivial, it is dramatically +lower than the cost of having to copy the entire data structure, like the +standard `Set` has to do. + +When looking up a particular member, we descend from the root node, +following along the path specified by successive digits of the member's hash +value. As long as hash values are unique, we will either find the member +we're looking for, or we will know for sure that it does not exist in the +set. + +In practice, hash values aren't guaranteed to be unique though. Members with +conflicting hash values need to be collected in special collision nodes that +are able to grow as large as necessary to contain all colliding members that +share the same hash. Looking up a member in one of these nodes requires a +linear search, so it is crucial that such collisions do not happen often. + +As long as `Element` properly implements `Hashable`, lookup operations in a +`PersistentSet` are expected to be able to decide whether the set contains a +particular item by looking at no more than a constant number of items on +average -- typically they will need to compare against just one member. diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Codable.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Codable.swift index 1c523328..11dd98b0 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Codable.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Codable.swift @@ -38,6 +38,9 @@ internal struct _DictionaryCodingKey: CodingKey { extension PersistentDictionary: Encodable where Key: Encodable, Value: Encodable { + /// Encodes the elements of this dictionary into the given encoder. + /// + /// - Parameter encoder: The encoder to write data to. public func encode(to encoder: Encoder) throws { if Key.self == String.self { // Since the keys are already Strings, we can use them as keys directly. diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Collection.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Collection.swift index a8968aab..51341042 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Collection.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Collection.swift @@ -10,6 +10,12 @@ //===----------------------------------------------------------------------===// extension PersistentDictionary { + /// The position of an element in a persistent dictionary. + /// + /// An index in a persistent dictionary is a compact encoding of a path in + /// the underlying prefix tree. Such indices are valid until the tree + /// structure is changed; hence, indices are usually invalidated every time + /// the dictionary gets mutated. @frozen public struct Index { @usableFromInline @@ -38,6 +44,12 @@ where Key: Sendable, Value: Sendable {} #endif extension PersistentDictionary.Index: Equatable { + /// Returns a Boolean value indicating whether two index values are equal. + /// + /// Note that comparing two indices that do not belong to the same tree + /// leads to a runtime error. + /// + /// - Complexity: O(1) @inlinable public static func ==(left: Self, right: Self) -> Bool { precondition( @@ -47,14 +59,14 @@ extension PersistentDictionary.Index: Equatable { } } -extension PersistentDictionary.Index: Hashable { - @inlinable - public func hash(into hasher: inout Hasher) { - hasher.combine(_path) - } -} - extension PersistentDictionary.Index: Comparable { + /// Returns a Boolean value indicating whether the value of the first argument + /// is less than the second argument. + /// + /// Note that comparing two indices that do not belong to the same tree + /// leads to a runtime error. + /// + /// - Complexity: O(1) public static func <(left: Self, right: Self) -> Bool { precondition( left._root == right._root && left._version == right._version, @@ -63,6 +75,17 @@ extension PersistentDictionary.Index: Comparable { } } +extension PersistentDictionary.Index: Hashable { + /// Hashes the essential components of this value by feeding them into the + /// given hasher. + /// + /// - Complexity: O(1) + @inlinable + public func hash(into hasher: inout Hasher) { + hasher.combine(_path) + } +} + extension PersistentDictionary.Index: CustomStringConvertible { // A textual representation of this instance. public var description: String { @@ -78,16 +101,26 @@ extension PersistentDictionary.Index: CustomDebugStringConvertible { } extension PersistentDictionary: Collection { + /// A Boolean value indicating whether the collection is empty. + /// + /// - Complexity: O(1) @inlinable public var isEmpty: Bool { _root.count == 0 } + /// The number of elements in the collection. + /// + /// - Complexity: O(1) @inlinable public var count: Int { _root.count } + /// The position of the first element in a nonempty collection, or `endIndex` + /// if the collection is empty. + /// + /// - Complexity: O(1) @inlinable public var startIndex: Index { var path = _UnsafePath(root: _root.raw) @@ -95,6 +128,10 @@ extension PersistentDictionary: Collection { return Index(_root: _root.unmanaged, version: _version, path: path) } + /// The collection’s “past the end” position—that is, the position one greater + /// than the last valid subscript argument. + /// + /// - Complexity: O(1) @inlinable public var endIndex: Index { var path = _UnsafePath(root: _root.raw) @@ -113,6 +150,12 @@ extension PersistentDictionary: Collection { } /// Accesses the key-value pair at the specified position. + /// + /// - Parameter position: The position of the element to access. `position` + /// must be a valid index of the collection that is not equal to + /// `endIndex`. + /// + /// - Complexity: O(1) @inlinable public subscript(i: Index) -> Element { precondition(_isValid(i), "Invalid index") @@ -122,6 +165,12 @@ extension PersistentDictionary: Collection { } } + /// Replaces the given index with its successor. + /// + /// - Parameter i: A valid index of the collection. + /// `i` must be less than `endIndex`. + /// + /// - Complexity: O(1) @inlinable public func formIndex(after i: inout Index) { precondition(_isValid(i), "Invalid index") @@ -130,6 +179,12 @@ extension PersistentDictionary: Collection { } } + /// Returns the position immediately after the given index. + /// + /// - Parameter i: A valid index of the collection. + /// `i` must be less than `endIndex`. + /// + /// - Complexity: O(1) @inlinable @inline(__always) public func index(after i: Index) -> Index { var i = i @@ -137,12 +192,38 @@ extension PersistentDictionary: Collection { return i } + /// Returns the distance between two arbitrary valid indices in this + /// collection. + /// + /// - Parameter start: A valid index of the collection. + /// - Parameter end: Another valid index of the collection. + /// - Returns: The distance between `start` and `end`. + /// (The result can be negative, even though `PersistentDictionary` is not + /// a bidirectional collection.) + /// - Complexity: O(log(`count`)) @inlinable public func distance(from start: Index, to end: Index) -> Int { precondition(_isValid(start) && _isValid(end), "Invalid index") return _root.raw.distance(.top, from: start._path, to: end._path) } + /// Returns an index that is the specified distance from the given index. + /// + /// The value passed as `distance` must not offset `i` beyond the bounds of + /// the collection. + /// + /// - Parameters: + /// - i: A valid index of the collection. + /// - distance: The distance to offset `i`. As a special exception, + /// `distance` is allowed to be negative even though + /// `PersistentDictionary` isn't a bidirectional collection. + /// - Returns: An index offset by `distance` from the index `i`. If + /// `distance` is positive, this is the same value as the result of + /// `distance` calls to `index(after:)`. If distance is negative, then + /// `distance` calls to `index(after:)` on the returned value will be the + /// same as `start`. + /// + /// - Complexity: O(log(`distance`)) @inlinable public func index(_ i: Index, offsetBy distance: Int) -> Index { precondition(_isValid(i), "Invalid index") @@ -152,6 +233,27 @@ extension PersistentDictionary: Collection { return i } + /// Returns an index that is the specified distance from the given index, + /// unless that distance is beyond a given limiting index. + /// + /// The value passed as `distance` must not offset `i` beyond the bounds of + /// the collection, unless the index passed as `limit` prevents offsetting + /// beyond those bounds. + /// + /// - Parameters: + /// - i: A valid index of the collection. + /// - distance: The distance to offset `i`. As a special exception, + /// `distance` is allowed to be negative even though + /// `PersistentDictionary` isn't a bidirectional collection. + /// - limit: A valid index of the collection to use as a limit. If + /// `distance > 0`, a limit that is less than `i` has no effect. + /// Likewise, if `distance < 0`, a limit that is greater than `i` has no + /// effect. + /// - Returns: An index offset by `distance` from the index `i`, unless that + /// index would be beyond `limit` in the direction of movement. In that + /// case, the method returns `nil`. + /// + /// - Complexity: O(log(`distance`)) @inlinable public func index( _ i: Index, offsetBy distance: Int, limitedBy limit: Index diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+CustomReflectable.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+CustomReflectable.swift index fde019a9..8d967200 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+CustomReflectable.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+CustomReflectable.swift @@ -10,6 +10,7 @@ //===----------------------------------------------------------------------===// extension PersistentDictionary: CustomReflectable { + /// The custom mirror for this instance. public var customMirror: Mirror { Mirror(self, unlabeledChildren: self, displayStyle: .dictionary) } diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Equatable.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Equatable.swift index f4d8f23a..55205e7f 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Equatable.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Equatable.swift @@ -10,6 +10,12 @@ //===----------------------------------------------------------------------===// extension PersistentDictionary: Equatable where Value: Equatable { + /// Returns a Boolean value indicating whether two values are equal. + /// + /// Two persistent dictionaries are considered equal if they contain the same + /// key-value pairs, but not necessarily in the same order. + /// + /// - Complexity: O(`min(left.count, right.count)`) @inlinable public static func == (left: Self, right: Self) -> Bool { left._root.isEqual(to: right._root, by: { $0 == $1 }) diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+ExpressibleByDictionaryLiteral.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+ExpressibleByDictionaryLiteral.swift index ebe99b7d..fa7cc08f 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+ExpressibleByDictionaryLiteral.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+ExpressibleByDictionaryLiteral.swift @@ -10,6 +10,23 @@ //===----------------------------------------------------------------------===// extension PersistentDictionary: ExpressibleByDictionaryLiteral { + /// Creates a new dictionary from the contents of a dictionary literal. + /// + /// The literal must not contain duplicate elements. + /// + /// Do not call this initializer directly. It is used by the compiler when + /// you use a dictionary literal. Instead, create a new dictionary using a + /// dictionary literal as its value by enclosing a comma-separated list of + /// values in square brackets. You can use a dictionary literal anywhere a + /// persistent dictionary is expected by the type context. + /// + /// Like the standard `Dictionary`, persistent dictionaries do not preserve + /// the order of elements inside the array literal. + /// + /// - Parameter elements: A variadic list of elements of the new set. + /// + /// - Complexity: O(`elements.count`) if `Element` properly implements + /// hashing. @inlinable @inline(__always) public init(dictionaryLiteral elements: (Key, Value)...) { diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Filter.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Filter.swift index 6e6272fe..823e4922 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Filter.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Filter.swift @@ -10,6 +10,16 @@ //===----------------------------------------------------------------------===// extension PersistentDictionary { + /// Returns a new persistent dictionary containing the key-value pairs of this + /// dictionary that satisfy the given predicate. + /// + /// - Parameter isIncluded: A closure that takes a key-value pair as its + /// argument and returns a Boolean value indicating whether it should be + /// included in the returned dictionary. + /// + /// - Returns: A dictionary of the key-value pairs that `isIncluded` allows. + /// + /// - Complexity: O(`count`) @inlinable public func filter( _ isIncluded: (Element) throws -> Bool diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Fluent Operations.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Fluent Operations.swift new file mode 100644 index 00000000..57eaf17c --- /dev/null +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Fluent Operations.swift @@ -0,0 +1,61 @@ +//===----------------------------------------------------------------------===// +// +// 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 PersistentDictionary { + /// Return a new dictionary that has the specified key-value pair in addition + /// to all existing elements in this dictionary. + /// + /// If `self` already contains the given key, then the result replaces its + /// original value in `self` with `value`, without updating the existing key. + /// (In some cases, equal keys may be distinguishable from each other by + /// identity comparison or some other means.) + /// + /// - Parameters: + /// - value: The new value to add to the dictionary. + /// - key: The key to associate with `value`. If `key` already exists in + /// the dictionary, `value` replaces the existing associated value in the + /// result. If `key` isn't already a key of the dictionary, then the + /// `(key, value)` pair is added to the result. + /// + /// - Returns: A new dictionary with the update applied. + /// + /// - Complexity: This operation is expected to copy at most O(log(`count`)) + /// existing members and to perform at most O(1) hashing/comparison + /// operations on the `Element` type, as long as `Element` properly + /// implements hashing. + @inlinable + public func updatingValue(_ value: Value, forKey key: Key) -> Self { + var copy = self + copy.updateValue(value, forKey: key) + return copy + } + + /// Return a new dictionary that contains all key-value pairs that are in + /// this dictionary except for the pair that matches given `key`. + /// + /// If this dictionary does not contain a value for `key`, then this + /// method simply returns `self`. + /// + /// - Parameter key: The key to remove from the returned dictionary. + /// + /// - Returns: A new dictionary with all existing key-value pairs in `self` + /// except for the one that matches `key` (if any). + /// + /// - Complexity: This operation is expected to copy at most O(log(`count`)) + /// existing members and to perform at most O(1) hashing/comparison + /// operations on the `Element` type, as long as `Element` properly + /// implements hashing. + @inlinable + public func removingValue(forKey key: Key) -> Self { + guard let r = _root.removing(.top, key, _Hash(key)) else { return self } + return Self(_new: r.replacement.finalize(.top)) + } +} diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Hashable.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Hashable.swift index d545be32..6d230aaa 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Hashable.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Hashable.swift @@ -10,6 +10,10 @@ //===----------------------------------------------------------------------===// extension PersistentDictionary: Hashable where Value: 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) { var commutativeHash = 0 diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Initializers.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Initializers.swift index fb912d84..5818b2e2 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Initializers.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Initializers.swift @@ -10,31 +10,67 @@ //===----------------------------------------------------------------------===// extension PersistentDictionary { + /// Creates an empty dictionary. + /// + /// This initializer is equivalent to initializing with an empty dictionary + /// literal. + /// + /// - Complexity: O(1) @inlinable public init() { self.init(_new: ._emptyNode()) } + /// Makes a copy of an existing persistent dictionary. + /// + /// - Complexity: O(1) @inlinable public init(_ other: PersistentDictionary) { self = other } + /// Creates a new persistent dictionary that contains the same key-value + /// pairs as the given `Dictionary` instance, although not necessarily + /// in the same order. + /// + /// - Complexity: O(`other.count`) @inlinable public init(_ other: Dictionary) { - self.init(uniqueKeysWithValues: other) + self.init(_uniqueKeysWithValues: other) } - // FIXME: This is a non-standard addition + /// Creates a new persistent dictionary by associating the given persistent + /// set of keys with the values generated using the specified closure. + /// + /// - Complexity: O(`other.count`) @inlinable public init( keys: PersistentSet, valueGenerator valueTransform: (Key) throws -> Value ) rethrows { + // FIXME: This is a non-standard addition let root = try keys._root.mapValues { try valueTransform($0.key) } self.init(_new: root) } + /// Creates a new dictionary from the key-value pairs in the given sequence. + /// + /// You use this initializer to create a dictionary when you have a sequence + /// of key-value tuples with unique keys. Passing a sequence with duplicate + /// keys to this initializer results in a runtime error. If your + /// sequence might have duplicate keys, use the + /// `Dictionary(_:uniquingKeysWith:)` initializer instead. + /// + /// - Parameter keysAndValues: A sequence of key-value pairs to use for + /// the new dictionary. Every key in `keysAndValues` must be unique. + /// + /// - Returns: A new dictionary initialized with the elements of + /// `keysAndValues`. + /// + /// - Precondition: The sequence must not have duplicate keys. + /// + /// - Complexity: Expected O(*n*) on average, where *n* is the count if + /// key-value pairs, if `Key` properly implements hashing. @inlinable public init( uniqueKeysWithValues keysAndValues: S @@ -48,6 +84,24 @@ extension PersistentDictionary { _invariantCheck() } + /// Creates a new dictionary from the key-value pairs in the given sequence. + /// + /// You use this initializer to create a dictionary when you have a sequence + /// of key-value tuples with unique keys. Passing a sequence with duplicate + /// keys to this initializer results in a runtime error. If your + /// sequence might have duplicate keys, use the + /// `Dictionary(_:uniquingKeysWith:)` initializer instead. + /// + /// - Parameter keysAndValues: A sequence of key-value pairs to use for + /// the new dictionary. Every key in `keysAndValues` must be unique. + /// + /// - Returns: A new dictionary initialized with the elements of + /// `keysAndValues`. + /// + /// - Precondition: The sequence must not have duplicate keys. + /// + /// - Complexity: Expected O(*n*) on average, where *n* is the count if + /// key-value pairs, if `Key` properly implements hashing. @_disfavoredOverload // https://github.com/apple/swift-collections/issues/125 @inlinable public init( @@ -57,10 +111,58 @@ extension PersistentDictionary { self = keysAndValues as! Self return } - self.init( - uniqueKeysWithValues: keysAndValues.lazy.map { ($0.key, $0.value ) }) + if S.self == Dictionary.self { + self.init(keysAndValues as! Dictionary) + return + } + self.init(_uniqueKeysWithValues: keysAndValues) } + @inlinable + internal init( + _uniqueKeysWithValues keysAndValues: S + ) where S.Element == Element { + self.init() + for item in keysAndValues { + let hash = _Hash(item.key) + let r = _root.insert(.top, item, hash) + precondition(r.inserted, "Duplicate key: '\(item.key)'") + } + _invariantCheck() + } + + /// Creates a new dictionary from the key-value pairs in the given sequence, + /// using a combining closure to determine the value for any duplicate keys. + /// + /// You use this initializer to create a dictionary when you have a sequence + /// of key-value tuples that might have duplicate keys. As the dictionary is + /// built, the initializer calls the `combine` closure with the current and + /// new values for any duplicate keys. Pass a closure as `combine` that + /// returns the value to use in the resulting dictionary: The closure can + /// choose between the two values, combine them to produce a new value, or + /// even throw an error. + /// + /// let pairsWithDuplicateKeys = [("a", 1), ("b", 2), ("a", 3), ("b", 4)] + /// + /// let firstValues = PersistentDictionary( + /// pairsWithDuplicateKeys, + /// uniquingKeysWith: { (first, _) in first }) + /// // ["a": 1, "b": 2] + /// + /// let lastValues = PersistentDictionary( + /// pairsWithDuplicateKeys, + /// uniquingKeysWith: { (_, last) in last }) + /// // ["a": 3, "b": 4] + /// + /// - Parameters: + /// - keysAndValues: A sequence of key-value pairs to use for the new + /// dictionary. + /// - combine: A closure that is called with the values for any duplicate + /// keys that are encountered. The closure returns the desired value for + /// the final dictionary. + /// + /// - Complexity: Expected O(*n*) on average, where *n* is the count of + /// key-value pairs, if `Key` properly implements hashing. public init( _ keysAndValues: S, uniquingKeysWith combine: (Value, Value) throws -> Value ) rethrows where S.Element == (Key, Value) { @@ -68,6 +170,38 @@ extension PersistentDictionary { try self.merge(keysAndValues, uniquingKeysWith: combine) } + /// Creates a new dictionary from the key-value pairs in the given sequence, + /// using a combining closure to determine the value for any duplicate keys. + /// + /// You use this initializer to create a dictionary when you have a sequence + /// of key-value tuples that might have duplicate keys. As the dictionary is + /// built, the initializer calls the `combine` closure with the current and + /// new values for any duplicate keys. Pass a closure as `combine` that + /// returns the value to use in the resulting dictionary: The closure can + /// choose between the two values, combine them to produce a new value, or + /// even throw an error. + /// + /// let pairsWithDuplicateKeys = [("a", 1), ("b", 2), ("a", 3), ("b", 4)] + /// + /// let firstValues = PersistentDictionary( + /// pairsWithDuplicateKeys, + /// uniquingKeysWith: { (first, _) in first }) + /// // ["a": 1, "b": 2] + /// + /// let lastValues = PersistentDictionary( + /// pairsWithDuplicateKeys, + /// uniquingKeysWith: { (_, last) in last }) + /// // ["a": 3, "b": 4] + /// + /// - Parameters: + /// - keysAndValues: A sequence of key-value pairs to use for the new + /// dictionary. + /// - combine: A closure that is called with the values for any duplicate + /// keys that are encountered. The closure returns the desired value for + /// the final dictionary. + /// + /// - Complexity: Expected O(*n*) on average, where *n* is the count of + /// key-value pairs, if `Key` properly implements hashing. @_disfavoredOverload // https://github.com/apple/swift-collections/issues/125 public init( _ keysAndValues: S, uniquingKeysWith combine: (Value, Value) throws -> Value @@ -79,6 +213,31 @@ extension PersistentDictionary { } extension PersistentDictionary { + /// Creates a new dictionary whose keys are the groupings returned by the + /// given closure and whose values are arrays of the elements that returned + /// each key. + /// + /// The arrays in the "values" position of the new dictionary each contain at + /// least one element, with the elements in the same order as the source + /// sequence. + /// + /// The following example declares an array of names, and then creates a + /// dictionary from that array by grouping the names by first letter: + /// + /// let students = ["Kofi", "Abena", "Efua", "Kweku", "Akosua"] + /// let studentsByLetter = PersistentDictionary(grouping: students, by: { $0.first! }) + /// // ["K": ["Kofi", "Kweku"], "A": ["Abena", "Akosua"], "E": ["Efua"]] + /// + /// The new `studentsByLetter` dictionary has three entries, with students' + /// names grouped by the keys `"E"`, `"K"`, and `"A"`. + /// + /// - Parameters: + /// - values: A sequence of values to group into a dictionary. + /// - keyForValue: A closure that returns a key for each element in + /// `values`. + /// + /// - Complexity: Expected O(*n*) on average, where *n* is the count of + /// values, if `Key` properly implements hashing. @inlinable @inline(__always) public init( grouping values: S, @@ -89,6 +248,31 @@ extension PersistentDictionary { try self.init(_grouping: values, by: keyForValue) } + /// Creates a new dictionary whose keys are the groupings returned by the + /// given closure and whose values are arrays of the elements that returned + /// each key. + /// + /// The arrays in the "values" position of the new dictionary each contain at + /// least one element, with the elements in the same order as the source + /// sequence. + /// + /// The following example declares an array of names, and then creates a + /// dictionary from that array by grouping the names by first letter: + /// + /// let students = ["Kofi", "Abena", "Efua", "Kweku", "Akosua"] + /// let studentsByLetter = PersistentDictionary(grouping: students, by: { $0.first! }) + /// // ["K": ["Kofi", "Kweku"], "A": ["Abena", "Akosua"], "E": ["Efua"]] + /// + /// The new `studentsByLetter` dictionary has three entries, with students' + /// names grouped by the keys `"E"`, `"K"`, and `"A"`. + /// + /// - Parameters: + /// - values: A sequence of values to group into a dictionary. + /// - keyForValue: A closure that returns a key for each element in + /// `values`. + /// + /// - Complexity: Expected O(*n*) on average, where *n* is the count of + /// values, if `Key` properly implements hashing. @inlinable @inline(__always) public init( grouping values: S, diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Keys.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Keys.swift index f973ed5c..4832d8c3 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Keys.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Keys.swift @@ -12,7 +12,7 @@ import _CollectionsUtilities extension PersistentDictionary { - /// A view of a dictionary’s keys. + /// A view of a persistent dictionary’s keys, as a standalone collection. @frozen public struct Keys { @usableFromInline @@ -28,6 +28,8 @@ extension PersistentDictionary { } /// A collection containing just the keys of the dictionary. + /// + /// - Complexity: O(1) @inlinable public var keys: Keys { Keys(_base: self) @@ -59,8 +61,11 @@ extension PersistentDictionary.Keys: CustomDebugStringConvertible { } extension PersistentDictionary.Keys: Sequence { + /// The element type of the collection. public typealias Element = Key + /// The type that allows iteration over the elements of the keys view + /// of a persistent dictionary. @frozen public struct Iterator: IteratorProtocol { public typealias Element = Key @@ -91,6 +96,16 @@ extension PersistentDictionary.Keys: Sequence { _base._root.containsKey(.top, element, _Hash(element)) } + /// Returns a Boolean value that indicates whether the given key exists + /// in the dictionary. + /// + /// - Parameter element: A key to look for in the dictionary/ + /// + /// - Returns: `true` if `element` 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(_ element: Element) -> Bool { _base._root.containsKey(.top, element, _Hash(element)) @@ -163,3 +178,19 @@ extension PersistentDictionary.Keys: BidirectionalCollection { } } #endif + +extension PersistentDictionary.Keys { + public func intersection(_ other: Self) -> Self { + guard let r = _base._root.intersection(.top, other._base._root) else { + return self + } + return PersistentDictionary(_new: r).keys + } + + public func subtracting(_ other: Self) -> Self { + guard let r = _base._root.subtracting(.top, other._base._root) else { + return self + } + return PersistentDictionary(_new: r).keys + } +} diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+MapValues.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+MapValues.swift index ebd35e27..499286e5 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+MapValues.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+MapValues.swift @@ -10,6 +10,16 @@ //===----------------------------------------------------------------------===// extension PersistentDictionary { + /// Returns a new dictionary containing the keys of this dictionary with the + /// values transformed by the given closure. + /// + /// - Parameter transform: A closure that transforms a value. `transform` + /// accepts each value of the dictionary as its parameter and returns a + /// transformed value of the same or of a different type. + /// - Returns: A dictionary containing the keys and transformed values of + /// this dictionary. + /// + /// - Complexity: O(`count`) @inlinable public func mapValues( _ transform: (Value) throws -> T @@ -18,6 +28,32 @@ extension PersistentDictionary { return PersistentDictionary(_new: transformed) } + /// Returns a new dictionary containing only the key-value pairs that have + /// non-`nil` values as the result of transformation by the given closure. + /// + /// Use this method to receive a dictionary with non-optional values when + /// your transformation produces optional values. + /// + /// In this example, note the difference in the result of using `mapValues` + /// and `compactMapValues` with a transformation that returns an optional + /// `Int` value. + /// + /// let data: PersistentDictionary = ["a": "1", "b": "three", "c": "///4///"] + /// + /// let m: [String: Int?] = data.mapValues { str in Int(str) } + /// // ["a": Optional(1), "b": nil, "c": nil] + /// + /// let c: [String: Int] = data.compactMapValues { str in Int(str) } + /// // ["a": 1] + /// + /// - Parameter transform: A closure that transforms a value. `transform` + /// accepts each value of the dictionary as its parameter and returns an + /// optional transformed value of the same or of a different type. + /// + /// - Returns: A dictionary containing the keys and non-`nil` transformed + /// values of this dictionary. + /// + /// - Complexity: O(`count`) @inlinable public func compactMapValues( _ transform: (Value) throws -> T? diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Merge.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Merge.swift index 1954ba5b..520fa8bc 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Merge.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Merge.swift @@ -10,6 +10,33 @@ //===----------------------------------------------------------------------===// extension PersistentDictionary { + /// Merges the key-value pairs in the given sequence into the dictionary, + /// using a combining closure to determine the value for any duplicate keys. + /// + /// Use the `combine` closure to select a value to use in the updated + /// dictionary, or to combine existing and new values. As the key-value + /// pairs are merged with the dictionary, the `combine` closure is called + /// with the current and new values for any duplicate keys that are + /// encountered. + /// + /// This example shows how to choose the current or new values for any + /// duplicate keys: + /// + /// var dictionary: PersistentDictionary = ["a": 1, "b": 2] + /// + /// // Keeping existing value for key "a": + /// dictionary.merge(zip(["a", "c"], [3, 4])) { (current, _) in current } + /// // ["a": 1, "b": 2, "c": 4] (in some order) + /// + /// // Taking the new value for key "a": + /// dictionary.merge(zip(["a", "d"], [5, 6])) { (_, new) in new } + /// // ["a": 5, "b": 2, "c": 4, "d": 6] (in some order) + /// + /// - Parameters: + /// - keysAndValues: A sequence of key-value pairs. + /// - combine: A closure that takes the current and new values for any + /// duplicate keys. The closure returns the desired value for the final + /// dictionary. @inlinable public mutating func merge( _ keysAndValues: Self, @@ -19,6 +46,33 @@ extension PersistentDictionary { try _root.merge(.top, keysAndValues._root, combine) } + /// Merges the key-value pairs in the given sequence into the dictionary, + /// using a combining closure to determine the value for any duplicate keys. + /// + /// Use the `combine` closure to select a value to use in the updated + /// dictionary, or to combine existing and new values. As the key-value + /// pairs are merged with the dictionary, the `combine` closure is called + /// with the current and new values for any duplicate keys that are + /// encountered. + /// + /// This example shows how to choose the current or new values for any + /// duplicate keys: + /// + /// var dictionary: PersistentDictionary = ["a": 1, "b": 2] + /// + /// // Keeping existing value for key "a": + /// dictionary.merge(zip(["a", "c"], [3, 4])) { (current, _) in current } + /// // ["a": 1, "b": 2, "c": 4] (in some order) + /// + /// // Taking the new value for key "a": + /// dictionary.merge(zip(["a", "d"], [5, 6])) { (_, new) in new } + /// // ["a": 5, "b": 2, "c": 4, "d": 6] (in some order) + /// + /// - Parameters: + /// - keysAndValues: A sequence of key-value pairs. + /// - combine: A closure that takes the current and new values for any + /// duplicate keys. The closure returns the desired value for the final + /// dictionary. @inlinable public mutating func merge( _ keysAndValues: __owned S, @@ -35,6 +89,33 @@ extension PersistentDictionary { } } + /// Merges the key-value pairs in the given sequence into the dictionary, + /// using a combining closure to determine the value for any duplicate keys. + /// + /// Use the `combine` closure to select a value to use in the updated + /// dictionary, or to combine existing and new values. As the key-value + /// pairs are merged with the dictionary, the `combine` closure is called + /// with the current and new values for any duplicate keys that are + /// encountered. + /// + /// This example shows how to choose the current or new values for any + /// duplicate keys: + /// + /// var dictionary: PersistentDictionary = ["a": 1, "b": 2] + /// + /// // Keeping existing value for key "a": + /// dictionary.merge(zip(["a", "c"], [3, 4])) { (current, _) in current } + /// // ["a": 1, "b": 2, "c": 4] (in some order) + /// + /// // Taking the new value for key "a": + /// dictionary.merge(zip(["a", "d"], [5, 6])) { (_, new) in new } + /// // ["a": 5, "b": 2, "c": 4, "d": 6] (in some order) + /// + /// - Parameters: + /// - keysAndValues: A sequence of key-value pairs. + /// - combine: A closure that takes the current and new values for any + /// duplicate keys. The closure returns the desired value for the final + /// dictionary. @_disfavoredOverload // https://github.com/apple/swift-collections/issues/125 @inlinable public mutating func merge( @@ -46,6 +127,41 @@ extension PersistentDictionary { uniquingKeysWith: combine) } + /// Creates a dictionary by merging key-value pairs in a sequence into this + /// dictionary, using a combining closure to determine the value for + /// duplicate keys. + /// + /// Use the `combine` closure to select a value to use in the returned + /// dictionary, or to combine existing and new values. As the key-value + /// pairs are merged with the dictionary, the `combine` closure is called + /// with the current and new values for any duplicate keys that are + /// encountered. + /// + /// This example shows how to choose the current or new values for any + /// duplicate keys: + /// + /// let dictionary: OrderedDictionary = ["a": 1, "b": 2] + /// let newKeyValues = zip(["a", "b"], [3, 4]) + /// + /// let keepingCurrent = dictionary.merging(newKeyValues) { (current, _) in current } + /// // ["a": 1, "b": 2] + /// let replacingCurrent = dictionary.merging(newKeyValues) { (_, new) in new } + /// // ["a": 3, "b": 4] + /// + /// - Parameters: + /// - other: A sequence of key-value pairs. + /// - combine: A closure that takes the current and new values for any + /// duplicate keys. The closure returns the desired value for the final + /// dictionary. + /// + /// - Returns: A new dictionary with the combined keys and values of this + /// dictionary and `other`. The order of keys in the result dictionary + /// matches that of `self`, with additional key-value pairs (if any) + /// appended at the end in the order they appear in `other`. + /// + /// - Complexity: Expected to be O(`count` + *n*) on average, where *n* is the + /// number of elements in `keysAndValues`, if `Key` implements high-quality + /// hashing. @inlinable public func merging( _ other: Self, @@ -56,6 +172,41 @@ extension PersistentDictionary { return copy } + /// Creates a dictionary by merging key-value pairs in a sequence into this + /// dictionary, using a combining closure to determine the value for + /// duplicate keys. + /// + /// Use the `combine` closure to select a value to use in the returned + /// dictionary, or to combine existing and new values. As the key-value + /// pairs are merged with the dictionary, the `combine` closure is called + /// with the current and new values for any duplicate keys that are + /// encountered. + /// + /// This example shows how to choose the current or new values for any + /// duplicate keys: + /// + /// let dictionary: OrderedDictionary = ["a": 1, "b": 2] + /// let newKeyValues = zip(["a", "b"], [3, 4]) + /// + /// let keepingCurrent = dictionary.merging(newKeyValues) { (current, _) in current } + /// // ["a": 1, "b": 2] + /// let replacingCurrent = dictionary.merging(newKeyValues) { (_, new) in new } + /// // ["a": 3, "b": 4] + /// + /// - Parameters: + /// - other: A sequence of key-value pairs. + /// - combine: A closure that takes the current and new values for any + /// duplicate keys. The closure returns the desired value for the final + /// dictionary. + /// + /// - Returns: A new dictionary with the combined keys and values of this + /// dictionary and `other`. The order of keys in the result dictionary + /// matches that of `self`, with additional key-value pairs (if any) + /// appended at the end in the order they appear in `other`. + /// + /// - Complexity: Expected to be O(`count` + *n*) on average, where *n* is the + /// number of elements in `keysAndValues`, if `Key` implements high-quality + /// hashing. @inlinable public func merging( _ other: __owned S, @@ -67,6 +218,41 @@ extension PersistentDictionary { return copy } + /// Creates a dictionary by merging key-value pairs in a sequence into this + /// dictionary, using a combining closure to determine the value for + /// duplicate keys. + /// + /// Use the `combine` closure to select a value to use in the returned + /// dictionary, or to combine existing and new values. As the key-value + /// pairs are merged with the dictionary, the `combine` closure is called + /// with the current and new values for any duplicate keys that are + /// encountered. + /// + /// This example shows how to choose the current or new values for any + /// duplicate keys: + /// + /// let dictionary: OrderedDictionary = ["a": 1, "b": 2] + /// let newKeyValues = zip(["a", "b"], [3, 4]) + /// + /// let keepingCurrent = dictionary.merging(newKeyValues) { (current, _) in current } + /// // ["a": 1, "b": 2] + /// let replacingCurrent = dictionary.merging(newKeyValues) { (_, new) in new } + /// // ["a": 3, "b": 4] + /// + /// - Parameters: + /// - other: A sequence of key-value pairs. + /// - combine: A closure that takes the current and new values for any + /// duplicate keys. The closure returns the desired value for the final + /// dictionary. + /// + /// - Returns: A new dictionary with the combined keys and values of this + /// dictionary and `other`. The order of keys in the result dictionary + /// matches that of `self`, with additional key-value pairs (if any) + /// appended at the end in the order they appear in `other`. + /// + /// - Complexity: Expected to be O(`count` + *n*) on average, where *n* is the + /// number of elements in `keysAndValues`, if `Key` implements high-quality + /// hashing. @_disfavoredOverload // https://github.com/apple/swift-collections/issues/125 @inlinable public func merging( diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Sequence.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Sequence.swift index 5591067c..bf600835 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Sequence.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Sequence.swift @@ -10,8 +10,11 @@ //===----------------------------------------------------------------------===// extension PersistentDictionary: Sequence { + /// The element type of a dictionary: a tuple containing an individual + /// key-value pair. public typealias Element = (key: Key, value: Value) + /// The type that allows iteration over a persistent dictionary's elements. @frozen public struct Iterator { // Fixed-stack iterator for traversing a hash tree. @@ -30,11 +33,18 @@ extension PersistentDictionary: Sequence { } } + /// A value less than or equal to the number of elements in the sequence, + /// calculated nondestructively. + /// + /// - Complexity: O(1) @inlinable public var underestimatedCount: Int { _root.count } + /// Returns an iterator over the elements of this collection. + /// + /// - Complexity: O(1) @inlinable public __consuming func makeIterator() -> Iterator { return Iterator(_root: _root.raw) @@ -47,8 +57,16 @@ where Key: Sendable, Value: Sendable {} #endif extension PersistentDictionary.Iterator: IteratorProtocol { + /// The element type of a dictionary: a tuple containing an individual + /// key-value pair. public typealias Element = (key: Key, value: Value) + /// Advances to the next element and returns it, or `nil` if no next + /// element exists. + /// + /// Once `nil` has been returned, all subsequent calls return `nil`. + /// + /// - Complexity: O(1) @inlinable public mutating func next() -> Element? { guard let (node, slot) = _it.next() else { return nil } diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary.swift index d97a9ab0..e35735b0 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary.swift @@ -9,6 +9,58 @@ // //===----------------------------------------------------------------------===// +/// An unordered collection of unique keys and associated values, optimized for +/// mutating shared copies and comparing different snapshots of the same +/// collection. +/// +/// `PersistentDictionary` has the same functionality as a standard +/// `Dictionary`, and it largely implements the same APIs: both are hashed +/// collection types with convenient and efficient ways to look up the value +/// associated with a particular key, and both types are unordered, meaning that +/// neither type provides any guarantees about the ordering of their items. +/// +/// However, `PersistentDictionary` is optimizing specifically for use cases +/// that need to mutate shared copies or to compare a set value to one of its +/// older snapshots. +/// +/// The standard `Dictionary` stores its members in a single, flat hash table, +/// and it implements value semantics with all-or-nothing copy-on-write +/// behavior: every time a shared copy of a set is mutated, the mutation needs +/// to make a full copy of the set's storage. `PersistentDictionary` takes a +/// different approach: it organizes its members into a tree structure, the +/// nodes of which can be freely shared across collection values. When mutating +/// a shared copy of a set value, `PersistentSet` is able to simply link the +/// unchanged parts of the tree directly into the result, saving both time and +/// memory. +/// +/// This structural sharing also makes it more efficient to compare mutated +/// dictionaries values to earlier versions of themselves. When comparing or +/// combining dictionaries, parts that are shared across both inputs can +/// typically be handled in constant time, leading to a dramatic performance +/// boost when the two inputs are still largely unchanged: +/// +/// var d = PersistentDictionary( +/// uniqueKeysWithValues: (0 ..< 10_000).map { ($0, 2 * $0) }) +/// let copy = d +/// d[20_000] = 42 // Expected to be an O(log(n)) operation +/// let diff = d.keys.subtracting(copy.keys) // Also O(log(n))! +/// // `diff` now holds the single item 20_000. +/// +/// The tree structure also eliminates the need to reserve capacity in advance: +/// `PersistentDictionary` creates, destroys and resizes individual nodes as +/// needed, always consuming just enough memory to store its contents. As of +/// Swift 5.7, the standard collection types never shrink their storage, so +/// temporary storage spikes can linger as unused but still allocated memory +/// long after the collection has shrunk back to its usual size. +/// +/// Of course, switching to a tree structure comes with some trade offs. In +/// particular, inserting new items, removing existing ones, and iterating over +/// a `PersistentDictionary` is expected to be a constant factor slower than a +/// standard `Dictionary` -- allocating/deallocating nodes isn't free, and +/// navigating the tree structure requires more pointer dereferences than +/// accessing a flat hash table. However the algorithmic improvements above +/// usually more than make up for this, as long as the use case can make use of +/// them. @frozen // Not really -- this package is not at all ABI stable public struct PersistentDictionary { @usableFromInline @@ -58,10 +110,6 @@ extension PersistentDictionary { /// dictionary overwrites the existing value. If the dictionary doesn't /// contain the key, the key and value are added as a new key-value pair. /// - /// Inserting a new key-value pair into a dictionary invalidates all - /// previously returned indices to it. Updating the value of an existing key - /// does not invalidate any indices. - /// /// Here, the value for the key `"Coral"` is updated from `16` to `18` and a /// new key-value pair is added for the key `"Cerise"`. /// @@ -74,9 +122,7 @@ extension PersistentDictionary { /// // Prints "Optional(330)" /// /// If you assign `nil` as the value for the given key, the dictionary - /// removes that key and its associated value. Removing an existing key-value - /// pair in the dictionary invalidates all previously returned indices to it. - /// Removing a key that doesn't exist does not invalidate any indices. + /// removes that key and its associated value. /// /// In the following example, the key-value pair for the key `"Aquamarine"` /// is removed from the dictionary by assigning `nil` to the key-based @@ -86,19 +132,27 @@ extension PersistentDictionary { /// print(hues) /// // Prints "["Coral": 18, "Heliotrope": 296, "Cerise": 330]" /// + /// Updating the value of an existing key only modifies the value: it does not + /// change the key that is stored in the dictionary. (In some cases, equal + /// keys may be distinguishable from each other by identity comparison or + /// some other means.) + /// + /// Removing or updating an existing key-value pair or inserting a new + /// key-value pair invalidates all indices in the dictionary. Removing a + /// key that doesn't exist does not invalidate any indices. + /// /// - Parameter key: The key to find in the dictionary. /// /// - Returns: The value associated with `key` if `key` is in the dictionary; /// otherwise, `nil`. /// - /// - Complexity: Traversing the hash tree to find a key requires visiting - /// O(log(`count`)) nodes. Looking up and updating values in the - /// dictionary through this subscript has an expected complexity of O(1) - /// hashing/comparison operations on average, if `Key` implements - /// high-quality hashing. + /// - Complexity: Looking up the value for a key is expected to traverse + /// O(log(`count`)) tree nodes and to do at most O(1) hashing/comparison + /// operations on the `Element` type, as long as `Element` properly + /// implements hashing. /// - /// When used to mutate dictionary values with shared storage, this - /// operation is expected to copy at most O(log(`count`)) items. + /// Updating the dictionary through this subscript is expected to copy at + /// most O(log(`count`)) existing members. @inlinable public subscript(key: Key) -> Value? { get { @@ -164,9 +218,12 @@ extension PersistentDictionary { /// specified default value (`0`) is returned from the subscript, /// incremented, and then added to the dictionary under that key. /// - /// Inserting a new key-value pair invalidates all existing indices in the - /// dictionary. Updating the value of an existing key does not invalidate - /// any indices. + /// Updating the value of an existing key only modifies the value: it does not + /// change the key that is stored in the dictionary. (In some cases, equal + /// keys may be distinguishable from each other by identity comparison or + /// some other means.) + /// + /// Calling this method invalidates all existing indices in the dictionary. /// /// - Note: Do not use this subscript to modify dictionary values if the /// dictionary's `Value` type is a class. In that case, the default value @@ -182,14 +239,12 @@ extension PersistentDictionary { /// - Returns: The value associated with `key` in the dictionary; otherwise, /// `defaultValue`. /// - /// - Complexity: Traversing the hash tree to find a key requires visiting - /// O(log(`count`)) nodes. Looking up and updating values in the - /// dictionary through this subscript has an expected complexity of O(1) - /// hashing/comparison operations on average, if `Key` implements - /// high-quality hashing. + /// - Complexity: Looking up the value for a key is expected to do at most + /// O(1) hashing/comparison operations on the `Element` type, as long as + /// `Element` properly implements hashing. /// - /// When used to mutate dictionary values with shared storage, this - /// operation is expected to copy at most O(log(`count`)) items. + /// Updating the dictionary through this subscript is expected to copy at + /// most O(log(`count`)) existing members. @inlinable public subscript( key: Key, @@ -214,13 +269,20 @@ extension PersistentDictionary { } } - // FIXME: New addition; needs discussion - @inlinable - public func contains(_ key: Key) -> Bool { - _root.containsKey(.top, key, _Hash(key)) - } - /// Returns the index for the given key. + /// + /// If the given key is found in the dictionary, this method returns an index + /// into the dictionary that corresponds with the key-value pair. If the + /// key is not found, then this method returns `nil`. + /// + /// - Parameter key: The key to find in the dictionary. + /// + /// - Returns: The index for `key` and its associated value if `key` is in + /// the dictionary; otherwise, `nil`. + /// + /// - 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 index(forKey key: Key) -> Index? { guard let path = _root.path(to: key, _Hash(key)) @@ -256,9 +318,12 @@ extension PersistentDictionary { /// } /// // Prints "No value was found in the dictionary for that key." /// - /// Inserting a new key-value pair invalidates all existing indices in the - /// dictionary. Updating the value of an existing key does not invalidate - /// any indices. + /// Updating the value of an existing key only modifies the value: it does not + /// change the key that is stored in the dictionary. (In some cases, equal + /// keys may be distinguishable from each other by identity comparison or + /// some other means.) + /// + /// Calling this method invalidates all existing indices in the dictionary. /// /// - Parameters: /// - value: The new value to add to the dictionary. @@ -270,13 +335,10 @@ extension PersistentDictionary { /// - Returns: The value that was replaced, or `nil` if a new key-value pair /// was added. /// - /// - Complexity: Traversing the hash tree to find a key requires visiting - /// O(log(`count`)) nodes. Updating values in the has an expected - /// complexity of O(1) hashing/comparison operations on average, if - /// `Key` implements high-quality hashing. - /// - /// When used to mutate dictionary values with shared storage, this - /// operation is expected to copy at most O(log(`count`)) items. + /// - Complexity: This operation is expected to copy at most O(log(`count`)) + /// existing members and to perform at most O(1) hashing/comparison + /// operations on the `Element` type, as long as `Element` properly + /// implements hashing. @inlinable @discardableResult public mutating func updateValue( @@ -312,15 +374,48 @@ extension PersistentDictionary { return false } - // fluid/immutable API - @inlinable - public func updatingValue(_ value: Value, forKey key: Key) -> Self { - var copy = self - copy.updateValue(value, forKey: key) - return copy - } - - // FIXME: New addition; needs discussion + /// Calls `body` to directly update the current value of `key` in the + /// dictionary. + /// + /// You can use this method to perform in-place operations on values in the + /// dictionary, whether or not `Value` has value semantics. The following + /// example uses this method while counting the occurrences of each letter + /// in a string: + /// + /// let message = "Hello, Elle!" + /// var letterCounts: PersistentDictionary = [:] + /// for letter in message { + /// letterCounts.updateValue(forKey: letter) { count in + /// if count == nil { + /// count = 1 + /// } else + /// count! += 1 + /// } + /// } + /// } + /// // letterCounts == ["H": 1, "e": 2, "l": 4, "o": 1, ...] + /// + /// Updating the value of an existing key only modifies the value: it does not + /// change the key that is stored in the dictionary. (In some cases, equal + /// keys may be distinguishable from each other by identity comparison or + /// some other means.) + /// + /// Removing or updating an existing key-value pair or inserting a new + /// key-value pair invalidates all indices in the dictionary. Removing a + /// key that doesn't exist does not invalidate any indices. + /// + /// - Parameters: + /// - key: The key whose value to look up. + /// - body: A function that performs an in-place mutation on the dictionary + /// value. If `key` exists in the dictionary, then `body` is called with + /// its current value; otherwise `body` is passed `nil`. + /// + /// - Returns: The return value of `body`. + /// + /// - Complexity: In addition to calling `body`, this operation is expected + /// to copy at most O(log(`count`)) existing members and to perform at + /// most O(1) hashing/comparison operations on the `Element` type, as long + /// as `Element` properly implements hashing. @inlinable @inline(__always) public mutating func updateValue( forKey key: Key, @@ -329,6 +424,45 @@ extension PersistentDictionary { try body(&self[key]) } + /// Ensures that the specified key exists in the dictionary (by inserting one + /// with the supplied default value if necessary), then calls `body` to update + /// it in place. + /// + /// You can use this method to perform in-place operations on values in the + /// dictionary, whether or not `Value` has value semantics. The following + /// example uses this method while counting the occurrences of each letter + /// in a string: + /// + /// let message = "Hello, Elle!" + /// var letterCounts: PersistentDictionary = [:] + /// for letter in message { + /// letterCounts.updateValue(forKey: letter, default: 0) { count in + /// count += 1 + /// } + /// } + /// // letterCounts == ["H": 1, "e": 2, "l": 4, "o": 1, ...] + /// + /// Updating the value of an existing key only modifies the value: it does not + /// change the key that is stored in the dictionary. (In some cases, equal + /// keys may be distinguishable from each other by identity comparison or + /// some other means.) + /// + /// Calling this method invalidates all existing indices in the dictionary. + /// + /// - Parameters: + /// - key: The key to look up (or insert). If `key` does not already exist + /// in the dictionary, it is inserted with the supplied default value. + /// - defaultValue: The default value to insert if `key` doesn't exist in + /// the dictionary. + /// - body: A function that performs an in-place mutation on the dictionary + /// value. + /// + /// - Returns: The return value of `body`. + /// + /// - Complexity: In addition to calling `body`, this operation is expected + /// to copy at most O(log(`count`)) existing members and to perform at + /// most O(1) hashing/comparison operations on the `Element` type, as long + /// as `Element` properly implements hashing. @inlinable public mutating func updateValue( forKey key: Key, @@ -349,7 +483,7 @@ extension PersistentDictionary { /// If the key is found in the dictionary, this method returns the key's /// associated value, and invalidates all previously returned indices. /// - /// var hues: OrderedDictionary = [ + /// var hues: PersistentDictionary = [ /// "Heliotrope": 296, /// "Coral": 16, /// "Aquamarine": 156] @@ -370,16 +504,14 @@ extension PersistentDictionary { /// // Prints "No value found for that key."" /// /// - Parameter key: The key to remove along with its associated value. + /// /// - Returns: The value that was removed, or `nil` if the key was not /// present in the dictionary. /// - /// - Complexity: Traversing the hash tree to find a key requires visiting - /// O(log(`count`)) nodes. Updating values in the has an expected - /// complexity of O(1) hashing/comparison operations on average, if - /// `Key` implements high-quality hashing. - /// - /// When used to mutate dictionary values with shared storage, this - /// operation is expected to copy at most O(log(`count`)) items. + /// - Complexity: In addition to calling `body`, this operation is expected + /// to copy at most O(log(`count`)) existing members and to perform at + /// most O(1) hashing/comparison operations on the `Element` type, as long + /// as `Element` properly implements hashing. @inlinable @discardableResult public mutating func removeValue(forKey key: Key) -> Value? { @@ -390,13 +522,19 @@ extension PersistentDictionary { return r.removed.value } - // fluid/immutable API - @inlinable - public func removingValue(forKey key: Key) -> Self { - guard let r = _root.removing(.top, key, _Hash(key)) else { return self } - return Self(_new: r.replacement.finalize(.top)) - } - + /// Removes and returns the key-value pair at the specified index. + /// + /// Calling this method invalidates all existing indices in the dictionary. + /// + /// - Parameter index: The position of the element to remove. `index` must be + /// a valid index of the dictionary that is not equal to `endIndex`. + /// + /// - Returns: The removed key-value pair. + /// + /// - Complexity: This operation is expected to copy at most O(log(`count`)) + /// existing members and to perform at most O(1) hashing/comparison + /// operations on the `Element` type, as long as `Element` properly + /// implements hashing. @inlinable public mutating func remove(at index: Index) -> Element { precondition(_isValid(index), "Invalid index") diff --git a/Tests/PersistentCollectionsTests/PersistentDictionary Smoke Tests.swift b/Tests/PersistentCollectionsTests/PersistentDictionary Smoke Tests.swift index 0cd0c9b3..e21bcb54 100644 --- a/Tests/PersistentCollectionsTests/PersistentDictionary Smoke Tests.swift +++ b/Tests/PersistentCollectionsTests/PersistentDictionary Smoke Tests.swift @@ -12,6 +12,12 @@ import _CollectionsTestSupport import PersistentCollections +extension PersistentDictionary { + fileprivate func contains(_ key: Key) -> Bool { + self[key] != nil + } +} + final class PersistentDictionarySmokeTests: CollectionTestCase { func testDummy() { let map = PersistentDictionary( From 2dae70dba7fc4c5b01e8e7251f827233cf5413fc Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 26 Oct 2022 18:09:09 -0700 Subject: [PATCH 27/39] [OrderedSet, BitSet] Fix display style of custom mirror --- Sources/BitCollections/BitSet/BitSet+CustomReflectable.swift | 2 +- .../OrderedSet/OrderedSet+CustomReflectable.swift | 2 +- Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Sources/BitCollections/BitSet/BitSet+CustomReflectable.swift b/Sources/BitCollections/BitSet/BitSet+CustomReflectable.swift index 2ed48046..56317f2e 100644 --- a/Sources/BitCollections/BitSet/BitSet+CustomReflectable.swift +++ b/Sources/BitCollections/BitSet/BitSet+CustomReflectable.swift @@ -12,6 +12,6 @@ extension BitSet: CustomReflectable { /// The custom mirror for this instance. public var customMirror: Mirror { - Mirror(self, unlabeledChildren: self, displayStyle: .collection) + Mirror(self, unlabeledChildren: self, displayStyle: .set) } } diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+CustomReflectable.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+CustomReflectable.swift index 8b054628..e5fa6c2e 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+CustomReflectable.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+CustomReflectable.swift @@ -12,6 +12,6 @@ extension OrderedSet: CustomReflectable { /// The custom mirror for this instance. public var customMirror: Mirror { - Mirror(self, unlabeledChildren: _elements, displayStyle: .collection) + Mirror(self, unlabeledChildren: _elements, displayStyle: .set) } } diff --git a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift index 2c2e9004..e44f2918 100644 --- a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift +++ b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift @@ -168,7 +168,7 @@ class OrderedSetTests: CollectionTestCase { do { let set: OrderedSet = [1, 2, 3] let mirror = Mirror(reflecting: set) - expectEqual(mirror.displayStyle, .collection) + expectEqual(mirror.displayStyle, .set) expectNil(mirror.superclassMirror) expectTrue(mirror.children.compactMap { $0.label }.isEmpty) // No label expectEqualElements(mirror.children.map { $0.value as? Int }, set.map { $0 }) From 207029a613dca008e708370c09fc69010cf6a11d Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Sat, 22 Oct 2022 17:28:06 -0700 Subject: [PATCH 28/39] [OrderedSet] Improve Sequence initializer --- .../OrderedSet/OrderedSet+Initializers.swift | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Initializers.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Initializers.swift index e9b68df6..ab24de09 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Initializers.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Initializers.swift @@ -9,6 +9,8 @@ // //===----------------------------------------------------------------------===// +import _CollectionsUtilities + extension OrderedSet { /// Creates a set with the contents of the given sequence, which /// must not include duplicate elements. @@ -63,12 +65,12 @@ extension OrderedSet { return } // Fast paths for when we know elements are all unique - if S.self == Set.self || S.self == SubSequence.self { + if elements is _UniqueCollection { self.init(uncheckedUniqueElements: elements) return } - self.init() + self.init(minimumCapacity: elements.underestimatedCount) append(contentsOf: elements) } From 68bc6567be4c1ae96cfea1217b9e5cee63421c6a Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Sat, 22 Oct 2022 11:39:52 -0700 Subject: [PATCH 29/39] [Xcode] Disable implicit dependencies --- .../xcshareddata/xcschemes/BitCollections.xcscheme | 2 +- .../xcshareddata/xcschemes/Collections.xcscheme | 2 +- .../xcshareddata/xcschemes/CollectionsBenchmark.xcscheme | 2 +- .../xcshareddata/xcschemes/CollectionsTestSupport.xcscheme | 2 +- .../xcshareddata/xcschemes/DequeModule.xcscheme | 2 +- .../xcshareddata/xcschemes/HeapModule.xcscheme | 2 +- .../xcshareddata/xcschemes/OrderedCollections.xcscheme | 2 +- .../xcshareddata/xcschemes/PersistentCollections.xcscheme | 2 +- .../xcshareddata/xcschemes/benchmark.xcscheme | 2 +- .../xcshareddata/xcschemes/memory-benchmark.xcscheme | 2 +- .../xcshareddata/xcschemes/swift-collections-Package.xcscheme | 2 +- 11 files changed, 11 insertions(+), 11 deletions(-) diff --git a/Utils/swift-collections.xcworkspace/xcshareddata/xcschemes/BitCollections.xcscheme b/Utils/swift-collections.xcworkspace/xcshareddata/xcschemes/BitCollections.xcscheme index 22d4e3c3..af14ac47 100644 --- a/Utils/swift-collections.xcworkspace/xcshareddata/xcschemes/BitCollections.xcscheme +++ b/Utils/swift-collections.xcworkspace/xcshareddata/xcschemes/BitCollections.xcscheme @@ -4,7 +4,7 @@ version = "1.7"> + buildImplicitDependencies = "NO"> + buildImplicitDependencies = "NO"> + buildImplicitDependencies = "NO"> + buildImplicitDependencies = "NO"> + buildImplicitDependencies = "NO"> + buildImplicitDependencies = "NO"> + buildImplicitDependencies = "NO"> + buildImplicitDependencies = "NO"> + buildImplicitDependencies = "NO"> + buildImplicitDependencies = "NO"> + buildImplicitDependencies = "NO"> Date: Fri, 28 Oct 2022 10:40:42 -0700 Subject: [PATCH 30/39] [BitSet] Adjust test for updated mirror display style --- Tests/BitCollectionsTests/BitSetTests.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Tests/BitCollectionsTests/BitSetTests.swift b/Tests/BitCollectionsTests/BitSetTests.swift index bd204cc9..b2ac7632 100644 --- a/Tests/BitCollectionsTests/BitSetTests.swift +++ b/Tests/BitCollectionsTests/BitSetTests.swift @@ -1526,12 +1526,12 @@ final class BitSetTest: CollectionTestCase { } expectEqual(check(BitSet()), """ - - 0 elements + - 0 members """) expectEqual(check([1, 2, 3] as BitSet), """ - ▿ 3 elements + ▿ 3 members - 1 - 2 - 3 From 98d62d236bef8c30af5b7015ccbb7db66f43399e Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 28 Oct 2022 12:19:08 -0700 Subject: [PATCH 31/39] [PersistentDictionary] More keys diffing APIs; additional documentation & testing --- .../PersistentDictionary+Keys.swift | 95 ++++++++++++++++++- .../PersistentDictionary+Values.swift | 40 ++------ ...ersistentSet+SetAlgebra intersection.swift | 4 +- ...PersistentSet+SetAlgebra subtracting.swift | 4 +- .../PersistentDictionary.Keys Tests.swift | 62 ++++++++++++ .../Utilities.swift | 12 +-- 6 files changed, 174 insertions(+), 43 deletions(-) diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Keys.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Keys.swift index 4832d8c3..7ad05ae6 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Keys.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Keys.swift @@ -167,6 +167,9 @@ extension PersistentDictionary.Keys: Collection { #if false extension PersistentDictionary.Keys: BidirectionalCollection { + // Note: Let's not do this. `BidirectionalCollection` would imply that + // the ordering of elements would be meaningful, which isn't true for + // `PersistentDictionary.Keys`. @inlinable public func formIndex(before i: inout Index) { _base.formIndex(before: &i) @@ -180,17 +183,105 @@ extension PersistentDictionary.Keys: BidirectionalCollection { #endif extension PersistentDictionary.Keys { - public func intersection(_ other: Self) -> Self { + /// Returns a new keys view with the elements that are common to both this + /// view and the provided other one. + /// + /// var a: PersistentDictionary = ["a": 1, "b": 2, "c": 3] + /// let b: PersistentDictionary = ["b": 4, "d": 5, "e": 6] + /// let c = a.keys.intersection(b.keys) + /// // `c` is `["b"]` + /// + /// The result will only contain instances that were originally in `self`. + /// (This matters if equal members can be distinguished by comparing their + /// identities, or by some other means.) + /// + /// - Parameter other: The keys view of a persistent dictionary with the same + /// `Key` type. + /// + /// - Complexity: Expected complexity is O(`self.count`) in + /// the worst case, if `Element` properly implements hashing. + /// However, the implementation is careful to make the best use of + /// hash tree structure to minimize work when possible, e.g. by linking + /// parts of the input trees directly into the result. + public func intersection( + _ other: PersistentDictionary.Keys + ) -> Self { guard let r = _base._root.intersection(.top, other._base._root) else { return self } return PersistentDictionary(_new: r).keys } - public func subtracting(_ other: Self) -> Self { + /// Returns a new keys view with the elements that are common to both this + /// view and the provided persistent set. + /// + /// var a: PersistentDictionary = ["a": 1, "b": 2, "c": 3] + /// let b: PersistentSet = ["b", "d", "e"] + /// let c = a.keys.intersection(b) + /// // `c` is `["b"]` + /// + /// The result will only contain instances that were originally in `self`. + /// (This matters if equal members can be distinguished by comparing their + /// identities, or by some other means.) + /// + /// - Parameter other: A persistent set whose `Element` type is `Key`. + /// + /// - Complexity: Expected complexity is O(`self.count`) in + /// the worst case, if `Element` properly implements hashing. + /// However, the implementation is careful to make the best use of + /// hash tree structure to minimize work when possible, e.g. by linking + /// parts of the input trees directly into the result. + public func intersection(_ other: PersistentSet) -> Self { + guard let r = _base._root.intersection(.top, other._root) else { + return self + } + return PersistentDictionary(_new: r).keys + } + + /// Returns a new keys view containing the elements of `self` that do not + /// occur in the provided other one. + /// + /// var a: PersistentDictionary = ["a": 1, "b": 2, "c": 3] + /// let b: PersistentDictionary = ["b": 4, "d": 5, "e": 6] + /// let c = a.keys.subtracting(b.keys) + /// // `c` is some permutation of `["a", "c"]` + /// + /// - Parameter other: The keys view of a persistent dictionary with the same + /// `Key` type. + /// + /// - Complexity: Expected complexity is O(`self.count`) in + /// the worst case, if `Element` properly implements hashing. + /// However, the implementation is careful to make the best use of + /// hash tree structure to minimize work when possible, e.g. by linking + /// parts of the input trees directly into the result. + public func subtracting( + _ other: PersistentDictionary.Keys + ) -> Self { guard let r = _base._root.subtracting(.top, other._base._root) else { return self } return PersistentDictionary(_new: r).keys } + + /// Returns a new keys view containing the elements of `self` that do not + /// occur in the provided persistent set. + /// + /// var a: PersistentDictionary = ["a": 1, "b": 2, "c": 3] + /// let b: PersistentSet = ["b", "d", "e"] + /// let c = a.keys.subtracting(b) + /// // `c` is some permutation of `["a", "c"]` + /// + /// - Parameter other: A persistent set whose `Element` type is `Key`. + /// + /// - Complexity: Expected complexity is O(`self.count`) in + /// the worst case, if `Element` properly implements hashing. + /// However, the implementation is careful to make the best use of + /// hash tree structure to minimize work when possible, e.g. by linking + /// parts of the input trees directly into the result. + public func subtracting(_ other: PersistentSet) -> Self { + guard let r = _base._root.subtracting(.top, other._root) else { + return self + } + return PersistentDictionary(_new: r).keys + } } diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Values.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Values.swift index cf8b48a2..1f593755 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Values.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Values.swift @@ -33,20 +33,11 @@ extension PersistentDictionary { /// A collection containing just the values of the dictionary. @inlinable public var values: Values { + // Note: this property is kept read only for now until we decide whether + // it's worth providing setters without a `MutableCollection` conformance. get { Values(_base: self) } - set { // FIXME: Consider removing - self = newValue._base - } - _modify { // FIXME: Consider removing - var values = Values(_base: self) - self = Self() - defer { - self = values._base - } - yield &values - } } } @@ -123,29 +114,13 @@ extension PersistentDictionary.Values: Collection { @inlinable public subscript(index: Index) -> Element { + // The subscript is kept read only for now until we decide whether it's + // worth providing setters without a `MutableCollection` conformance. + // (With the current index implementation, mutating values must invalidate + // indices.) get { _base[index].value } - set { // FIXME: Consider removing - precondition(_base._isValid(index), "Invalid index") - precondition(index._path.isOnItem, "Cannot set value at end index") - let (leaf, slot) = _base._root.ensureUnique(level: .top, at: index._path) - _UnsafeHandle.update(leaf) { $0[item: slot].value = newValue } - _base._invalidateIndices() - } - _modify { // FIXME: Consider removing - precondition(_base._isValid(index), "Invalid index") - precondition(index._path.isOnItem, "Cannot set value at end index") - let (leaf, slot) = _base._root.ensureUnique(level: .top, at: index._path) - var item = _UnsafeHandle.update(leaf) { $0.itemPtr(at: slot).move() } - defer { - _Node.UnsafeHandle.update(leaf) { - $0.itemPtr(at: slot).initialize(to: item) - } - _base._invalidateIndices() - } - yield &item.value - } } @inlinable @@ -178,6 +153,9 @@ extension PersistentDictionary.Values: Collection { #if false extension PersistentDictionary.Values: BidirectionalCollection { + // Note: Let's not do this. `BidirectionalCollection` would imply that + // the ordering of elements would be meaningful, which isn't true for + // `PersistentDictionary.Values`. @inlinable public func formIndex(before i: inout Index) { _base.formIndex(before: &i) diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra intersection.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra intersection.swift index 3d6bab5a..bce0e00f 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra intersection.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra intersection.swift @@ -24,7 +24,7 @@ extension PersistentSet { /// /// - Parameter other: An arbitrary set of elements. /// - /// - Complexity: Expected complexity is O(`self.count` + `other.count`) in + /// - Complexity: Expected complexity is O(`self.count`) in /// the worst case, if `Element` properly implements hashing. /// However, the implementation is careful to make the best use of /// hash tree structure to minimize work when possible, e.g. by linking @@ -48,7 +48,7 @@ extension PersistentSet { /// /// - Parameter other: The keys view of a persistent dictionary. /// - /// - Complexity: Expected complexity is O(`self.count` + `other.count`) in + /// - Complexity: Expected complexity is O(`self.count`) in /// the worst case, if `Element` properly implements hashing. /// However, the implementation is careful to make the best use of /// hash tree structure to minimize work when possible, e.g. by linking diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra subtracting.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra subtracting.swift index 3d1ef5ff..bbdb76be 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra subtracting.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra subtracting.swift @@ -20,7 +20,7 @@ extension PersistentSet { /// /// - Parameter other: An arbitrary set of elements. /// - /// - Complexity: Expected complexity is O(`self.count` + `other.count`) in + /// - Complexity: Expected complexity is O(`self.count`) in /// the worst case, if `Element` properly implements hashing. /// However, the implementation is careful to make the best use of /// hash tree structure to minimize work when possible, e.g. by linking @@ -40,7 +40,7 @@ extension PersistentSet { /// /// - Parameter other: The keys view of a persistent dictionary. /// - /// - Complexity: Expected complexity is O(`self.count` + `other.count`) in + /// - Complexity: Expected complexity is O(`self.count`) in /// the worst case, if `Element` properly implements hashing. /// However, the implementation is careful to make the best use of /// hash tree structure to minimize work when possible, e.g. by linking diff --git a/Tests/PersistentCollectionsTests/PersistentDictionary.Keys Tests.swift b/Tests/PersistentCollectionsTests/PersistentDictionary.Keys Tests.swift index 6fc4784e..39e4f28f 100644 --- a/Tests/PersistentCollectionsTests/PersistentDictionary.Keys Tests.swift +++ b/Tests/PersistentCollectionsTests/PersistentDictionary.Keys Tests.swift @@ -44,4 +44,66 @@ class PersistentDictionaryKeysTests: CollectionTestCase { "PersistentDictionary.Keys([\"b\", \"a\"])") } } + + func test_contains() { + withEverySubset("a", of: testItems) { a in + let x = PersistentDictionary( + uniqueKeysWithValues: a.lazy.map { ($0, 2 * $0.identity) }) + let u = Set(a) + + func checkSequence( + _ items: S, + _ value: S.Element + ) -> Bool + where S.Element: Equatable { + items.contains(value) + } + + withEvery("key", in: testItems) { key in + expectEqual(x.keys.contains(key), u.contains(key)) + expectEqual(checkSequence(x.keys, key), u.contains(key)) + } + } + } + + func test_intersection_exhaustive() { + withEverySubset("a", of: testItems) { a in + let x = PersistentDictionary( + uniqueKeysWithValues: a.lazy.map { ($0, 2 * $0.identity) }) + let u = Set(a) + expectEqualSets(x.keys.intersection(x.keys), u) + withEverySubset("b", of: testItems) { b in + let y = PersistentDictionary( + uniqueKeysWithValues: b.lazy.map { ($0, -$0.identity - 1) }) + let v = Set(b) + let z = PersistentSet(b) + + let reference = u.intersection(v) + + expectEqualSets(x.keys.intersection(y.keys), reference) + expectEqualSets(x.keys.intersection(z), reference) + } + } + } + + func test_subtracting_exhaustive() { + withEverySubset("a", of: testItems) { a in + let x = PersistentDictionary( + uniqueKeysWithValues: a.lazy.map { ($0, 2 * $0.identity) }) + let u = Set(a) + expectEqualSets(x.keys.subtracting(x.keys), []) + withEverySubset("b", of: testItems) { b in + let y = PersistentDictionary( + uniqueKeysWithValues: b.lazy.map { ($0, -$0.identity - 1) }) + let v = Set(b) + let z = PersistentSet(b) + + let reference = u.subtracting(v) + + expectEqualSets(x.keys.subtracting(y.keys), reference) + expectEqualSets(x.keys.subtracting(z), reference) + } + } + } + } diff --git a/Tests/PersistentCollectionsTests/Utilities.swift b/Tests/PersistentCollectionsTests/Utilities.swift index e5354529..8184f643 100644 --- a/Tests/PersistentCollectionsTests/Utilities.swift +++ b/Tests/PersistentCollectionsTests/Utilities.swift @@ -145,18 +145,18 @@ func expectEqualSets( file: file, line: line) } -func expectEqualSets( - _ set: PersistentSet, - _ ref: Set, +func expectEqualSets( + _ set: C, + _ ref: Set, _ message: @autoclosure () -> String = "", trapping: Bool = false, file: StaticString = #file, line: UInt = #line ) { var ref = ref - var seen: Set = [] - var extras: [Element] = [] - var dupes: [Element: Int] = [:] + var seen: Set = [] + var extras: [C.Element] = [] + var dupes: [C.Element: Int] = [:] for item in set { if !seen.insert(item).inserted { dupes[item, default: 1] += 1 From 86bce288358754a07d87dd67a77addf095aaa03d Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 27 Oct 2022 18:19:10 -0700 Subject: [PATCH 32/39] [docs] Start working on DocC support --- .../BitCollections.docc/BitCollections.md | 20 +++ .../Extensions/BitSet.Counted.md | 84 +++++++++++ .../BitCollections.docc/Extensions/BitSet.md | 88 +++++++++++ .../Collections.docc/Collections.md | 38 +++++ .../DequeModule.docc/DequeModule.md | 8 + .../HeapModule/HeapModule.docc/HeapModule.md | 13 ++ .../Extensions/OrderedSet.UnorderedView.md | 64 ++++++++ .../Extensions/OrderedSet.md | 142 ++++++++++++++++++ .../OrderedCollections.md | 20 +++ 9 files changed, 477 insertions(+) create mode 100644 Sources/BitCollections/BitCollections.docc/BitCollections.md create mode 100644 Sources/BitCollections/BitCollections.docc/Extensions/BitSet.Counted.md create mode 100644 Sources/BitCollections/BitCollections.docc/Extensions/BitSet.md create mode 100644 Sources/Collections/Collections.docc/Collections.md create mode 100644 Sources/DequeModule/DequeModule.docc/DequeModule.md create mode 100644 Sources/HeapModule/HeapModule.docc/HeapModule.md create mode 100644 Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.UnorderedView.md create mode 100644 Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.md create mode 100644 Sources/OrderedCollections/OrderedCollections.docc/OrderedCollections.md diff --git a/Sources/BitCollections/BitCollections.docc/BitCollections.md b/Sources/BitCollections/BitCollections.docc/BitCollections.md new file mode 100644 index 00000000..9ed49e20 --- /dev/null +++ b/Sources/BitCollections/BitCollections.docc/BitCollections.md @@ -0,0 +1,20 @@ +# ``BitCollections`` + +**Swift Collections** is an open-source package of data structure implementations for the Swift programming language. + +## Overview + + + +#### Additional Resources + +- [`Swift Collections` on GitHub](https://github.com/apple/swift-collections/) +- [`Swift Collections` on the Swift Forums](https://forums.swift.org/c/related-projects/collections/72) + + +## Topics + +### Structures + +- ``BitSet`` +- ``BitArray`` diff --git a/Sources/BitCollections/BitCollections.docc/Extensions/BitSet.Counted.md b/Sources/BitCollections/BitCollections.docc/Extensions/BitSet.Counted.md new file mode 100644 index 00000000..fbec5925 --- /dev/null +++ b/Sources/BitCollections/BitCollections.docc/Extensions/BitSet.Counted.md @@ -0,0 +1,84 @@ +# ``BitCollections/BitSet/Counted-swift.struct`` + +Summary + +## Overview + +Text + +## Topics + +### Binary Set Operations + +- ``intersection(_:)-1wfb5`` +- ``intersection(_:)-4evdp`` +- ``intersection(_:)-9rtcc`` +- ``intersection(_:)-13us`` + +- ``union(_:)-2okwt`` +- ``union(_:)-pwqf`` +- ``union(_:)-18u31`` +- ``union(_:)-8ysz9`` + +- ``subtracting(_:)-7u4tf`` +- ``subtracting(_:)-5vgml`` +- ``subtracting(_:)-6scy1`` +- ``subtracting(_:)-82loi`` + +- ``symmetricDifference(_:)-84e40`` +- ``symmetricDifference(_:)-3suo3`` +- ``symmetricDifference(_:)-7zx5q`` +- ``symmetricDifference(_:)-46ni1`` + +- ``formIntersection(_:)-49and`` +- ``formIntersection(_:)-49a0x`` +- ``formIntersection(_:)-79anv`` +- ``formIntersection(_:)-3zoc4`` + +- ``formUnion(_:)-c6a3`` +- ``formUnion(_:)-c5kv`` +- ``formUnion(_:)-2f05x`` +- ``formUnion(_:)-8kilf`` + +- ``subtract(_:)-2hzty`` +- ``subtract(_:)-2i1qq`` +- ``subtract(_:)-32jtb`` +- ``subtract(_:)-75xgt`` + +- ``formSymmetricDifference(_:)-6vskl`` +- ``formSymmetricDifference(_:)-6vs05`` +- ``formSymmetricDifference(_:)-d2kd`` +- ``formSymmetricDifference(_:)-54ghn`` + +### Binary Set Predicates + +- ``==(_:_:)`` +- ``isEqual(to:)-5bw9h`` +- ``isEqual(to:)-8jxq5`` +- ``isEqual(to:)-7w9qy`` +- ``isEqual(to:)-9tnfo`` + +- ``isSubset(of:)-8iy8c`` +- ``isSubset(of:)-1r41b`` +- ``isSubset(of:)-1dz0p`` +- ``isSubset(of:)-3bq5m`` + +- ``isSuperset(of:)-48i5c`` +- ``isSuperset(of:)-10gu8`` +- ``isSuperset(of:)-8b7lq`` +- ``isSuperset(of:)-6slai`` + +- ``isStrictSubset(of:)-5ry1b`` +- ``isStrictSubset(of:)-2ndu3`` +- ``isStrictSubset(of:)-9iul0`` +- ``isStrictSubset(of:)-2pq1j`` + +- ``isStrictSuperset(of:)-9mgmd`` +- ``isStrictSuperset(of:)-6hw4t`` +- ``isStrictSuperset(of:)-1ya0j`` +- ``isStrictSuperset(of:)-4qt1e`` + +- ``isDisjoint(with:)-9wyku`` +- ``isDisjoint(with:)-5fww0`` +- ``isDisjoint(with:)-6p0t7`` +- ``isDisjoint(with:)-eujj`` diff --git a/Sources/BitCollections/BitCollections.docc/Extensions/BitSet.md b/Sources/BitCollections/BitCollections.docc/Extensions/BitSet.md new file mode 100644 index 00000000..df39d0d0 --- /dev/null +++ b/Sources/BitCollections/BitCollections.docc/Extensions/BitSet.md @@ -0,0 +1,88 @@ +# ``BitCollections/BitSet`` + +Summary + +## Overview + +Text + +## Topics + +### Nested Structures + +- ``Counted-swift.struct`` + +### Binary Set Operations + +- ``intersection(_:)-84q4u`` +- ``intersection(_:)-8hcl9`` +- ``intersection(_:)-7l8p3`` +- ``intersection(_:)-7kgi`` + +- ``union(_:)-5kqmx`` +- ``union(_:)-6mj8`` +- ``union(_:)-50wc4`` +- ``union(_:)-10had`` + +- ``subtracting(_:)-79e0o`` +- ``subtracting(_:)-7re82`` +- ``subtracting(_:)-7rn26`` +- ``subtracting(_:)-42s7d`` + +- ``symmetricDifference(_:)-55kqn`` +- ``symmetricDifference(_:)-5xt65`` +- ``symmetricDifference(_:)-91kh8`` +- ``symmetricDifference(_:)-79wfx`` + +- ``formIntersection(_:)-u07v`` +- ``formIntersection(_:)-87gjl`` +- ``formIntersection(_:)-9gffv`` +- ``formIntersection(_:)-8t2je`` + +- ``formUnion(_:)-72o7q`` +- ``formUnion(_:)-370hb`` +- ``formUnion(_:)-7tw8j`` +- ``formUnion(_:)-12ll3`` + +- ``subtract(_:)-9aabm`` +- ``subtract(_:)-1o083`` +- ``subtract(_:)-6kijg`` +- ``subtract(_:)-3pynh`` + +- ``formSymmetricDifference(_:)-2le2k`` +- ``formSymmetricDifference(_:)-5edyr`` +- ``formSymmetricDifference(_:)-7wole`` +- ``formSymmetricDifference(_:)-8vcnf`` + +### Binary Set Predicates + +- ``==(_:_:)`` +- ``isEqual(to:)-5zfpo`` +- ``isEqual(to:)-93d52`` +- ``isEqual(to:)-542zl`` +- ``isEqual(to:)-1d66i`` + +- ``isSubset(of:)-73apg`` +- ``isSubset(of:)-14xt1`` +- ``isSubset(of:)-4mj71`` +- ``isSubset(of:)-20wxs`` + +- ``isSuperset(of:)-1mfg2`` +- ``isSuperset(of:)-5adir`` +- ``isSuperset(of:)-4y68t`` +- ``isSuperset(of:)-2m7mj`` + +- ``isStrictSubset(of:)-8m1z6`` +- ``isStrictSubset(of:)-3y2l1`` +- ``isStrictSubset(of:)-97rky`` +- ``isStrictSubset(of:)-p3zj`` + +- ``isStrictSuperset(of:)-6e5gm`` +- ``isStrictSuperset(of:)-735zn`` +- ``isStrictSuperset(of:)-26acy`` +- ``isStrictSuperset(of:)-5jmxx`` + +- ``isDisjoint(with:)-2cdg6`` +- ``isDisjoint(with:)-3klxy`` +- ``isDisjoint(with:)-4uidy`` +- ``isDisjoint(with:)-78a8w`` diff --git a/Sources/Collections/Collections.docc/Collections.md b/Sources/Collections/Collections.docc/Collections.md new file mode 100644 index 00000000..c2a559c2 --- /dev/null +++ b/Sources/Collections/Collections.docc/Collections.md @@ -0,0 +1,38 @@ +# ``Collections`` + +**Swift Collections** is an open-source package of data structure implementations for the Swift programming language. + +## Overview + + + +#### Additional Resources + +- [`Swift Collections` on GitHub](https://github.com/apple/swift-collections/) +- [`Swift Collections` on the Swift Forums](https://forums.swift.org/c/related-projects/collections/72) + + +## Topics + +### Bit Collections + +- ``BitSet`` +- ``BitArray`` + +### Deque Module + +- ``Deque`` + +### Heap Module + +- ``Heap`` + +### Ordered Collections + +- ``OrderedSet`` +- ``OrderedDictionary`` + +### Persistent Collections + +- ``PersistentSet`` +- ``PersistentDictionary`` diff --git a/Sources/DequeModule/DequeModule.docc/DequeModule.md b/Sources/DequeModule/DequeModule.docc/DequeModule.md new file mode 100644 index 00000000..98ad67f4 --- /dev/null +++ b/Sources/DequeModule/DequeModule.docc/DequeModule.md @@ -0,0 +1,8 @@ +# ``DequeModule`` + +Summary + +## Overview + +Text + diff --git a/Sources/HeapModule/HeapModule.docc/HeapModule.md b/Sources/HeapModule/HeapModule.docc/HeapModule.md new file mode 100644 index 00000000..5523f52b --- /dev/null +++ b/Sources/HeapModule/HeapModule.docc/HeapModule.md @@ -0,0 +1,13 @@ +# ``HeapModule`` + +Summary + +## Overview + +Text + +## Topics + +### Structures + +- ``Heap`` diff --git a/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.UnorderedView.md b/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.UnorderedView.md new file mode 100644 index 00000000..d812d0d6 --- /dev/null +++ b/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.UnorderedView.md @@ -0,0 +1,64 @@ +# ``OrderedCollections/OrderedSet/UnorderedView`` + +Summary + +## Overview + +Text + +## Topics + +### Binary Set Operations + +- ``intersection(_:)-3q45l`` +- ``intersection(_:)-6ee3o`` + +- ``union(_:)-79uk3`` +- ``union(_:)-23dm1`` + +- ``subtracting(_:)-3ct1b`` +- ``subtracting(_:)-8e6mw`` + +- ``symmetricDifference(_:)-6aed7`` +- ``symmetricDifference(_:)-7r79p`` + +- ``formIntersection(_:)-4ow38`` +- ``formIntersection(_:)-80iht`` + +- ``formUnion(_:)-6ijb`` +- ``formUnion(_:)-8tuol`` + +- ``subtract(_:)-627eq`` +- ``subtract(_:)-4pjhu`` + +- ``formSymmetricDifference(_:)-8pkt5`` +- ``formSymmetricDifference(_:)-75z52`` + +### Binary Set Predicates + +- ``==(_:_:)`` + +- ``isSubset(of:)-n4t7`` +- ``isSubset(of:)-2dx31`` +- ``isSubset(of:)-801lo`` +- ``isSubset(of:)-952h5`` + +- ``isSuperset(of:)-4ea6h`` +- ``isSuperset(of:)-9t33p`` +- ``isSuperset(of:)-2vtig`` +- ``isSuperset(of:)-9krpz`` + +- ``isStrictSubset(of:)-33z0l`` +- ``isStrictSubset(of:)-9o6mg`` +- ``isStrictSubset(of:)-91par`` +- ``isStrictSubset(of:)-7n66e`` + +- ``isStrictSuperset(of:)-8pbce`` +- ``isStrictSuperset(of:)-89ig3`` +- ``isStrictSuperset(of:)-1e0xt`` +- ``isStrictSuperset(of:)-5dsfd`` + +- ``isDisjoint(with:)-7sbsg`` +- ``isDisjoint(with:)-3wuso`` +- ``isDisjoint(with:)-25vmx`` +- ``isDisjoint(with:)-8nfqs`` diff --git a/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.md b/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.md new file mode 100644 index 00000000..c8b1b579 --- /dev/null +++ b/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.md @@ -0,0 +1,142 @@ +# ``OrderedCollections/OrderedSet`` + +Summary + +## Overview + +Text + +## Topics + +### Creating a Set + +- ``init()`` +- ``init(_:)-5zktd`` +- ``init(_:)-3d7qr`` +- ``init(_:)-68j7`` +- ``init(_:)-8zm9d`` +- ``init(_:)-7rt2h`` +- ``init(_:)-8tli8`` +- ``init(_:)-2d3a9`` +- ``init(uncheckedUniqueElements:)`` +- ``init(minimumCapacity:persistent:)`` + +### Collection Views + +- ``UnorderedView`` +- ``unordered`` +- ``elements`` + +### Finding Elements + +- ``contains(_:)`` +- ``firstIndex(of:)`` +- ``lastIndex(of:)`` + +### Adding Elements + +- ``append(_:)`` +- ``append(contentsOf:)`` +- ``insert(_:at:)`` +- ``updateOrAppend(_:)`` +- ``updateOrInsert(_:at:)`` +- ``update(_:at:)`` + +### Removing Elements + +- ``filter(_:)`` +- ``removeAll(where:)`` +- ``remove(_:)`` +- ``remove(at:)`` +- ``removeAll(keepingCapacity:)`` +- ``removeFirst()`` +- ``removeLast()`` +- ``removeFirst(_:)`` +- ``removeLast(_:)`` +- ``removeSubrange(_:)-62u6a`` +- ``removeSubrange(_:)-2fqke`` + +### Combining Sets + +- ``intersection(_:)-4o09a`` +- ``intersection(_:)-9yzg3`` +- ``intersection(_:)-80md4`` + +- ``union(_:)-67y2h`` +- ``union(_:)-3lt5i`` +- ``union(_:)-2939h`` + +- ``subtracting(_:)-5graf`` +- ``subtracting(_:)-7kl8r`` +- ``subtracting(_:)-1gl4y`` + +- ``symmetricDifference(_:)-1810l`` +- ``symmetricDifference(_:)-8dvm6`` +- ``symmetricDifference(_:)-9huk7`` + +- ``formIntersection(_:)-43o1u`` +- ``formIntersection(_:)-2a4y4`` +- ``formIntersection(_:)-7odn2`` + +- ``formUnion(_:)-6pksr`` +- ``formUnion(_:)-3dkzw`` +- ``formUnion(_:)-59end`` + +- ``subtract(_:)-3b6nj`` +- ``subtract(_:)-9rtmd`` +- ``subtract(_:)-9wmg8`` + +- ``formSymmetricDifference(_:)-96csi`` +- ``formSymmetricDifference(_:)-2ll2z`` +- ``formSymmetricDifference(_:)-391sm`` + +### Comparing Sets + +- ``==(_:_:)`` +- ``isEqual(to:)-69p52`` +- ``isEqual(to:)-1xzfo`` +- ``isEqual(to:)-3ab2q`` + +- ``isSubset(of:)-ptij`` +- ``isSubset(of:)-3mw6r`` +- ``isSubset(of:)-8yb29`` +- ``isSubset(of:)-9hxl4`` + +- ``isSuperset(of:)-4rrsh`` +- ``isSuperset(of:)-2bbv8`` +- ``isSuperset(of:)-7xvog`` +- ``isSuperset(of:)-7oow7`` + +- ``isStrictSubset(of:)-8m21h`` +- ``isStrictSubset(of:)-9lv3x`` +- ``isStrictSubset(of:)-4efhn`` +- ``isStrictSubset(of:)-10abw`` + +- ``isStrictSuperset(of:)-7u97x`` +- ``isStrictSuperset(of:)-3kfwa`` +- ``isStrictSuperset(of:)-98d9s`` +- ``isStrictSuperset(of:)-5e6d5`` + +- ``isDisjoint(with:)-6vmoh`` +- ``isDisjoint(with:)-4tsmx`` +- ``isDisjoint(with:)-54iy6`` +- ``isDisjoint(with:)-7nqur`` + +### Reordering Elements + +- ``swapAt(_:_:)`` +- ``sort()`` +- ``sort(by:)`` +- ``reverse()`` +- ``shuffle()`` +- ``shuffle(using:)`` +- ``partition(by:)`` + +### Creating and Applying Differences + +- ``difference(from:)-30bkk`` +- ``applying(_:)`` + +### Memory Management + +- ``reserveCapacity(_:)`` diff --git a/Sources/OrderedCollections/OrderedCollections.docc/OrderedCollections.md b/Sources/OrderedCollections/OrderedCollections.docc/OrderedCollections.md new file mode 100644 index 00000000..a15dedd9 --- /dev/null +++ b/Sources/OrderedCollections/OrderedCollections.docc/OrderedCollections.md @@ -0,0 +1,20 @@ +# ``OrderedCollections`` + +**Swift Collections** is an open-source package of data structure implementations for the Swift programming language. + +## Overview + + + +#### Additional Resources + +- [`Swift Collections` on GitHub](https://github.com/apple/swift-collections/) +- [`Swift Collections` on the Swift Forums](https://forums.swift.org/c/related-projects/collections/72) + + +## Topics + +### Structures + +- ``OrderedSet`` +- ``OrderedDictionary`` From de22bed429ed0c55c699ca3c1957535da15a6f65 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 27 Oct 2022 18:20:37 -0700 Subject: [PATCH 33/39] [OrderedCollections] Update top-level docs --- .../Extensions/OrderedSet.md | 4 +- .../OrderedDictionary/OrderedDictionary.swift | 128 ++++++++-------- .../OrderedSet/OrderedSet.swift | 140 +++++++++++------- 3 files changed, 151 insertions(+), 121 deletions(-) diff --git a/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.md b/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.md index c8b1b579..83750054 100644 --- a/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.md +++ b/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.md @@ -33,7 +33,7 @@ - ``firstIndex(of:)`` - ``lastIndex(of:)`` -### Adding Elements +### Adding and Updating Elements - ``append(_:)`` - ``append(contentsOf:)`` @@ -134,7 +134,7 @@ ### Creating and Applying Differences -- ``difference(from:)-30bkk`` +- ``difference(from:)`` - ``applying(_:)`` ### Memory Management diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift index 41fd036a..f24fbf2c 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift @@ -79,7 +79,7 @@ /// /// If the `Value` type implements reference semantics, or when you need to /// perform a series of individual mutations on the values, the closure-based -/// `updateValue(forKey:default:_:)` method provides an easier-to-use +/// ``updateValue(forKey:default:with:)`` method provides an easier-to-use /// alternative to the defaulted key-based subscript. /// /// let text = "short string" @@ -93,13 +93,14 @@ /// /// (This isn't currently available on the regular `Dictionary`.) /// -/// The `Dictionary` type's original `updateValue(_:forKey:)` method is also -/// available, and so is `index(forKey:)`, grouping/uniquing initializers -/// (`init(uniqueKeysWithValues:)`, `init(_:uniquingKeysWith:)`, -/// `init(grouping:by:)`), methods for merging one dictionary with another -/// (`merge`, `merging`), filtering dictionary entries (`filter(_:)`), -/// transforming values (`mapValues(_:)`), and a combination of these two -/// (`compactMapValues(_:)`). +/// The `Dictionary` type's original ``updateValue(_:forKey:)`` method is also +/// available, and so is ``index(forKey:)``, grouping/uniquing initializers +/// (``init(uniqueKeysWithValues:)-5ux9r``, ``init(_:uniquingKeysWith:)-2y39b``, +/// ``init(grouping:by:)-6mahw``), methods for merging one dictionary with +/// another (``merge(_:uniquingKeysWith:)-6ka2i``, +/// ``merging(_:uniquingKeysWith:)-4z49c``), filtering dictionary entries +/// (``filter(_:)``), transforming values (``mapValues(_:)``), and a combination +/// of these two (``compactMapValues(_:)``). /// /// ### Sequence and Collection Operations /// @@ -114,53 +115,51 @@ /// /// Because ordered dictionaries need to maintain unique keys, neither /// `OrderedDictionary` nor its `elements` view can conform to the full -/// `MutableCollection` or `RangeReplaceableCollection` protocols. However, they -/// are able to partially implement requirements: they support mutations -/// that merely change the order of elements, or just remove a subset of -/// existing members: +/// `MutableCollection` or `RangeReplaceableCollection` protocols. /// -/// // Permutation operations from MutableCollection: -/// func swapAt(_ i: Int, _ j: Int) -/// func partition(by predicate: (Element) throws -> Bool) -> rethrows Int -/// func sort() where Element: Comparable -/// func sort(by predicate: (Element, Element) throws -> Bool) rethrows -/// func shuffle() -/// func shuffle(using generator: inout T) +/// However, `OrderedDictioanr` is still able to implement some of the +/// requirements of these protocols. In particular, it supports permutation +/// operations from `MutableCollection`: /// -/// // Removal operations from RangeReplaceableCollection: -/// func removeAll(keepingCapacity: Bool = false) -/// func remove(at index: Int) -> Element -/// func removeSubrange(_ bounds: Range) -/// func removeLast() -> Element -/// func removeLast(_ n: Int) -/// func removeFirst() -> Element -/// func removeFirst(_ n: Int) -/// func removeAll(where shouldBeRemoved: (Element) throws -> Bool) rethrows +/// - ``swapAt(_:_:)`` +/// - ``partition(by:)`` +/// - ``sort()``, ``sort(by:)`` +/// - ``shuffle()``, ``shuffle(using:)`` +/// - ``reverse()`` /// -/// `OrderedDictionary` also implements `reserveCapacity(_)` from +/// It also supports removal operations from `RangeReplaceableCollection`: +/// +/// - ``removeAll(keepingCapacity:)`` +/// - ``remove(at:)`` +/// - ``removeSubrange(_:)-512n3``, ``removeSubrange(_:)-8rmzx`` +/// - ``removeLast()``, ``removeLast(_:)`` +/// - ``removeFirst()``, ``removeFirst(_:)`` +/// - ``removeAll(where:)`` +/// +/// `OrderedDictionary` also implements ``reserveCapacity(_:)`` from /// `RangeReplaceableCollection`, to allow for efficient insertion of a known /// number of elements. (However, unlike `Array` and `Dictionary`, /// `OrderedDictionary` does not provide a `capacity` property.) /// /// ### Keys and Values Views /// -/// Like the standard `Dictionary`, `OrderedDictionary` provides `keys` and -/// `values` properties that provide lightweight views into the corresponding -/// parts of the dictionary. +/// Like the standard `Dictionary`, `OrderedDictionary` provides ``keys`` and +/// ``values-swift.property`` properties that provide lightweight views into +/// the corresponding parts of the dictionary. /// -/// The `keys` collection is of type `OrderedSet`, containing all the keys +/// The ``keys`` collection is of type ``OrderedSet``, containing all the keys /// in the original dictionary. /// /// let d: OrderedDictionary = [2: "two", 1: "one", 0: "zero"] /// d.keys // [2, 1, 0] as OrderedSet /// -/// The `keys` property is read-only, so you cannot mutate the dictionary +/// The ``keys`` property is read-only, so you cannot mutate the dictionary /// through it. However, it returns an ordinary ordered set value, which can be /// copied out and then mutated if desired. (Such mutations won't affect the /// original dictionary value.) /// -/// The `values` collection is a mutable random-access collection of the values -/// in the dictionary: +/// The ``values-swift.property`` collection is a mutable random-access +/// collection of the values in the dictionary: /// /// d.values // "two", "one", "zero" /// d.values[2] = "nada" @@ -169,40 +168,37 @@ /// // `d` is now [2: "nada", 1: "one", 0: "two"] /// /// Both views store their contents in regular `Array` values, accessible -/// through their `elements` property. +/// through their ``elements-swift.property`` property. /// /// ## Performance /// -/// Like the standard `Dictionary` type, the performance of hashing operations -/// in `OrderedDictionary` is highly sensitive to the quality of hashing -/// implemented by the `Key` type. Failing to correctly implement hashing can -/// easily lead to unacceptable performance, with the severity of the effect -/// increasing with the size of the hash table. -/// -/// In particular, if a certain set of keys all produce the same hash value, -/// then hash table lookups regress to searching an element in an unsorted -/// array, i.e., a linear operation. To ensure hashed collection types exhibit -/// their target performance, it is important to ensure that such collisions -/// cannot be induced merely by adding a particular list of keys to the -/// dictionary. -/// -/// The easiest way to achieve this is to make sure `Key` implements hashing -/// following `Hashable`'s documented best practices. The conformance must -/// implement the `hash(into:)` requirement, and every bit of information that -/// is compared in `==` needs to be combined into the supplied `Hasher` value. -/// When used correctly, `Hasher` produces high-quality, randomly seeded hash -/// values that prevent repeatable hash collisions. -/// -/// When `Key` correctly conforms to `Hashable`, key-based lookups in an ordered -/// dictionary is expected to take O(1) equality checks on average. Hash -/// collisions can still occur organically, so the worst-case lookup performance -/// is technically still O(*n*) (where *n* is the size of the dictionary); -/// however, long lookup chains are unlikely to occur in practice. -/// -/// ## Implementation Details -/// -/// An ordered dictionary consists of an ordered set of keys, alongside a +/// An ordered dictionary consists of an ``OrderedSet`` of keys, alongside a /// regular `Array` value that contains their associated values. +/// The performance characteristics of `OrderedDictionary` are mostly dictated +/// by this setup. +/// +/// - Looking up a member in an ordered dictionary is expected to execute +/// a constant number of hashing and equality check operations, just like +/// the standard `Dictionary`. +/// - `OrderedDictionary` is also able to append new items at the end of the +/// dictionary with an expected amortized complexity of O(1), similar to +/// inserting new items into `Dictionary`. +/// - Unfortunately, removing or inserting items at the start or middle of an +/// `OrderedDictionary` has linear complexity, making these significantly +/// slower than `Dictionary`. +/// - Storing keys and values outside of the hash table makes +/// `OrderedDictionary` more memory efficient than most alternative +/// ordered dictionary representations. It can sometimes also be more memory +/// efficient than the standard `Dictionary`, despote the additional +/// functionality of preserving element ordering. +/// +/// Like all hashed data structures, ordered dictionaries are extremely +/// sensitive to the quality of the `Key` type's `Hashable` conformance. +/// All complexity guarantees are null and void if `Key` implements `Hashable` +/// incorrectly. +/// +/// See ``OrderedSet`` for a more detailed discussion of these performance +/// characteristics. @frozen public struct OrderedDictionary { @usableFromInline diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet.swift index e65caf4a..bad7d2d2 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet.swift @@ -132,28 +132,24 @@ /// /// However, `OrderedSet` is able to partially implement these two protocols; /// namely, there is no issue with mutation operations that merely change the -/// order of elements, or just remove some subset of existing members: +/// order of elements, or just remove some subset of existing members. /// -/// // Permutation operations from MutableCollection: -/// func swapAt(_ i: Int, _ j: Int) -/// func partition(by predicate: (Element) throws -> Bool) -> rethrows Int -/// func sort() where Element: Comparable -/// func sort(by predicate: (Element, Element) throws -> Bool) rethrows -/// func shuffle() -/// func shuffle(using generator: inout T) -/// func reverse() +/// Accordingly, `OrderedSet` provides permutation operations from `MutableCollection`: +/// - ``swapAt(_:_:)`` +/// - ``partition(by:)`` +/// - ``sort()``, ``sort(by:)`` +/// - ``shuffle()``, ``shuffle(using:)`` +/// - ``reverse()`` /// -/// // Removal operations from RangeReplaceableCollection: -/// func removeAll(keepingCapacity: Bool = false) -/// func remove(at index: Int) -> Element -/// func removeSubrange(_ bounds: Range) -/// func removeLast() -> Element -/// func removeLast(_ n: Int) -/// func removeFirst() -> Element -/// func removeFirst(_ n: Int) -/// func removeAll(where shouldBeRemoved: (Element) throws -> Bool) rethrows +/// It also supports removal operations from `RangeReplaceableCollection`: +/// - ``removeAll(keepingCapacity:)`` +/// - ``remove(at:)`` +/// - ``removeSubrange(_:)-2fqke``, ``removeSubrange(_:)-62u6a`` +/// - ``removeLast()``, ``removeLast(_:)`` +/// - ``removeFirst()``, ``removeFirst(_:)`` +/// - ``removeAll(where:)`` /// -/// `OrderedSet` also implements `reserveCapacity(_)` from +/// `OrderedSet` also implements ``reserveCapacity(_:)`` from /// `RangeReplaceableCollection`, to allow for efficient insertion of a known /// number of elements. (However, unlike `Array` and `Set`, `OrderedSet` does /// not provide a `capacity` property.) @@ -175,20 +171,77 @@ /// pickyFunction(set.elements) // OK /// /// It is also possible to mutate the set by updating the value of the -/// `elements` property. This guarantees that direct mutations happen in place +/// ``elements`` property. This guarantees that direct mutations happen in place /// when possible (i.e., without spurious copy-on-write copies). /// /// However, the set needs to ensure the uniqueness of its members, so every -/// update to `elements` includes a postprocessing step to detect and remove +/// update to ``elements`` includes a postprocessing step to detect and remove /// duplicates over the entire array. This can be slower than doing the /// equivalent updates with direct `OrderedSet` operations, so updating -/// `elements` is best used in cases where direct implementations aren't +/// ``elements`` is best used in cases where direct implementations aren't /// available -- for example, when you need to call a `MutableCollection` /// algorithm that isn't directly implemented by `OrderedSet` itself. /// /// # Performance /// -/// Like the standard `Set` type, the performance of hashing operations in +/// An `OrderedSet` stores its members in a standard `Array` value (exposed by +/// the ``elements`` property). It also maintains a separate hash table +/// containing array indices into this array; this hash table is used to ensure +/// member uniqueness and to implement fast membership tests. +/// +/// ## Element Lookups +/// +/// Like the standard `Set`, looking up a member is expected to execute +/// a constant number of hashing and equality check operations. To look up +/// an element, `OrderedSet` generates a hash value from it, and then finds a +/// set of array indices within the hash table that could potentially contain +/// the element we're looking for. By looking through these indices in the +/// storage array, `OrderedSet` is able to determine if the element is a member. +/// As long as `Element` properly implements hashing, the size of this set of +/// candidate indices is expected to have a constant upper bound, so looking up +/// an item will be a constant operation. +/// +/// ## Appending New Items +/// +/// Similarly, appending a new element to the end of an `OrderedSet` is expected +/// to require amortized O(1) hashing/comparison/copy operations on the +/// element type, just like inserting an item into a standard `Set`. +/// (If the ordered set value has multiple copies, then appending an item will +/// need to copy all its items into unique storage (again just like the standard +/// `Set`) -- but once the set has been uniqued, additional appends will only +/// perform a constant number of operations, so when averaged over many appends, +/// the overall complexity comes out as O(1).) +/// +/// ## Removing Items and Inserting in Places Other Than the End +/// +/// Unfortunately, `OrderedSet` does not emulate `Set`'s performance for all +/// operations. In particular, operations that insert or remove elements at the +/// front or in the middle of an ordered set are generally expected to be +/// significantly slower than with `Set`. To perform these operations, an +/// `OrderedSet` needs to perform the corresponding operation in the storage +/// array, and then it needs to renumber all subsequent members in the hash +/// table. Both of these phases take a number of steps that grows linearly with +/// the size of the ordered set, while the standard `Set` can do the +/// corresponding operations with O(1) expected complexity. +/// +/// This generally makes `OrderedSet` a poor replacement to `Set` in use cases +/// that do not specifically require a particular element ordering. +/// +/// ## Memory Utilization +/// +/// The hash table in an ordered set never needs to store larger indices than +/// the current size of the storage array, and `OrderedSet` makes use of this +/// observation to reduce the number of bits it uses to encode these integer +/// vaues. Additionally, the actual hashed elements are stored in a flat array +/// value rather than the hash table itself, so they aren't subject to the hash +/// table's strict maximum load factor. These two observations combine to +/// optimize the memory utilization of `OrderedSet`, sometimes making it even +/// more efficient than the standard `Set` -- despite the additional +/// functionality of preserving element ordering. +/// +/// ## Proper Hashing is Crucial +/// +/// Similar to the standard `Set` type, the performance of hashing operations in /// `OrderedSet` is highly sensitive to the quality of hashing implemented by /// the `Element` type. Failing to correctly implement hashing can easily lead /// to unacceptable performance, with the severity of the effect increasing with @@ -201,37 +254,18 @@ /// cannot be induced merely by adding a particular list of members to the set. /// /// The easiest way to achieve this is to make sure `Element` implements hashing -/// following `Hashable`'s documented best practices. The conformance must -/// implement the `hash(into:)` requirement, and every bit of information that -/// is compared in `==` needs to be combined into the supplied `Hasher` value. -/// When used correctly, `Hasher` produces high-quality, randomly seeded hash -/// values that prevent repeatable hash collisions. +/// following `Hashable`'s documented best practices. The `Element` type must +/// implement the `hash(into:)` requirement (not `hashValue`) in such a way that +/// every bit of information that is compared in `==` is fed into the supplied +/// `Hasher` value. When used correctly, `Hasher` produces high-quality, +/// randomly seeded hash values that prevent repeatable hash collisions and +/// therefore avoid (intentional or accidental) denial of service attacks. /// -/// When `Element` implements `Hashable` correctly, testing for membership in an -/// ordered set is expected to take O(1) equality checks on average. Hash -/// collisions can still occur organically, so the worst-case lookup performance -/// is technically still O(*n*) (where *n* is the size of the set); however, -/// long lookup chains are unlikely to occur in practice. -/// -/// # Implementation Details -/// -/// An `OrderedSet` stores its members in a regular `Array` value (exposed by -/// the `elements` property). It also maintains a standalone hash table -/// containing array indices alongside the array; this is used to implement fast -/// membership tests. The size of the array is limited by the capacity of the -/// corresponding hash table, so indices stored inside the hash table can be -/// encoded into fewer bits than a standard `Int` value, leading to a storage -/// representation that can often be more compact than that of `Set` itself. -/// -/// Inserting or removing a single member (or a range of members) needs to -/// perform the corresponding operation in the storage array, in addition to -/// renumbering any subsequent members in the hash table. Therefore, these -/// operations are expected to have performance characteristics similar to an -/// `Array`: inserting or removing an element to the end of an ordered set is -/// expected to execute in O(1) operations, while they are expected to take -/// linear time at the front (or in the middle) of the set. (Note that this is -/// different to the standard `Set`, where insertions and removals are expected -/// to take amortized O(1) time.) +/// Like with all hashed collection types, all complexity guarantees are null +/// and void if `Element` implements `Hashable` incorrectly. In the worst case, +/// the hash table can regress into a particularly slow implementation of an +/// unsorted array, with even basic lookup operations taking complexity +/// proportional to the size of the set. @frozen public struct OrderedSet where Element: Hashable { From 0120dd1d7946f769f7115577fa29c7dc6e141cf4 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 27 Oct 2022 18:22:54 -0700 Subject: [PATCH 34/39] [BitCollections] Categorize member APIs --- .../Extensions/BitArray.md | 72 +++++++++++++++++++ .../Extensions/BitSet.Counted.md | 43 +++++++++++ .../BitCollections.docc/Extensions/BitSet.md | 50 ++++++++++++- 3 files changed, 162 insertions(+), 3 deletions(-) create mode 100644 Sources/BitCollections/BitCollections.docc/Extensions/BitArray.md diff --git a/Sources/BitCollections/BitCollections.docc/Extensions/BitArray.md b/Sources/BitCollections/BitCollections.docc/Extensions/BitArray.md new file mode 100644 index 00000000..1f3baa3c --- /dev/null +++ b/Sources/BitCollections/BitCollections.docc/Extensions/BitArray.md @@ -0,0 +1,72 @@ +# ``BitCollections/BitArray`` + +Summary + +## Overview + +Text + +## Topics + +### Creating a Bit Array + +- ``init()`` +- ``init(_:)-2y0wv`` +- ``init(repeating:count:)-4j5yd`` +- ``init(_:)-6ldyw`` +- ``init(_:)-4tksd`` +- ``init(_:)-765d2`` +- ``init(bitPattern:)`` +- ``random(count:)`` +- ``random(count:using:)`` + +### Accessing Elements + +- ``subscript(_:)-51ccj`` +- ``subscript(_:)-944vg`` +- ``first`` +- ``last`` + +### Adding Elements + +- ``append(_:)`` +- ``append(contentsOf:)-18dwf`` +- ``append(contentsOf:)-576q4`` +- ``append(contentsOf:)-8xkr8`` +- ``insert(_:at:)`` +- ``insert(contentsOf:at:)-7e1xn`` +- ``insert(contentsOf:at:)-35dp3`` +- ``insert(contentsOf:at:)-1wsgw`` +- ``truncateOrExtend(toCount:with:)`` + +### Removing Elements + +- ``remove(at:)-7ij12`` +- ``removeAll(keepingCapacity:)-5tkge`` +- ``removeAll(where:)-7tv7z`` +- ``removeSubrange(_:)-86ou8`` +- ``removeSubrange(_:)-18qe7`` +- ``removeLast()`` +- ``removeLast(_:)`` +- ``removeFirst()`` +- ``removeFirst(_:)`` +- ``popLast()`` + +### Replacing Elements + +- ``fill(in:with:)`` +- ``fill(with:)`` +- ``replaceSubrange(_:with:)-163u2`` +- ``replaceSubrange(_:with:)-875d8`` +- ``replaceSubrange(_:with:)-2i7lu`` +- ``replaceSubrange(_:with:)-b5ou`` + +### Bitwise Operators + +- ``&(_:_:)`` +- ``_(_:_:)-1rhw`` +- ``_(_:_:)-56s54`` +- ``~(_:)`` +- ``&=(_:_:)`` +- ``_=(_:_:)-69yf0`` +- ``_=(_:_:)-icef`` diff --git a/Sources/BitCollections/BitCollections.docc/Extensions/BitSet.Counted.md b/Sources/BitCollections/BitCollections.docc/Extensions/BitSet.Counted.md index fbec5925..a3fed3b0 100644 --- a/Sources/BitCollections/BitCollections.docc/Extensions/BitSet.Counted.md +++ b/Sources/BitCollections/BitCollections.docc/Extensions/BitSet.Counted.md @@ -8,6 +8,49 @@ ## Topics +### Collection Views + +- ``uncounted`` + +### Creating a Set + +- ``init()`` +- ``init(reservingCapacity:)`` +- ``init(_:)-15cws`` +- ``init(_:)-38hho`` +- ``init(_:)-2of3i`` +- ``init(_:)-5fhls`` +- ``init(bitPattern:)`` +- ``init(words:)`` +- ``random(upTo:)`` +- ``random(upTo:using:)`` + +### Finding Elements + +- ``contains(_:)`` +- ``firstIndex(of:)`` +- ``lastIndex(of:)`` + +### Adding and Updating Elements + +- ``insert(_:)`` +- ``update(with:)`` + +### Removing Elements + +- ``filter(_:)`` +- ``remove(_:)`` +- ``remove(at:)`` + +### Sorted Set Operations + +- ``subscript(member:)`` +- ``subscript(members:)-5nkxk`` +- ``subscript(members:)-5xfq5`` +- ``min()`` +- ``max()`` +- ``sorted()`` + ### Binary Set Operations - ``intersection(_:)-1wfb5`` diff --git a/Sources/BitCollections/BitCollections.docc/Extensions/BitSet.md b/Sources/BitCollections/BitCollections.docc/Extensions/BitSet.md index df39d0d0..44ce1d15 100644 --- a/Sources/BitCollections/BitCollections.docc/Extensions/BitSet.md +++ b/Sources/BitCollections/BitCollections.docc/Extensions/BitSet.md @@ -8,11 +8,51 @@ ## Topics -### Nested Structures +### Collection Views - ``Counted-swift.struct`` +- ``counted-swift.property`` -### Binary Set Operations +### Creating a Set + +- ``init()`` +- ``init(reservingCapacity:)`` +- ``init(_:)-15cws`` +- ``init(_:)-38hho`` +- ``init(_:)-2of3i`` +- ``init(_:)-5fhls`` +- ``init(bitPattern:)`` +- ``init(words:)`` +- ``random(upTo:)`` +- ``random(upTo:using:)`` + +### Finding Elements + +- ``contains(_:)`` +- ``firstIndex(of:)`` +- ``lastIndex(of:)`` + +### Adding and Updating Elements + +- ``insert(_:)`` +- ``update(with:)`` + +### Removing Elements + +- ``filter(_:)`` +- ``remove(_:)`` +- ``remove(at:)`` + +### Sorted Set Operations + +- ``subscript(member:)`` +- ``subscript(members:)-5nkxk`` +- ``subscript(members:)-5xfq5`` +- ``min()`` +- ``max()`` +- ``sorted()`` + +### Combining Sets - ``intersection(_:)-84q4u`` - ``intersection(_:)-8hcl9`` @@ -54,7 +94,7 @@ - ``formSymmetricDifference(_:)-7wole`` - ``formSymmetricDifference(_:)-8vcnf`` -### Binary Set Predicates +### Comparing Sets - ``==(_:_:)`` - ``isEqual(to:)-5zfpo`` @@ -86,3 +126,7 @@ - ``isDisjoint(with:)-3klxy`` - ``isDisjoint(with:)-4uidy`` - ``isDisjoint(with:)-78a8w`` + +### Memory Management + +- ``reserveCapacity(_:)`` From 6af8954d5b9c2937480d35d58a104fbd5229b272 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 27 Oct 2022 18:04:51 -0700 Subject: [PATCH 35/39] [doc] Add generate-docs.sh --- Utils/generate-docs.sh | 94 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100755 Utils/generate-docs.sh diff --git a/Utils/generate-docs.sh b/Utils/generate-docs.sh new file mode 100755 index 00000000..448e5cfa --- /dev/null +++ b/Utils/generate-docs.sh @@ -0,0 +1,94 @@ +#!/bin/sh +#===---------------------------------------------------------------------- +# +# 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 +# +#===---------------------------------------------------------------------- + +set -eu + +shopt -s nullglob +cd "$(dirname $0)/.." + +if [ "$(uname)" = "Darwin" ]; then + swift="xcrun swift" + export DOCC_HTML_DIR="$(dirname $(xcrun --find docc))/../share/docc/render" +else + swift="swift" +fi + +build_dir="$(mktemp -d "/tmp/$(basename $0).XXXXX")" +echo "Build directory: $build_dir" + +output_dir_base=/tmp/foo + +rm -rf "$output_dir_base" + +components="\ + BitCollections DequeModule HeapModule OrderedCollections \ + PersistentCollections" + +if [ $# -eq 0 ]; then + targets="Collections $components" +else + targets="$@" +fi + +for target in $targets; do + if [ "$target" = "Collections" ]; then + # Update extensions under Collections.docc + rm -rf Sources/Collections/Collections.docc/Extensions/*.md + for component in $components; do + for file in Sources/"$component"/"$component".docc/Extensions/*.md; do + output="Sources/Collections/Collections.docc/Extensions/$(basename $file)" + blurb="" + sed 's?^# ``[^/]*/\(.*\)``?# ``Collections/\1``\n\n'"$blurb"'\n?' "$file" > "$output" + done + done + fi + + mkdir -p "$build_dir/$target/build" + mkdir -p "$build_dir/$target/symbol-graphs" + mkdir -p "$build_dir/$target/docc" + $swift build --target "$target" \ + --build-path "$build_dir/$target/build" \ + -Xswiftc -emit-symbol-graph \ + -Xswiftc -emit-symbol-graph-dir \ + -Xswiftc "$build_dir/$target/symbol-graphs" + + # Prevent DocC from getting confused by too much data :-/ + cp \ + "$build_dir/$target/symbol-graphs/$target.symbols.json" \ + "$build_dir/$target/docc" + extrafile="$build_dir/$target/symbol-graphs/${target}@Swift.symbols.json" + if [ -r "$extrafile" ]; then + cp "$extrafile" "$build_dir/$target/docc" + fi + + mkdir -p "$output_dir_base/$target" + xcrun docc convert \ + --analyze \ + --fallback-display-name "$target" \ + --fallback-bundle-identifier "org.swift.swift-collections.$target" \ + --fallback-bundle-version 1.1.0 \ + --default-code-listing-language swift \ + --additional-symbol-graph-dir "$build_dir/$target/docc" \ + --transform-for-static-hosting \ + --output-path "$output_dir_base/$target" \ + --hosting-base-path "/swift-collections/$target" \ + "Sources/$target/$target.docc" +done + +if [ $# -eq 1 ]; then + module="$1" + xcrun docc preview "Sources/$module/$module.docc" \ + --fallback-display-name "Swift Collections" \ + --fallback-bundle-identifier "org.swift.swift-collections.$module" \ + --fallback-bundle-version 1.1.0 \ + --additional-symbol-graph-dir "$build_dir/$module/docc" +fi From b2f254384dcb40c2c293e226093ce7dadbec2ee4 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 27 Oct 2022 18:06:09 -0700 Subject: [PATCH 36/39] [doc] Add some flesh to DocC structure # Conflicts: # Sources/BitCollections/BitCollections.docc/Extensions/BitArray.md # Sources/BitCollections/BitCollections.docc/Extensions/BitSet.Counted.md # Sources/BitCollections/BitCollections.docc/Extensions/BitSet.md # Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.UnorderedView.md # Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.md --- .../BitCollections.docc/Extensions/BitArray.md | 6 ++---- .../BitCollections.docc/Extensions/BitSet.Counted.md | 6 ++---- .../BitCollections.docc/Extensions/BitSet.md | 6 ++---- Sources/DequeModule/DequeModule.docc/Extensions/Deque.md | 7 +++++++ Sources/HeapModule/HeapModule.docc/Extensions/Heap.md | 7 +++++++ .../Extensions/OrderedSet.UnorderedView.md | 8 +++----- .../OrderedCollections.docc/Extensions/OrderedSet.md | 6 ++---- 7 files changed, 25 insertions(+), 21 deletions(-) create mode 100644 Sources/DequeModule/DequeModule.docc/Extensions/Deque.md create mode 100644 Sources/HeapModule/HeapModule.docc/Extensions/Heap.md diff --git a/Sources/BitCollections/BitCollections.docc/Extensions/BitArray.md b/Sources/BitCollections/BitCollections.docc/Extensions/BitArray.md index 1f3baa3c..5fa6a8e4 100644 --- a/Sources/BitCollections/BitCollections.docc/Extensions/BitArray.md +++ b/Sources/BitCollections/BitCollections.docc/Extensions/BitArray.md @@ -1,10 +1,8 @@ # ``BitCollections/BitArray`` -Summary + -## Overview - -Text + ## Topics diff --git a/Sources/BitCollections/BitCollections.docc/Extensions/BitSet.Counted.md b/Sources/BitCollections/BitCollections.docc/Extensions/BitSet.Counted.md index a3fed3b0..ae58fdf3 100644 --- a/Sources/BitCollections/BitCollections.docc/Extensions/BitSet.Counted.md +++ b/Sources/BitCollections/BitCollections.docc/Extensions/BitSet.Counted.md @@ -1,10 +1,8 @@ # ``BitCollections/BitSet/Counted-swift.struct`` -Summary + -## Overview - -Text + ## Topics diff --git a/Sources/BitCollections/BitCollections.docc/Extensions/BitSet.md b/Sources/BitCollections/BitCollections.docc/Extensions/BitSet.md index 44ce1d15..6f6edce8 100644 --- a/Sources/BitCollections/BitCollections.docc/Extensions/BitSet.md +++ b/Sources/BitCollections/BitCollections.docc/Extensions/BitSet.md @@ -1,10 +1,8 @@ # ``BitCollections/BitSet`` -Summary + -## Overview - -Text + ## Topics diff --git a/Sources/DequeModule/DequeModule.docc/Extensions/Deque.md b/Sources/DequeModule/DequeModule.docc/Extensions/Deque.md new file mode 100644 index 00000000..c262c77f --- /dev/null +++ b/Sources/DequeModule/DequeModule.docc/Extensions/Deque.md @@ -0,0 +1,7 @@ +# ``DequeModule/Deque`` + + + + + +## Topics diff --git a/Sources/HeapModule/HeapModule.docc/Extensions/Heap.md b/Sources/HeapModule/HeapModule.docc/Extensions/Heap.md new file mode 100644 index 00000000..bc647cdc --- /dev/null +++ b/Sources/HeapModule/HeapModule.docc/Extensions/Heap.md @@ -0,0 +1,7 @@ +# ``HeapModule/Heap`` + + + + + +## Topics diff --git a/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.UnorderedView.md b/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.UnorderedView.md index d812d0d6..0b6be3da 100644 --- a/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.UnorderedView.md +++ b/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.UnorderedView.md @@ -1,10 +1,8 @@ -# ``OrderedCollections/OrderedSet/UnorderedView`` +# ``Collections/OrderedSet/UnorderedView`` -Summary + -## Overview - -Text + ## Topics diff --git a/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.md b/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.md index 83750054..ed5d75c5 100644 --- a/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.md +++ b/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.md @@ -1,10 +1,8 @@ # ``OrderedCollections/OrderedSet`` -Summary + -## Overview - -Text + ## Topics From aaeeb9e440e4253f3148540dd02df4e434ed31c0 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 27 Oct 2022 17:13:44 -0700 Subject: [PATCH 37/39] [OrderedCollections] Doc updates --- .../Extensions/OrderedSet.UnorderedView.md | 2 +- .../OrderedDictionary+Partial RangeReplaceableCollection.swift | 2 +- .../OrderedDictionary/OrderedDictionary.swift | 2 +- Sources/OrderedCollections/OrderedSet/OrderedSet.swift | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.UnorderedView.md b/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.UnorderedView.md index 0b6be3da..b8ef33ba 100644 --- a/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.UnorderedView.md +++ b/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.UnorderedView.md @@ -1,4 +1,4 @@ -# ``Collections/OrderedSet/UnorderedView`` +# ``OrderedCollections/OrderedSet/UnorderedView`` diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial RangeReplaceableCollection.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial RangeReplaceableCollection.swift index bc5791ba..a681b813 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial RangeReplaceableCollection.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial RangeReplaceableCollection.swift @@ -48,7 +48,7 @@ extension OrderedDictionary { _values.removeAll(keepingCapacity: keepCapacity) } - /// Removes and returns the element at the specified position. + /// Removes and returns the key-value pair at the specified index. /// /// All the elements following the specified position are moved to close the /// resulting gap. diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift index f24fbf2c..3863521c 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift @@ -658,7 +658,7 @@ extension OrderedDictionary { /// in a string: /// /// let message = "Hello, Elle!" - /// var letterCounts: [Character: Int] = [:] + /// var letterCounts: OrderedDictionary = [:] /// for letter in message { /// letterCounts.updateValue(forKey: letter, default: 0) { count in /// count += 1 diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet.swift index bad7d2d2..ac19712d 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet.swift @@ -531,7 +531,7 @@ extension OrderedSet { } extension OrderedSet { - /// Returns a new ordered set containing the values pairs of the ordered set + /// Returns a new ordered set containing all the members of this ordered set /// that satisfy the given predicate. /// /// - Parameter isIncluded: A closure that takes a value as its From 1c147e3b06edbe0b00217e38e94d2d3bc4b4c6a7 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 28 Oct 2022 12:35:37 -0700 Subject: [PATCH 38/39] [Collections] Regenerate docs --- .../Collections.docc/Extensions/BitArray.md | 73 ++++++++ .../Extensions/BitSet.Counted.md | 128 ++++++++++++++ .../Collections.docc/Extensions/BitSet.md | 133 ++++++++++++++ .../Collections.docc/Extensions/Deque.md | 10 ++ .../Collections.docc/Extensions/Heap.md | 10 ++ .../Extensions/OrderedSet.UnorderedView.md | 65 +++++++ .../Collections.docc/Extensions/OrderedSet.md | 143 +++++++++++++++ .../Extensions/PersistentDictionary.md | 75 ++++++++ .../Extensions/PersistentSet.md | 166 ++++++++++++++++++ 9 files changed, 803 insertions(+) create mode 100644 Sources/Collections/Collections.docc/Extensions/BitArray.md create mode 100644 Sources/Collections/Collections.docc/Extensions/BitSet.Counted.md create mode 100644 Sources/Collections/Collections.docc/Extensions/BitSet.md create mode 100644 Sources/Collections/Collections.docc/Extensions/Deque.md create mode 100644 Sources/Collections/Collections.docc/Extensions/Heap.md create mode 100644 Sources/Collections/Collections.docc/Extensions/OrderedSet.UnorderedView.md create mode 100644 Sources/Collections/Collections.docc/Extensions/OrderedSet.md create mode 100644 Sources/Collections/Collections.docc/Extensions/PersistentDictionary.md create mode 100644 Sources/Collections/Collections.docc/Extensions/PersistentSet.md diff --git a/Sources/Collections/Collections.docc/Extensions/BitArray.md b/Sources/Collections/Collections.docc/Extensions/BitArray.md new file mode 100644 index 00000000..7afab2f5 --- /dev/null +++ b/Sources/Collections/Collections.docc/Extensions/BitArray.md @@ -0,0 +1,73 @@ +# ``Collections/BitArray`` + + + + + + + + +## Topics + +### Creating a Bit Array + +- ``init()`` +- ``init(_:)-2y0wv`` +- ``init(repeating:count:)-4j5yd`` +- ``init(_:)-6ldyw`` +- ``init(_:)-4tksd`` +- ``init(_:)-765d2`` +- ``init(bitPattern:)`` +- ``random(count:)`` +- ``random(count:using:)`` + +### Accessing Elements + +- ``subscript(_:)-51ccj`` +- ``subscript(_:)-944vg`` +- ``first`` +- ``last`` + +### Adding Elements + +- ``append(_:)`` +- ``append(contentsOf:)-18dwf`` +- ``append(contentsOf:)-576q4`` +- ``append(contentsOf:)-8xkr8`` +- ``insert(_:at:)`` +- ``insert(contentsOf:at:)-7e1xn`` +- ``insert(contentsOf:at:)-35dp3`` +- ``insert(contentsOf:at:)-1wsgw`` +- ``truncateOrExtend(toCount:with:)`` + +### Removing Elements + +- ``remove(at:)-7ij12`` +- ``removeAll(keepingCapacity:)-5tkge`` +- ``removeAll(where:)-7tv7z`` +- ``removeSubrange(_:)-86ou8`` +- ``removeSubrange(_:)-18qe7`` +- ``removeLast()`` +- ``removeLast(_:)`` +- ``removeFirst()`` +- ``removeFirst(_:)`` +- ``popLast()`` + +### Replacing Elements + +- ``fill(in:with:)`` +- ``fill(with:)`` +- ``replaceSubrange(_:with:)-163u2`` +- ``replaceSubrange(_:with:)-875d8`` +- ``replaceSubrange(_:with:)-2i7lu`` +- ``replaceSubrange(_:with:)-b5ou`` + +### Bitwise Operators + +- ``&(_:_:)`` +- ``_(_:_:)-1rhw`` +- ``_(_:_:)-56s54`` +- ``~(_:)`` +- ``&=(_:_:)`` +- ``_=(_:_:)-69yf0`` +- ``_=(_:_:)-icef`` diff --git a/Sources/Collections/Collections.docc/Extensions/BitSet.Counted.md b/Sources/Collections/Collections.docc/Extensions/BitSet.Counted.md new file mode 100644 index 00000000..93aeebc9 --- /dev/null +++ b/Sources/Collections/Collections.docc/Extensions/BitSet.Counted.md @@ -0,0 +1,128 @@ +# ``Collections/BitSet/Counted-swift.struct`` + + + + + + + + +## Topics + +### Collection Views + +- ``uncounted`` + +### Creating a Set + +- ``init()`` +- ``init(reservingCapacity:)`` +- ``init(_:)-15cws`` +- ``init(_:)-38hho`` +- ``init(_:)-2of3i`` +- ``init(_:)-5fhls`` +- ``init(bitPattern:)`` +- ``init(words:)`` +- ``random(upTo:)`` +- ``random(upTo:using:)`` + +### Finding Elements + +- ``contains(_:)`` +- ``firstIndex(of:)`` +- ``lastIndex(of:)`` + +### Adding and Updating Elements + +- ``insert(_:)`` +- ``update(with:)`` + +### Removing Elements + +- ``filter(_:)`` +- ``remove(_:)`` +- ``remove(at:)`` + +### Sorted Set Operations + +- ``subscript(member:)`` +- ``subscript(members:)-5nkxk`` +- ``subscript(members:)-5xfq5`` +- ``min()`` +- ``max()`` +- ``sorted()`` + +### Binary Set Operations + +- ``intersection(_:)-1wfb5`` +- ``intersection(_:)-4evdp`` +- ``intersection(_:)-9rtcc`` +- ``intersection(_:)-13us`` + +- ``union(_:)-2okwt`` +- ``union(_:)-pwqf`` +- ``union(_:)-18u31`` +- ``union(_:)-8ysz9`` + +- ``subtracting(_:)-7u4tf`` +- ``subtracting(_:)-5vgml`` +- ``subtracting(_:)-6scy1`` +- ``subtracting(_:)-82loi`` + +- ``symmetricDifference(_:)-84e40`` +- ``symmetricDifference(_:)-3suo3`` +- ``symmetricDifference(_:)-7zx5q`` +- ``symmetricDifference(_:)-46ni1`` + +- ``formIntersection(_:)-49and`` +- ``formIntersection(_:)-49a0x`` +- ``formIntersection(_:)-79anv`` +- ``formIntersection(_:)-3zoc4`` + +- ``formUnion(_:)-c6a3`` +- ``formUnion(_:)-c5kv`` +- ``formUnion(_:)-2f05x`` +- ``formUnion(_:)-8kilf`` + +- ``subtract(_:)-2hzty`` +- ``subtract(_:)-2i1qq`` +- ``subtract(_:)-32jtb`` +- ``subtract(_:)-75xgt`` + +- ``formSymmetricDifference(_:)-6vskl`` +- ``formSymmetricDifference(_:)-6vs05`` +- ``formSymmetricDifference(_:)-d2kd`` +- ``formSymmetricDifference(_:)-54ghn`` + +### Binary Set Predicates + +- ``==(_:_:)`` +- ``isEqual(to:)-5bw9h`` +- ``isEqual(to:)-8jxq5`` +- ``isEqual(to:)-7w9qy`` +- ``isEqual(to:)-9tnfo`` + +- ``isSubset(of:)-8iy8c`` +- ``isSubset(of:)-1r41b`` +- ``isSubset(of:)-1dz0p`` +- ``isSubset(of:)-3bq5m`` + +- ``isSuperset(of:)-48i5c`` +- ``isSuperset(of:)-10gu8`` +- ``isSuperset(of:)-8b7lq`` +- ``isSuperset(of:)-6slai`` + +- ``isStrictSubset(of:)-5ry1b`` +- ``isStrictSubset(of:)-2ndu3`` +- ``isStrictSubset(of:)-9iul0`` +- ``isStrictSubset(of:)-2pq1j`` + +- ``isStrictSuperset(of:)-9mgmd`` +- ``isStrictSuperset(of:)-6hw4t`` +- ``isStrictSuperset(of:)-1ya0j`` +- ``isStrictSuperset(of:)-4qt1e`` + +- ``isDisjoint(with:)-9wyku`` +- ``isDisjoint(with:)-5fww0`` +- ``isDisjoint(with:)-6p0t7`` +- ``isDisjoint(with:)-eujj`` diff --git a/Sources/Collections/Collections.docc/Extensions/BitSet.md b/Sources/Collections/Collections.docc/Extensions/BitSet.md new file mode 100644 index 00000000..790c8f33 --- /dev/null +++ b/Sources/Collections/Collections.docc/Extensions/BitSet.md @@ -0,0 +1,133 @@ +# ``Collections/BitSet`` + + + + + + + + +## Topics + +### Collection Views + +- ``Counted-swift.struct`` +- ``counted-swift.property`` + +### Creating a Set + +- ``init()`` +- ``init(reservingCapacity:)`` +- ``init(_:)-15cws`` +- ``init(_:)-38hho`` +- ``init(_:)-2of3i`` +- ``init(_:)-5fhls`` +- ``init(bitPattern:)`` +- ``init(words:)`` +- ``random(upTo:)`` +- ``random(upTo:using:)`` + +### Finding Elements + +- ``contains(_:)`` +- ``firstIndex(of:)`` +- ``lastIndex(of:)`` + +### Adding and Updating Elements + +- ``insert(_:)`` +- ``update(with:)`` + +### Removing Elements + +- ``filter(_:)`` +- ``remove(_:)`` +- ``remove(at:)`` + +### Sorted Set Operations + +- ``subscript(member:)`` +- ``subscript(members:)-5nkxk`` +- ``subscript(members:)-5xfq5`` +- ``min()`` +- ``max()`` +- ``sorted()`` + +### Combining Sets + +- ``intersection(_:)-84q4u`` +- ``intersection(_:)-8hcl9`` +- ``intersection(_:)-7l8p3`` +- ``intersection(_:)-7kgi`` + +- ``union(_:)-5kqmx`` +- ``union(_:)-6mj8`` +- ``union(_:)-50wc4`` +- ``union(_:)-10had`` + +- ``subtracting(_:)-79e0o`` +- ``subtracting(_:)-7re82`` +- ``subtracting(_:)-7rn26`` +- ``subtracting(_:)-42s7d`` + +- ``symmetricDifference(_:)-55kqn`` +- ``symmetricDifference(_:)-5xt65`` +- ``symmetricDifference(_:)-91kh8`` +- ``symmetricDifference(_:)-79wfx`` + +- ``formIntersection(_:)-u07v`` +- ``formIntersection(_:)-87gjl`` +- ``formIntersection(_:)-9gffv`` +- ``formIntersection(_:)-8t2je`` + +- ``formUnion(_:)-72o7q`` +- ``formUnion(_:)-370hb`` +- ``formUnion(_:)-7tw8j`` +- ``formUnion(_:)-12ll3`` + +- ``subtract(_:)-9aabm`` +- ``subtract(_:)-1o083`` +- ``subtract(_:)-6kijg`` +- ``subtract(_:)-3pynh`` + +- ``formSymmetricDifference(_:)-2le2k`` +- ``formSymmetricDifference(_:)-5edyr`` +- ``formSymmetricDifference(_:)-7wole`` +- ``formSymmetricDifference(_:)-8vcnf`` + +### Comparing Sets + +- ``==(_:_:)`` +- ``isEqual(to:)-5zfpo`` +- ``isEqual(to:)-93d52`` +- ``isEqual(to:)-542zl`` +- ``isEqual(to:)-1d66i`` + +- ``isSubset(of:)-73apg`` +- ``isSubset(of:)-14xt1`` +- ``isSubset(of:)-4mj71`` +- ``isSubset(of:)-20wxs`` + +- ``isSuperset(of:)-1mfg2`` +- ``isSuperset(of:)-5adir`` +- ``isSuperset(of:)-4y68t`` +- ``isSuperset(of:)-2m7mj`` + +- ``isStrictSubset(of:)-8m1z6`` +- ``isStrictSubset(of:)-3y2l1`` +- ``isStrictSubset(of:)-97rky`` +- ``isStrictSubset(of:)-p3zj`` + +- ``isStrictSuperset(of:)-6e5gm`` +- ``isStrictSuperset(of:)-735zn`` +- ``isStrictSuperset(of:)-26acy`` +- ``isStrictSuperset(of:)-5jmxx`` + +- ``isDisjoint(with:)-2cdg6`` +- ``isDisjoint(with:)-3klxy`` +- ``isDisjoint(with:)-4uidy`` +- ``isDisjoint(with:)-78a8w`` + +### Memory Management + +- ``reserveCapacity(_:)`` diff --git a/Sources/Collections/Collections.docc/Extensions/Deque.md b/Sources/Collections/Collections.docc/Extensions/Deque.md new file mode 100644 index 00000000..b314f955 --- /dev/null +++ b/Sources/Collections/Collections.docc/Extensions/Deque.md @@ -0,0 +1,10 @@ +# ``Collections/Deque`` + + + + + + + + +## Topics diff --git a/Sources/Collections/Collections.docc/Extensions/Heap.md b/Sources/Collections/Collections.docc/Extensions/Heap.md new file mode 100644 index 00000000..8c0136f1 --- /dev/null +++ b/Sources/Collections/Collections.docc/Extensions/Heap.md @@ -0,0 +1,10 @@ +# ``Collections/Heap`` + + + + + + + + +## Topics diff --git a/Sources/Collections/Collections.docc/Extensions/OrderedSet.UnorderedView.md b/Sources/Collections/Collections.docc/Extensions/OrderedSet.UnorderedView.md new file mode 100644 index 00000000..f3f89bfc --- /dev/null +++ b/Sources/Collections/Collections.docc/Extensions/OrderedSet.UnorderedView.md @@ -0,0 +1,65 @@ +# ``Collections/OrderedSet/UnorderedView`` + + + + + + + + +## Topics + +### Binary Set Operations + +- ``intersection(_:)-3q45l`` +- ``intersection(_:)-6ee3o`` + +- ``union(_:)-79uk3`` +- ``union(_:)-23dm1`` + +- ``subtracting(_:)-3ct1b`` +- ``subtracting(_:)-8e6mw`` + +- ``symmetricDifference(_:)-6aed7`` +- ``symmetricDifference(_:)-7r79p`` + +- ``formIntersection(_:)-4ow38`` +- ``formIntersection(_:)-80iht`` + +- ``formUnion(_:)-6ijb`` +- ``formUnion(_:)-8tuol`` + +- ``subtract(_:)-627eq`` +- ``subtract(_:)-4pjhu`` + +- ``formSymmetricDifference(_:)-8pkt5`` +- ``formSymmetricDifference(_:)-75z52`` + +### Binary Set Predicates + +- ``==(_:_:)`` + +- ``isSubset(of:)-n4t7`` +- ``isSubset(of:)-2dx31`` +- ``isSubset(of:)-801lo`` +- ``isSubset(of:)-952h5`` + +- ``isSuperset(of:)-4ea6h`` +- ``isSuperset(of:)-9t33p`` +- ``isSuperset(of:)-2vtig`` +- ``isSuperset(of:)-9krpz`` + +- ``isStrictSubset(of:)-33z0l`` +- ``isStrictSubset(of:)-9o6mg`` +- ``isStrictSubset(of:)-91par`` +- ``isStrictSubset(of:)-7n66e`` + +- ``isStrictSuperset(of:)-8pbce`` +- ``isStrictSuperset(of:)-89ig3`` +- ``isStrictSuperset(of:)-1e0xt`` +- ``isStrictSuperset(of:)-5dsfd`` + +- ``isDisjoint(with:)-7sbsg`` +- ``isDisjoint(with:)-3wuso`` +- ``isDisjoint(with:)-25vmx`` +- ``isDisjoint(with:)-8nfqs`` diff --git a/Sources/Collections/Collections.docc/Extensions/OrderedSet.md b/Sources/Collections/Collections.docc/Extensions/OrderedSet.md new file mode 100644 index 00000000..b4e7087a --- /dev/null +++ b/Sources/Collections/Collections.docc/Extensions/OrderedSet.md @@ -0,0 +1,143 @@ +# ``Collections/OrderedSet`` + + + + + + + + +## Topics + +### Creating a Set + +- ``init()`` +- ``init(_:)-5zktd`` +- ``init(_:)-3d7qr`` +- ``init(_:)-68j7`` +- ``init(_:)-8zm9d`` +- ``init(_:)-7rt2h`` +- ``init(_:)-8tli8`` +- ``init(_:)-2d3a9`` +- ``init(uncheckedUniqueElements:)`` +- ``init(minimumCapacity:persistent:)`` + +### Collection Views + +- ``UnorderedView`` +- ``unordered`` +- ``elements`` + +### Finding Elements + +- ``contains(_:)`` +- ``firstIndex(of:)`` +- ``lastIndex(of:)`` + +### Adding and Updating Elements + +- ``append(_:)`` +- ``append(contentsOf:)`` +- ``insert(_:at:)`` +- ``updateOrAppend(_:)`` +- ``updateOrInsert(_:at:)`` +- ``update(_:at:)`` + +### Removing Elements + +- ``filter(_:)`` +- ``removeAll(where:)`` +- ``remove(_:)`` +- ``remove(at:)`` +- ``removeAll(keepingCapacity:)`` +- ``removeFirst()`` +- ``removeLast()`` +- ``removeFirst(_:)`` +- ``removeLast(_:)`` +- ``removeSubrange(_:)-62u6a`` +- ``removeSubrange(_:)-2fqke`` + +### Combining Sets + +- ``intersection(_:)-4o09a`` +- ``intersection(_:)-9yzg3`` +- ``intersection(_:)-80md4`` + +- ``union(_:)-67y2h`` +- ``union(_:)-3lt5i`` +- ``union(_:)-2939h`` + +- ``subtracting(_:)-5graf`` +- ``subtracting(_:)-7kl8r`` +- ``subtracting(_:)-1gl4y`` + +- ``symmetricDifference(_:)-1810l`` +- ``symmetricDifference(_:)-8dvm6`` +- ``symmetricDifference(_:)-9huk7`` + +- ``formIntersection(_:)-43o1u`` +- ``formIntersection(_:)-2a4y4`` +- ``formIntersection(_:)-7odn2`` + +- ``formUnion(_:)-6pksr`` +- ``formUnion(_:)-3dkzw`` +- ``formUnion(_:)-59end`` + +- ``subtract(_:)-3b6nj`` +- ``subtract(_:)-9rtmd`` +- ``subtract(_:)-9wmg8`` + +- ``formSymmetricDifference(_:)-96csi`` +- ``formSymmetricDifference(_:)-2ll2z`` +- ``formSymmetricDifference(_:)-391sm`` + +### Comparing Sets + +- ``==(_:_:)`` +- ``isEqual(to:)-69p52`` +- ``isEqual(to:)-1xzfo`` +- ``isEqual(to:)-3ab2q`` + +- ``isSubset(of:)-ptij`` +- ``isSubset(of:)-3mw6r`` +- ``isSubset(of:)-8yb29`` +- ``isSubset(of:)-9hxl4`` + +- ``isSuperset(of:)-4rrsh`` +- ``isSuperset(of:)-2bbv8`` +- ``isSuperset(of:)-7xvog`` +- ``isSuperset(of:)-7oow7`` + +- ``isStrictSubset(of:)-8m21h`` +- ``isStrictSubset(of:)-9lv3x`` +- ``isStrictSubset(of:)-4efhn`` +- ``isStrictSubset(of:)-10abw`` + +- ``isStrictSuperset(of:)-7u97x`` +- ``isStrictSuperset(of:)-3kfwa`` +- ``isStrictSuperset(of:)-98d9s`` +- ``isStrictSuperset(of:)-5e6d5`` + +- ``isDisjoint(with:)-6vmoh`` +- ``isDisjoint(with:)-4tsmx`` +- ``isDisjoint(with:)-54iy6`` +- ``isDisjoint(with:)-7nqur`` + +### Reordering Elements + +- ``swapAt(_:_:)`` +- ``sort()`` +- ``sort(by:)`` +- ``reverse()`` +- ``shuffle()`` +- ``shuffle(using:)`` +- ``partition(by:)`` + +### Creating and Applying Differences + +- ``difference(from:)`` +- ``applying(_:)`` + +### Memory Management + +- ``reserveCapacity(_:)`` diff --git a/Sources/Collections/Collections.docc/Extensions/PersistentDictionary.md b/Sources/Collections/Collections.docc/Extensions/PersistentDictionary.md new file mode 100644 index 00000000..5a435a04 --- /dev/null +++ b/Sources/Collections/Collections.docc/Extensions/PersistentDictionary.md @@ -0,0 +1,75 @@ +# ``Collections/PersistentDictionary`` + + + + + + + + +## Topics + +### Collection Views + +- ``Keys-swift.struct`` +- ``Values-swift.struct`` +- ``keys-swift.property`` +- ``values-swift.property`` + +### Creating a Dictionary + +- ``init()`` +- ``init(_:)-7jshe`` +- ``init(_:)-8ls8p`` +- ``init(uniqueKeysWithValues:)-65ax0`` +- ``init(uniqueKeysWithValues:)-5ok18`` +- ``init(_:uniquingKeysWith:)-7fuzu`` +- ``init(_:uniquingKeysWith:)-4jee3`` +- ``init(grouping:by:)-8ntzv`` +- ``init(grouping:by:)-7cu86`` +- ``init(keys:valueGenerator:)`` + + +### Inspecting a Dictionary + +- ``isEmpty-65s43`` +- ``count-9cdqd`` + +### Accessing Keys and Values + +- ``subscript(_:)-g0oi`` +- ``subscript(_:default:)`` +- ``index(forKey:)`` + +### Adding or Updating Keys and Values + +- ``updateValue(_:forKey:)`` +- ``updateValue(forKey:with:)`` +- ``updateValue(forKey:default:with:)`` +- ``merge(_:uniquingKeysWith:)-853bf`` +- ``merge(_:uniquingKeysWith:)-19xxn`` +- ``merge(_:uniquingKeysWith:)-2osh`` +- ``merging(_:uniquingKeysWith:)-2a7cl`` +- ``merging(_:uniquingKeysWith:)-1tq3e`` +- ``merging(_:uniquingKeysWith:)-2kjqq`` + +### Removing Keys and Values + +- ``removeValue(forKey:)`` +- ``remove(at:)`` + +### Non-mutating Dictionary Operations + +- ``updatingValue(_:forKey:)`` +- ``removingValue(forKey:)`` + +### Comparing Dictionaries + +- ``==(_:_:)`` + +### Transforming a Dictionary + +- ``filter(_:)`` +- ``mapValues(_:)`` +- ``compactMapValues(_:)`` + diff --git a/Sources/Collections/Collections.docc/Extensions/PersistentSet.md b/Sources/Collections/Collections.docc/Extensions/PersistentSet.md new file mode 100644 index 00000000..09b23d5b --- /dev/null +++ b/Sources/Collections/Collections.docc/Extensions/PersistentSet.md @@ -0,0 +1,166 @@ +# ``Collections/PersistentSet`` + + + + +### Implementation Details + +`PersistentSet` and `PersistentDictionary` are based on a Swift adaptation +of the *Compressed Hash-Array Mapped Prefix Tree* (CHAMP) data structure. + +- Michael J Steindorfer and Jurgen J Vinju. Optimizing Hash-Array Mapped + Tries for Fast and Lean Immutable JVM Collections. In *Proc. + International Conference on Object-Oriented Programming, Systems, + Languages, and Applications,* pp. 783-800, 2015. + https://doi.org/10.1145/2814270.2814312 + +In this setup, the members of such a collection are organized into a tree +data structure based on their hash values. For example, assuming 16 bit hash +values sliced into 4-bit chunks, each node in the prefix tree would have +sixteen slots (one for each digit), each of which may contain a member, a +child node reference, or it may be empty. A `PersistentSet` containing the +tree items `Maximo`, `Julia` and `Don Pablo` (with hash values of `0x2B65`, +`0xA69F` and `0xADA1`, respectively) may be organized into a prefix tree of +two nodes: + +``` +┌0┬1┬2───────┬3┬4┬5┬6┬7┬8┬9┬A──┬B┬C┬D┬E┬F┐ +│ │ │ Maximo │ │ │ │ │ │ │ │ • │ │ │ │ │ │ +└─┴─┴────────┴─┴─┴─┴─┴─┴─┴─┴─┼─┴─┴─┴─┴─┴─┘ + ╎ + ╎ + ┌0┬1┬2┬3┬4┬5┬6───┴──┬7┬8┬9┬A┬B┬C┬D──────────┬E┬F┐ + │ │ │ │ │ │ │ Julia │ │ │ │ │ │ │ Don Pablo │ │ │ + └─┴─┴─┴─┴─┴─┴───────┴─┴─┴─┴─┴─┴─┴───────────┴─┴─┘ +``` + +The root node directly contains `Maximo`, because it is the only set member +whose hash value starts with `8`. However, the first digits of the hashes of +`Julia` and `Don Pablo` are both `A`, so these items reside in a separate +node, one level below the root. + +(To save space, nodes are actually stored in a more compact form, with just +enough space allocated to store their contents: empty slots do not take up +any room. Hence the term "compressed" in "Compressed Hash-Array Mapped +Prefix Tree".) + +The resulting tree structure lends itself well to sharing nodes across +multiple collection values. Inserting or removing an item in a completely +shared tree requires copying at most log(n) nodes -- every node along the +path to the item needs to be uniqued, but all other nodes can remain shared. +While the cost of copying this many nodes isn't trivial, it is dramatically +lower than the cost of having to copy the entire data structure, like the +standard `Set` has to do. + +When looking up a particular member, we descend from the root node, +following along the path specified by successive digits of the member's hash +value. As long as hash values are unique, we will either find the member +we're looking for, or we will know for sure that it does not exist in the +set. + +In practice, hash values aren't guaranteed to be unique though. Members with +conflicting hash values need to be collected in special collision nodes that +are able to grow as large as necessary to contain all colliding members that +share the same hash. Looking up a member in one of these nodes requires a +linear search, so it is crucial that such collisions do not happen often. + +As long as `Element` properly implements `Hashable`, lookup operations in a +`PersistentSet` are expected to be able to decide whether the set contains a +particular item by looking at no more than a constant number of items on +average -- typically they will need to compare against just one member. + + + +## Topics + +### Creating a Set + +- ``init()`` +- ``init(_:)-6nn9e`` +- ``init(_:)-6qbps`` +- ``init(_:)-30nei`` + +### Finding Elements + +- ``contains(_:)`` +- ``firstIndex(of:)`` +- ``lastIndex(of:)`` + +### Adding and Updating Elements + +- ``insert(_:)`` +- ``update(with:)`` +- ``update(_:at:)`` + +### Removing Elements + +- ``filter(_:)`` +- ``remove(_:)`` +- ``remove(at:)`` + +### Non-mutating Set Operations + +- ``inserting(_:)`` +- ``updating(with:)`` +- ``removing(_:)`` + +### Combining Sets + +- ``intersection(_:)-9dx2a`` +- ``intersection(_:)-5z4my`` +- ``intersection(_:)-1d4e0`` + +- ``union(_:)-1nk1t`` +- ``union(_:)-8otnp`` +- ``union(_:)-6eysm`` + +- ``subtracting(_:)-8sczx`` +- ``subtracting(_:)-2iv0a`` +- ``subtracting(_:)-63bfb`` + +- ``symmetricDifference(_:)-76bw`` +- ``symmetricDifference(_:)-92ha9`` +- ``symmetricDifference(_:)-1n89g`` + +- ``formIntersection(_:)-4s0od`` +- ``formIntersection(_:)-7dqfx`` +- ``formIntersection(_:)-8i59p`` + +- ``formUnion(_:)-68pog`` +- ``formUnion(_:)-82rrc`` +- ``formUnion(_:)-4r7qz`` + +- ``subtract(_:)-7rmd3`` +- ``subtract(_:)-47r93`` +- ``subtract(_:)-3v8ms`` + +- ``formSymmetricDifference(_:)-499uq`` +- ``formSymmetricDifference(_:)-8wue8`` +- ``formSymmetricDifference(_:)-4t8jr`` + +### Comparing Sets + +- ``==(_:_:)`` +- ``isEqual(to:)-3m3in`` +- ``isEqual(to:)-7mkn1`` +- ``isEqual(to:)-5px5r`` + +- ``isSubset(of:)-9mp7l`` +- ``isSubset(of:)-2jlh`` +- ``isSubset(of:)-8vn0j`` + +- ``isSuperset(of:)-5af8o`` +- ``isSuperset(of:)-6mvxj`` +- ``isSuperset(of:)-864jy`` + +- ``isStrictSubset(of:)-48nx2`` +- ``isStrictSubset(of:)-2j680`` +- ``isStrictSubset(of:)-1s6n9`` + +- ``isStrictSuperset(of:)-nd5j`` +- ``isStrictSuperset(of:)-5z263`` +- ``isStrictSuperset(of:)-ivbh`` + +- ``isDisjoint(with:)-12irx`` +- ``isDisjoint(with:)-1hhyf`` +- ``isDisjoint(with:)-61lde`` From d19fb14c46266a20cba9c5362923c6a076e74407 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 28 Oct 2022 18:18:39 -0700 Subject: [PATCH 39/39] [CMake] Update CMake configuration --- Sources/BitCollections/CMakeLists.txt | 1 + Sources/CMakeLists.txt | 2 +- Sources/Collections/CMakeLists.txt | 2 +- Sources/HeapModule/CMakeLists.txt | 11 ++++++----- Sources/OrderedCollections/CMakeLists.txt | 15 +++++++++++---- Sources/PersistentCollections/CMakeLists.txt | 1 + 6 files changed, 21 insertions(+), 11 deletions(-) diff --git a/Sources/BitCollections/CMakeLists.txt b/Sources/BitCollections/CMakeLists.txt index 2e9c3681..06a2e744 100644 --- a/Sources/BitCollections/CMakeLists.txt +++ b/Sources/BitCollections/CMakeLists.txt @@ -56,6 +56,7 @@ add_library(BitCollections "BitSet/BitSet+SetAlgebra subtracting.swift" "BitSet/BitSet+SetAlgebra symmetricDifference.swift" "BitSet/BitSet+SetAlgebra union.swift" + "BitSet/BitSet+Sorted Collection APIs.swift" "BitSet/BitSet.Counted.swift" "BitSet/BitSet.Index.swift" "BitSet/BitSet._UnsafeHandle.swift" diff --git a/Sources/CMakeLists.txt b/Sources/CMakeLists.txt index 5e48abb3..7db3a61b 100644 --- a/Sources/CMakeLists.txt +++ b/Sources/CMakeLists.txt @@ -7,8 +7,8 @@ Licensed under Apache License v2.0 with Runtime Library Exception See https://swift.org/LICENSE.txt for license information #]] -add_subdirectory(Collections) add_subdirectory(BitCollections) +add_subdirectory(Collections) add_subdirectory(DequeModule) add_subdirectory(HeapModule) add_subdirectory(OrderedCollections) diff --git a/Sources/Collections/CMakeLists.txt b/Sources/Collections/CMakeLists.txt index e2194389..2a948e7e 100644 --- a/Sources/Collections/CMakeLists.txt +++ b/Sources/Collections/CMakeLists.txt @@ -8,7 +8,7 @@ See https://swift.org/LICENSE.txt for license information #]] add_library(Collections - Collections.swift) + "Collections.swift") target_link_libraries(Collections PRIVATE BitCollections DequeModule diff --git a/Sources/HeapModule/CMakeLists.txt b/Sources/HeapModule/CMakeLists.txt index 4c10b091..9e0bb6da 100644 --- a/Sources/HeapModule/CMakeLists.txt +++ b/Sources/HeapModule/CMakeLists.txt @@ -8,11 +8,12 @@ See https://swift.org/LICENSE.txt for license information #]] add_library(HeapModule - _Node.swift - Heap.swift - Heap+ExpressibleByArrayLiteral.swift - Heap+Invariants.swift - Heap+UnsafeHandle.swift) + "_Node.swift" + "Heap.swift" + "Heap+Descriptions.swift" + "Heap+ExpressibleByArrayLiteral.swift" + "Heap+Invariants.swift" + "Heap+UnsafeHandle.swift") target_link_libraries(HeapModule PRIVATE _CollectionsUtilities) set_target_properties(HeapModule PROPERTIES diff --git a/Sources/OrderedCollections/CMakeLists.txt b/Sources/OrderedCollections/CMakeLists.txt index f1cd5271..5bae3f6b 100644 --- a/Sources/OrderedCollections/CMakeLists.txt +++ b/Sources/OrderedCollections/CMakeLists.txt @@ -16,13 +16,13 @@ add_library(OrderedCollections "HashTable/_Hashtable+Header.swift" "HashTable/_HashTable+Testing.swift" "HashTable/_HashTable+UnsafeHandle.swift" - "OrderedDictionary/OrderedDictionary.Elements.swift" "OrderedDictionary/OrderedDictionary.swift" "OrderedDictionary/OrderedDictionary+Codable.swift" "OrderedDictionary/OrderedDictionary+CustomReflectable.swift" "OrderedDictionary/OrderedDictionary+Deprecations.swift" "OrderedDictionary/OrderedDictionary+Descriptions.swift" - "OrderedDictionary/OrderedDictionary+Elements+SubSequence.swift" + "OrderedDictionary/OrderedDictionary+Elements.SubSequence.swift" + "OrderedDictionary/OrderedDictionary+Elements.swift" "OrderedDictionary/OrderedDictionary+Equatable.swift" "OrderedDictionary/OrderedDictionary+ExpressibleByDictionaryLiteral.swift" "OrderedDictionary/OrderedDictionary+Hashable.swift" @@ -33,7 +33,6 @@ add_library(OrderedCollections "OrderedDictionary/OrderedDictionary+Sendable.swift" "OrderedDictionary/OrderedDictionary+Sequence.swift" "OrderedDictionary/OrderedDictionary+Values.swift" - "OrderedSet/OrderedSet.swift" "OrderedSet/OrderedSet+Codable.swift" "OrderedSet/OrderedSet+CustomReflectable.swift" "OrderedSet/OrderedSet+Descriptions.swift" @@ -46,14 +45,21 @@ add_library(OrderedCollections "OrderedSet/OrderedSet+Invariants.swift" "OrderedSet/OrderedSet+Partial MutableCollection.swift" "OrderedSet/OrderedSet+Partial RangeReplaceableCollection.swift" + "OrderedSet/OrderedSet+Partial SetAlgebra formIntersection.swift" + "OrderedSet/OrderedSet+Partial SetAlgebra formSymmetricDifference.swift" + "OrderedSet/OrderedSet+Partial SetAlgebra formUnion.swift" + "OrderedSet/OrderedSet+Partial SetAlgebra intersection.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 subtract.swift" + "OrderedSet/OrderedSet+Partial SetAlgebra subtracting.swift" + "OrderedSet/OrderedSet+Partial SetAlgebra symmetricDifference.swift" + "OrderedSet/OrderedSet+Partial SetAlgebra union.swift" "OrderedSet/OrderedSet+Partial SetAlgebra+Basics.swift" - "OrderedSet/OrderedSet+Partial SetAlgebra+Operations.swift" "OrderedSet/OrderedSet+RandomAccessCollection.swift" "OrderedSet/OrderedSet+ReserveCapacity.swift" "OrderedSet/OrderedSet+Sendable.swift" @@ -61,6 +67,7 @@ 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/PersistentCollections/CMakeLists.txt b/Sources/PersistentCollections/CMakeLists.txt index eac88614..121e50fb 100644 --- a/Sources/PersistentCollections/CMakeLists.txt +++ b/Sources/PersistentCollections/CMakeLists.txt @@ -55,6 +55,7 @@ add_library(PersistentCollections "PersistentDictionary/PersistentDictionary+Equatable.swift" "PersistentDictionary/PersistentDictionary+ExpressibleByDictionaryLiteral.swift" "PersistentDictionary/PersistentDictionary+Filter.swift" + "PersistentDictionary/PersistentDictionary+Fluent Operations.swift" "PersistentDictionary/PersistentDictionary+Hashable.swift" "PersistentDictionary/PersistentDictionary+Initializers.swift" "PersistentDictionary/PersistentDictionary+Keys.swift"