diff --git a/Documentation/Internals/README.md b/Documentation/Internals/README.md index a5594c39..c8430661 100644 --- a/Documentation/Internals/README.md +++ b/Documentation/Internals/README.md @@ -10,13 +10,13 @@ For more information on our benchmarking tool, please see its dedicated package, ## Test Support Library -The package comes with a rich test support library in the [Sources/_CollectionsTestSupport](./Sources/_CollectionsTestSupport) directory. These were loosely adapted from the contents of the `StdlibUnittest*` modules in the [Swift compiler repository](https://github.com/apple/swift/tree/main/stdlib/private), with some custom additions. +The package comes with a rich test support library in the [Sources/_CollectionsTestSupport](../../Sources/_CollectionsTestSupport) directory. These were loosely adapted from the contents of the `StdlibUnittest*` modules in the [Swift compiler repository](https://github.com/apple/swift/tree/main/stdlib/private), with some custom additions. These components would likely be of interest to the wider Swift community, but they aren't yet stable enough (or documented enough) to publish them. Accordingly, these testing helpers are currently considered implementation details of this package, and are subject to change at whim. The test support library currently provides the following functionality: -- [`AssertionContexts`](./Sources/CollectionsTestSupport/AssertionContexts): Custom test assertions with support for keeping track of nested context information, including stopping execution when the current context matches a particular value. (Useful for debugging combinatorial tests.) +- [`AssertionContexts`](../../Sources/_CollectionsTestSupport/AssertionContexts): Custom test assertions with support for keeping track of nested context information, including stopping execution when the current context matches a particular value. (Useful for debugging combinatorial tests.)
Click here for a short demonstration @@ -62,7 +62,7 @@ The test support library currently provides the following functionality:
-- [`Combinatorics`](./Sources/CollectionsTestSupport/AssertionContexts/Combinatorics.swift): Basic support for exhaustive combinatorial testing. This allows us to easily verify that a collection operation works correctly on all possible instances up to a certain size, including behavioral variations such as unique/shared storage. +- [`Combinatorics`](../../Sources/_CollectionsTestSupport/AssertionContexts/Combinatorics.swift): Basic support for exhaustive combinatorial testing. This allows us to easily verify that a collection operation works correctly on all possible instances up to a certain size, including behavioral variations such as unique/shared storage. This file also contains a basic set of functions for executing the same test code for all subsets or all permutations of a given collection, with each iteration registered in the current test context, for easy reproduction of failed cases.
Click here for an example @@ -84,35 +84,35 @@ The test support library currently provides the following functionality: } } ``` - +
- -- [`ConformanceCheckers`](./Sources/CollectionsTestSupport/ConformanceCheckers): A set of generic, semi-automated protocol conformance tests for some Standard Library protocols. These can be used to easily validate the custom protocol conformances provided by this package. These checks aren't (can't be) complete -- but when used correctly, they are able to detect most accidental mistakes. + +- [`ConformanceCheckers`](../../Sources/_CollectionsTestSupport/ConformanceCheckers): A set of generic, semi-automated protocol conformance tests for some Standard Library protocols. These can be used to easily validate the custom protocol conformances provided by this package. These checks aren't (can't be) complete -- but when used correctly, they are able to detect most accidental mistakes. We currently have conformance checkers for the following protocols: - - [`Sequence`](./Sources/CollectionsTestSupport/ConformanceCheckers/CheckSequence.swift) - - [`Collection`](./Sources/CollectionsTestSupport/ConformanceCheckers/CheckCollection.swift) - - [`BidirectionalCollection`](./Sources/CollectionsTestSupport/ConformanceCheckers/CheckBidirectionalCollection.swift) - - [`Equatable`](./Sources/CollectionsTestSupport/ConformanceCheckers/CheckEquatable.swift) - - [`Hashable`](./Sources/CollectionsTestSupport/ConformanceCheckers/CheckHashable.swift) - - [`Comparable`](./Sources/CollectionsTestSupport/ConformanceCheckers/CheckComparable.swift) + - [`Sequence`](../../Sources/_CollectionsTestSupport/ConformanceCheckers/CheckSequence.swift) + - [`Collection`](../../Sources/_CollectionsTestSupport/ConformanceCheckers/CheckCollection.swift) + - [`BidirectionalCollection`](../../Sources/_CollectionsTestSupport/ConformanceCheckers/CheckBidirectionalCollection.swift) + - [`Equatable`](../../Sources/_CollectionsTestSupport/ConformanceCheckers/CheckEquatable.swift) + - [`Hashable`](../../Sources/_CollectionsTestSupport/ConformanceCheckers/CheckHashable.swift) + - [`Comparable`](../../Sources/_CollectionsTestSupport/ConformanceCheckers/CheckComparable.swift) -- [`MinimalTypes`](./Sources/CollectionsTestSupport/MinimalTypes): Minimally conforming implementations for standard protocols. These types conform to various standard protocols by implementing the requirements in as narrow-minded way as possible -- sometimes going to extreme lengths to, say, implement collection index invalidation logic in the most unhelpful way possible. +- [`MinimalTypes`](../../Sources/_CollectionsTestSupport/MinimalTypes): Minimally conforming implementations for standard protocols. These types conform to various standard protocols by implementing the requirements in as narrow-minded way as possible -- sometimes going to extreme lengths to, say, implement collection index invalidation logic in the most unhelpful way possible. - - [`MinimalSequence`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalSequence.swift) - - [`MinimalCollection`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalCollection.swift) - - [`MinimalBidirectionalCollection`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalBidirectionalCollection.swift) - - [`MinimalRandomAccessCollection`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalRandomAccessCollection.swift) - - [`MinimalMutableRandomAccessCollection`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalMutableRandomAccessCollection.swift) - - [`MinimalRangeReplaceableRandomAccessCollection`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalRangeReplaceableRandomAccessCollection.swift) - - [`MinimalMutableRangeReplaceableRandomAccessCollection`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalMutableRangeReplaceableRandomAccessCollection.swift) - - [`MinimalIterator`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalIterator.swift) - - [`MinimalIndex`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalIndex.swift) - - [`MinimalEncoder`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalEncoder.swift) - - [`MinimalDecoder`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalDecoder.swift) + - [`MinimalSequence`](../../Sources/_CollectionsTestSupport/MinimalTypes/MinimalSequence.swift) + - [`MinimalCollection`](../../Sources/_CollectionsTestSupport/MinimalTypes/MinimalCollection.swift) + - [`MinimalBidirectionalCollection`](../../Sources/_CollectionsTestSupport/MinimalTypes/MinimalBidirectionalCollection.swift) + - [`MinimalRandomAccessCollection`](../../Sources/_CollectionsTestSupport/MinimalTypes/MinimalRandomAccessCollection.swift) + - [`MinimalMutableRandomAccessCollection`](../../Sources/_CollectionsTestSupport/MinimalTypes/MinimalMutableRandomAccessCollection.swift) + - [`MinimalRangeReplaceableRandomAccessCollection`](../../Sources/_CollectionsTestSupport/MinimalTypes/MinimalRangeReplaceableRandomAccessCollection.swift) + - [`MinimalMutableRangeReplaceableRandomAccessCollection`](../../Sources/_CollectionsTestSupport/MinimalTypes/MinimalMutableRangeReplaceableRandomAccessCollection.swift) + - [`MinimalIterator`](../../Sources/_CollectionsTestSupport/MinimalTypes/MinimalIterator.swift) + - [`MinimalIndex`](../../Sources/_CollectionsTestSupport/MinimalTypes/MinimalIndex.swift) + - [`MinimalEncoder`](../../Sources/_CollectionsTestSupport/MinimalTypes/MinimalEncoder.swift) + - [`MinimalDecoder`](../../Sources/_CollectionsTestSupport/MinimalTypes/MinimalDecoder.swift) -- [`Utilities`](./Sources/CollectionsTestSupport/Utilities): Utility types. Wrapper types for boxed values, a simple deterministic random number generator, and a lifetime tracker for catching simple memory management issues such as memory leaks. (The [Address Sanitizer][asan] can be used to catch more serious problems.) +- [`Utilities`](../../Sources/_CollectionsTestSupport/Utilities): Utility types. Wrapper types for boxed values, a simple deterministic random number generator, and a lifetime tracker for catching simple memory management issues such as memory leaks. (The [Address Sanitizer][asan] can be used to catch more serious problems.) [asan]: https://developer.apple.com/documentation/xcode/diagnosing_memory_thread_and_crash_issues_early?language=objc diff --git a/Package.swift b/Package.swift index fdb3aa1b..fb610813 100644 --- a/Package.swift +++ b/Package.swift @@ -66,14 +66,13 @@ let package = Package( "PersistentCollections", "SortedCollections", ], - path: "Sources/Collections", exclude: ["CMakeLists.txt"], swiftSettings: settings), // Testing support module .target( name: "_CollectionsTestSupport", - dependencies: [], + dependencies: ["_CollectionsUtilities"], swiftSettings: settings, linkerSettings: [ .linkedFramework( @@ -88,17 +87,20 @@ let package = Package( .target( name: "_CollectionsUtilities", + exclude: ["CMakeLists.txt"], swiftSettings: settings), // BitSet, BitArray .target( name: "BitCollections", dependencies: ["_CollectionsUtilities"], - path: "Sources/BitCollections", + exclude: ["CMakeLists.txt"], swiftSettings: settings), .testTarget( name: "BitCollectionsTests", - dependencies: ["BitCollections", "_CollectionsTestSupport"], + dependencies: [ + "BitCollections", "_CollectionsTestSupport", "OrderedCollections" + ], swiftSettings: settings), // Deque @@ -114,14 +116,14 @@ let package = Package( // Heap .target( - name: "HeapModule", - dependencies: ["_CollectionsUtilities"], - exclude: ["CMakeLists.txt"], - swiftSettings: settings), + name: "HeapModule", + dependencies: ["_CollectionsUtilities"], + exclude: ["CMakeLists.txt"], + swiftSettings: settings), .testTarget( - name: "HeapTests", - dependencies: ["HeapModule"], - swiftSettings: settings), + name: "HeapTests", + dependencies: ["HeapModule", "_CollectionsTestSupport"], + swiftSettings: settings), // OrderedSet, OrderedDictionary .target( @@ -136,13 +138,14 @@ let package = Package( // PersistentSet, PersistentDictionary .target( - name: "PersistentCollections", - dependencies: ["_CollectionsUtilities"], - swiftSettings: settings), + name: "PersistentCollections", + dependencies: ["_CollectionsUtilities"], + exclude: ["CMakeLists.txt"], + swiftSettings: settings), .testTarget( - name: "PersistentCollectionsTests", - dependencies: ["PersistentCollections", "_CollectionsTestSupport"], - swiftSettings: settings), + name: "PersistentCollectionsTests", + dependencies: ["PersistentCollections", "_CollectionsTestSupport"], + swiftSettings: settings), // SortedSet, SortedDictionary .target( diff --git a/README.md b/README.md index 19d51d57..51009808 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ Read more about the package, and the intent behind it, in the [announcement on s The package currently provides the following implementations: -- [`BitSet`][BitSet] and [`BitArray`][BitArray], dynamic bit vectors. +- [`BitSet`][BitSet] and [`BitArray`][BitArray], dynamic bit collections. - [`Deque`][Deque], a double-ended queue backed by a ring buffer. Deques are range-replaceable, mutable, random-access collections. @@ -71,14 +71,14 @@ Note that contents of the `Tests`, `Utils` and `Benchmarks` subdirectories aren' Future minor versions of the package may update these rules as needed. -We'd like this package to quickly embrace Swift language and toolchain improvements that are relevant to its mandate. Accordingly, from time to time, we expect that new versions of this package will require clients to upgrade to a more recent Swift toolchain release. (This allows the package to make use of new language/stdlib features, build on compiler bug fixes, and adopt new package manager functionality as soon as they are available.) Requiring a new Swift release will only need a minor version bump. +We'd like this package to quickly embrace Swift language and toolchain improvements that are relevant to its mandate. Accordingly, from time to time, new versions of this package require clients to upgrade to a more recent Swift toolchain release. (This allows the package to make use of new language/stdlib features, build on compiler bug fixes, and adopt new package manager functionality as soon as they are available.) Patch (i.e., bugfix) releases will not increase the required toolchain version, but any minor (i.e., new feature) release may do so. The following table maps existing package releases to their minimum required Swift toolchain release: -| Package version | Swift version | -|---|---|---| -| swift-collections 1.0.x | >= Swift 5.3 | -| swift-collections 1.1.x | >= Swift 5.5 | +| Package version | Swift version | Xcode release | +| ----------------------- | ------------- | ------------- | +| swift-collections 1.0.x | >= Swift 5.3 | >= Xcode 12 | +| swift-collections 1.1.x | >= Swift 5.5 | >= Xcode 13 | (Note: the package has no minimum deployment target, so while it does require clients to use a recent Swift toolchain to build it, the code itself is able to run on any OS release that supports running Swift code.) @@ -145,11 +145,20 @@ By submitting a pull request, you represent that you have the right to license y #### Proposing the addition of a new data structure -1. Start a topic on the [forum], explaining why you believe it would be important to implement the data structure. This way we can figure out if it would be right for the package, discuss implementation strategies, and plan to allocate capacity to help. -2. When maintainers agreed to your implementation plan, start work on it, and submit a PR with your implementation as soon as you have something that's ready to show! We'd love to get involved as early as you like. -3. Participate in the review discussion, and adapt the code accordingly. Sometimes we may need to go through several revisions! This is fine -- it makes the end result that much better. -3. When there is a consensus that the feature is ready, and the implementation is fully tested and documented, the PR will be merged by a maintainer. -4. Celebrate! You've achieved something great! +We intend this package to collect generally useful data structures -- the ones that ought to be within easy reach of every Swift engineer's basic toolbox. The implementations we ship need to be of the highest technical quality, polished to the same shine as anything that gets included in the Swift Standard Library. (The only real differences are that this package isn't under the formal Swift Evolution process, and its code isn't ABI stable.) + +Accordingly, adding a new data structure to this package is not an easy or quick process, and not all useful data structures are going to be a good fit. + +If you have an idea for a data structure that might make a good addition to this package, please start a topic on the [forum], explaining why you believe it would be important to implement it. This way we can figure out if it would be right for the package, discuss implementation strategies, and plan to allocate capacity to help. + +Not all data structures will reach a high enough level of usefulness to ship in this package -- those that have a more limited audience might work better as a standalone package. Of course, reasonable people might disagree on the importance of including any particular data structure; but at the end of the day, the decision whether to take an implementation is up to the maintainers of this package. + +If maintainers have agreed that your implementation would likely make a good addition, then it's time to start work on it. Submit a PR with your implementation as soon as you have something that's ready to show! We'd love to get involved as early as you like. Historically, the best additions resulted from close work between the contributor and a package maintainer. + +Participate in the review discussion, and adapt code accordingly. Sometimes we may need to go through several revisions over multiple months! This is fine -- it makes the end result that much better. When there is a consensus that the feature is ready, and the implementation is fully tested and documented, the PR will be merged by a maintainer. This is good time for a small celebration -- merging is a good indicator that the addition will ship at some point. + +Historically, PRs adding a new data structure have typically been merged to a new feature branch rather than directly to a release branch or `main`, and there was an extended amount of time between the initial merge and the tag that shipped the new feature. Nobody likes to wait, but getting a new data structure implementation from a state that was ready to merge to a state that's ready to ship is actually quite difficult work, and it takes maintainer time and effort that needs to be scheduled in advance. The closer an implementation is to the coding conventions and performance baseline of the Standard Library, the shorter this wait is likely to become, and the fewer changes there will be between merging and shipping. + ### Code of Conduct diff --git a/Sources/BitCollections/BitArray/BitArray+Invariants.swift b/Sources/BitCollections/BitArray/BitArray+Invariants.swift index 561e909f..d194ea0b 100644 --- a/Sources/BitCollections/BitArray/BitArray+Invariants.swift +++ b/Sources/BitCollections/BitArray/BitArray+Invariants.swift @@ -9,7 +9,19 @@ // //===----------------------------------------------------------------------===// +import _CollectionsUtilities + extension BitArray { + /// True if consistency checking is enabled in the implementation of this + /// type, false otherwise. + /// + /// Documented performance promises are null and void when this property + /// returns true -- for example, operations that are documented to take + /// O(1) time might take O(*n*) time, or worse. + public static var _isConsistencyCheckingEnabled: Bool { + _isCollectionsInternalCheckingEnabled + } + #if COLLECTIONS_INTERNAL_CHECKS @inline(never) @_effects(releasenone) diff --git a/Sources/BitCollections/BitSet/BitSet+Equatable.swift b/Sources/BitCollections/BitSet/BitSet+Equatable.swift index d4323b24..ce81333f 100644 --- a/Sources/BitCollections/BitSet/BitSet+Equatable.swift +++ b/Sources/BitCollections/BitSet/BitSet+Equatable.swift @@ -13,8 +13,13 @@ extension BitSet: Equatable { /// Returns a Boolean value indicating whether two values are equal. Two /// bit sets are considered equal if they contain the same elements. /// - /// - Complexity: O(*max*), where *max* is value of the largest member of either set. + /// - Note: This simply forwards to the ``isEqual(to:)-5zfpo`` method. + /// That method has additional overloads that can be used to compare + /// bit sets with additional types. + /// + /// - Complexity: O(*max*), where *max* is value of the largest member of + /// either set. public static func ==(left: Self, right: Self) -> Bool { - left._storage == right._storage + left.isEqual(to: right) } } diff --git a/Sources/BitCollections/BitSet/BitSet+Extras.swift b/Sources/BitCollections/BitSet/BitSet+Extras.swift index 2f40b7e3..a7ce8fca 100644 --- a/Sources/BitCollections/BitSet/BitSet+Extras.swift +++ b/Sources/BitCollections/BitSet/BitSet+Extras.swift @@ -11,6 +11,8 @@ import _CollectionsUtilities +extension BitSet: _UniqueCollection {} + extension BitSet { /// Creates a new empty bit set with enough storage capacity to store values /// up to the given maximum value without reallocating storage. @@ -163,12 +165,6 @@ extension BitSet { return Int(bitPattern: index._value) } - /// Returns the current set (already sorted). - /// - /// - Complexity: O(1) - public func sorted() -> BitSet { self } - - /// Returns a new bit set containing the elements of the set that satisfy the /// given predicate. /// diff --git a/Sources/BitCollections/BitSet/BitSet+Invariants.swift b/Sources/BitCollections/BitSet/BitSet+Invariants.swift index 1a7b4bf8..c11ecf2b 100644 --- a/Sources/BitCollections/BitSet/BitSet+Invariants.swift +++ b/Sources/BitCollections/BitSet/BitSet+Invariants.swift @@ -9,7 +9,19 @@ // //===----------------------------------------------------------------------===// +import _CollectionsUtilities + extension BitSet { + /// True if consistency checking is enabled in the implementation of this + /// type, false otherwise. + /// + /// Documented performance promises are null and void when this property + /// returns true -- for example, operations that are documented to take + /// O(1) time might take O(*n*) time, or worse. + public static var _isConsistencyCheckingEnabled: Bool { + _isCollectionsInternalCheckingEnabled + } + #if COLLECTIONS_INTERNAL_CHECKS @inline(never) @_effects(releasenone) diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra basics.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra basics.swift index 2c4adb30..41237e13 100644 --- a/Sources/BitCollections/BitSet/BitSet+SetAlgebra basics.swift +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra basics.swift @@ -10,6 +10,14 @@ //===----------------------------------------------------------------------===// extension BitSet { + /// Returns a Boolean value that indicates whether the given element exists + /// in the set. + /// + /// - Parameter element: An element to look for in the set. + /// + /// - Returns: `true` if `member` exists in the set; otherwise, `false`. + /// + /// - Complexity: O(1) @usableFromInline internal func _contains(_ member: UInt) -> Bool { _read { $0.contains(member) } @@ -30,10 +38,27 @@ extension BitSet { } extension BitSet { + /// Insert the given element in the set if it is not already present. + /// + /// If an element equal to `newMember` is already contained in the set, this + /// method has no effect. + /// + /// If `newMember` was not already a member, it gets inserted into the set. + /// + /// - Parameter newMember: An element to insert into the set. + /// + /// - Returns: True if `newMember` was not contained in the + /// set, false otherwise. + /// + /// - Complexity: O(1) if the set is a unique value (with no other copies), + /// and the inserted value is not greater than the largest value currently + /// contained in the set (named *max*). Otherwise the complexity is + /// O(max(`newMember`, *max*)). @discardableResult - public mutating func _insert(_ i: UInt) -> Bool { - _ensureCapacity(forValue: i) - return _update { $0.insert(i) } + @usableFromInline + internal mutating func _insert(_ newMember: UInt) -> Bool { + _ensureCapacity(forValue: newMember) + return _update { $0.insert(newMember) } } /// Inserts the given element in the set if it is not already present. diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isDisjoint.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isDisjoint.swift index 0fd93d97..b92486dc 100644 --- a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isDisjoint.swift +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isDisjoint.swift @@ -36,6 +36,39 @@ extension BitSet { } } + /// Returns a Boolean value that indicates whether a bit set has no members + /// in common with the given counted bit set. + /// + /// let a: BitSet = [1, 2, 3, 4] + /// let b: BitSet.Counted = [5, 6] + /// a.isDisjoint(with: b) // true + /// + /// - Parameter other: A counted bit set. + /// + /// - Returns: `true` if `self` has no elements in common with `other`; + /// otherwise, `false`. + /// + /// - Complexity: O(*max*), where *max* is the largest item in either input. + public func isDisjoint(with other: BitSet.Counted) -> Bool { + self.isDisjoint(with: other._bits) + } + + /// Returns a Boolean value that indicates whether the set has no members in + /// common with the given range of integers. + /// + /// let a: BitSet = [1, 2, 3, 4] + /// a.isDisjoint(with: -10 ..< 0) // true + /// + /// - Parameter other: A range of arbitrary integers. + /// + /// - Returns: `true` if `self` has no elements in common with `other`; + /// otherwise, `false`. + /// + /// - Complexity: O(*max*), where *max* is the largest item in `self`. + public func isDisjoint(with other: Range) -> Bool { + _read { $0.isDisjoint(with: other._clampedToUInt()) } + } + /// Returns a Boolean value that indicates whether the set has no members in /// common with the given sequence of integers. /// @@ -68,24 +101,4 @@ extension BitSet { } return true } - - public func isDisjoint(with other: BitSet.Counted) -> Bool { - self.isDisjoint(with: other._bits) - } - - /// Returns a Boolean value that indicates whether the set has no members in - /// common with the given range of integers. - /// - /// let a: BitSet = [1, 2, 3, 4] - /// a.isDisjoint(with: -10 ..< 0) // true - /// - /// - Parameter other: A range of arbitrary integers. - /// - /// - Returns: `true` if `self` has no elements in common with `other`; - /// otherwise, `false`. - /// - /// - Complexity: O(*max*), where *max* is the largest item in `self`. - public func isDisjoint(with other: Range) -> Bool { - _read { $0.isDisjoint(with: other._clampedToUInt()) } - } } diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isEqual.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isEqual.swift new file mode 100644 index 00000000..04e58099 --- /dev/null +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isEqual.swift @@ -0,0 +1,105 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +import _CollectionsUtilities + +// FIXME: These are non-standard extensions generalizing ==. +extension BitSet { + /// Returns a Boolean value indicating whether two bit sets are equal. Two + /// bit sets are considered equal if they contain the same elements. + /// + /// - Complexity: O(*max*), where *max* is value of the largest member of + /// either set. + public func isEqual(to other: Self) -> Bool { + self._storage == other._storage + } + + /// Returns a Boolean value indicating whether a bit set is equal to a range + /// of integers, i.e., whether they contain the same values. + /// + /// - Complexity: O(min(*max*, `other.upperBound`), where *max* is the largest + /// member of `self`. + public func isEqual(to other: Range) -> Bool { + guard let other = other._toUInt() else { return false } + return _read { $0.isEqual(to: other) } + } + + /// Returns a Boolean value indicating whether a bit set is equal to a counted + /// bit set, i.e., whether they contain the same values. + /// + /// - Complexity: O(*max*), where *max* is + public func isEqual(to other: BitSet.Counted) -> Bool { + self.isEqual(to: other._bits) + } + + /// Returns a Boolean value indicating whether this bit set contains the same + /// elements as the given `other` sequence. + /// + /// Duplicate items in `other` do not prevent it from comparing equal to + /// `self`. + /// + /// let bits: BitSet = [0, 1, 5, 6] + /// let other = [5, 5, 0, 1, 1, 6, 5, 0, 1, 6, 6, 5] + /// + /// bits.isEqual(to: other) // true + /// + /// - Complexity: O(*n*), where *n* is the number of items in `other`. + public func isEqual(to other: S) -> Bool where S.Element == Int { + if S.self == Self.self { + return isEqual(to: other as! Self) + } + if S.self == BitSet.Counted.self { + return isEqual(to: other as! BitSet.Counted) + } + if S.self == Range.self { + return isEqual(to: other as! Range) + } + + if self.isEmpty { + return other.allSatisfy { _ in false } + } + + if other is _UniqueCollection { + // We don't need to create a temporary set. + guard other.underestimatedCount <= self.count else { return false } + var seen = 0 + for item in other { + guard let item = UInt(exactly: item) else { return false } + guard self._contains(item) else { return false} + seen &+= 1 + } + precondition( + seen <= self.count, + // Otherwise other.underestimatedCount != other.count + "Invalid Collection '\(S.self)' (bad underestimatedCount)") + return seen == self.count + } + + var seen: BitSet? = BitSet(reservingCapacity: self.max()!) + var it = other.makeIterator() + while let item = it.next() { + guard let item = UInt(exactly: item) else { return false } + guard self._contains(item) else { return false} + seen!._insert(item) // Ignore dupes + if seen!.count == self.count { + // We've seen them all. Stop further accounting. + seen = nil + break + } + } + guard seen == nil else { return false } + while let item = it.next() { + guard let item = UInt(exactly: item) else { return false } + guard self._contains(item) else { return false} + } + return true + } +} diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSubset.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSubset.swift index 9838f442..576ada89 100644 --- a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSubset.swift +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSubset.swift @@ -50,6 +50,45 @@ extension BitSet { } } + /// Returns a Boolean value that indicates whether this bit set is a strict + /// subset of the given set. + /// + /// Set *A* is a strict subset of another set *B* if every member of *A* is + /// also a member of *B* and *B* contains at least one element that is not a + /// member of *A*. + /// + /// - Parameter other: A counted bit set. + /// + /// - Returns: `true` if the set is a strict subset of `other`; + /// otherwise, `false`. + /// + /// - Complexity: O(*max*), where *max* is the largest item in `self`. + public func isStrictSubset(of other: BitSet.Counted) -> Bool { + isStrictSubset(of: other._bits) + } + + /// Returns a Boolean value that indicates whether this set is a strict + /// subset of the given set. + /// + /// Set *A* is a strict subset of another set *B* if every member of *A* is + /// also a member of *B* and *B* contains at least one element that is not a + /// member of *A*. + /// + /// let b: BitSet = [0, 1, 2] + /// let c: BitSet = [2, 3, 4] + /// b.isStrictSubset(of: -10 ..< 4) // true + /// c.isStrictSubset(of: -10 ..< 4) // false + /// + /// - Parameter other: An arbitrary range of integers. + /// + /// - Returns: `true` if the set is a strict subset of `other`; + /// otherwise, `false`. + /// + /// - Complexity: O(*max*), where *max* is the largest item in `self`. + public func isStrictSubset(of other: Range) -> Bool { + isSubset(of: other) && !isSuperset(of: other) + } + /// Returns a Boolean value that indicates whether this bit set is a strict /// subset of the values in a given sequence of integers. /// @@ -115,30 +154,4 @@ extension BitSet { return false } } - - public func isStrictSubset(of other: BitSet.Counted) -> Bool { - isStrictSubset(of: other._bits) - } - - /// Returns a Boolean value that indicates whether this set is a strict - /// subset of the given set. - /// - /// Set *A* is a strict subset of another set *B* if every member of *A* is - /// also a member of *B* and *B* contains at least one element that is not a - /// member of *A*. - /// - /// let b: BitSet = [0, 1, 2] - /// let c: BitSet = [2, 3, 4] - /// b.isStrictSubset(of: -10 ..< 4) // true - /// c.isStrictSubset(of: -10 ..< 4) // false - /// - /// - Parameter other: An arbitrary range of integers. - /// - /// - Returns: `true` if the set is a strict subset of `other`; - /// otherwise, `false`. - /// - /// - Complexity: O(*max*), where *max* is the largest item in `self`. - public func isStrictSubset(of other: Range) -> Bool { - isSubset(of: other) && !isSuperset(of: other) - } } diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSuperset.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSuperset.swift index aa9c95a9..f6ab0e6a 100644 --- a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSuperset.swift +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSuperset.swift @@ -33,6 +33,48 @@ extension BitSet { other.isStrictSubset(of: self) } + /// Returns a Boolean value that indicates whether this set is a strict + /// superset of another set. + /// + /// Set *A* is a strict superset of another set *B* if every member of *B* is + /// also a member of *A* and *A* contains at least one element that is *not* + /// a member of *B*. + /// + /// - Parameter other: A counted bit set. + /// + /// - Returns: `true` if the set is a superset of `other`; otherwise, `false`. + /// + /// - Complexity: O(*max*), where *max* is the largest item in `other`. + public func isStrictSuperset(of other: BitSet.Counted) -> Bool { + other._bits.isStrictSubset(of: self) + } + + /// Returns a Boolean value that indicates whether this set is a superset of + /// a given range of integers. + /// + /// Set *A* is a superset of another set *B* if every member of *B* is also a + /// member of *A*. + /// + /// let a: BitSet = [0, 1, 2, 3, 4, 10] + /// a.isSuperset(of: 0 ..< 4) // true + /// a.isSuperset(of: -10 ..< 4) // false + /// + /// - Parameter other: An arbitrary range of integers. + /// + /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. + /// + /// - Complexity: O(`range.count`) + public func isStrictSuperset(of other: Range) -> Bool { + if other.isEmpty { return !isEmpty } + if isEmpty { return false } + if self[members: .. Bool { - other._bits.isStrictSubset(of: self) - } - - /// Returns a Boolean value that indicates whether this set is a superset of - /// a given range of integers. - /// - /// Set *A* is a superset of another set *B* if every member of *B* is also a - /// member of *A*. - /// - /// let a: BitSet = [0, 1, 2, 3, 4, 10] - /// a.isSuperset(of: 0 ..< 4) // true - /// a.isSuperset(of: -10 ..< 4) // false - /// - /// - Parameter other: An arbitrary range of integers. - /// - /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. - /// - /// - Complexity: O(`range.count`) - public func isStrictSuperset(of other: Range) -> Bool { - if other.isEmpty { return !isEmpty } - if isEmpty { return false } - if self[members: .. Bool { + self.isSubset(of: other._bits) + } + + /// Returns a Boolean value that indicates whether this set is a subset of + /// the given range of integers. + /// + /// Set *A* is a subset of another set *B* if every member of *A* is also a + /// member of *B*. + /// + /// let b: BitSet = [0, 1, 2] + /// let c: BitSet = [2, 3, 4] + /// b.isSubset(of: -10 ..< 4) // true + /// c.isSubset(of: -10 ..< 4) // false + /// + /// - Parameter other: An arbitrary range of integers. + /// + /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. + /// + /// - Complexity: O(*max*), where *max* is the largest item in `self`. + public func isSubset(of other: Range) -> Bool { + _read { $0.isSubset(of: other._clampedToUInt()) } + } + /// Returns a Boolean value that indicates whether this set is a subset of /// the values in a given sequence of integers. /// @@ -77,7 +112,18 @@ extension BitSet { if S.self == Range.self { return self.isSubset(of: other as! Range) } - if _storage.isEmpty { return true } + + var it = self.makeIterator() + guard let first = it.next() else { return true } + if let match = other._customContainsEquatableElement(first) { + // Fast path: the sequence has fast containment checks. + guard match else { return false } + while let item = it.next() { + guard other.contains(item) else { return false } + } + return true + } + var t = self for i in other { guard let i = UInt(exactly: i) else { continue } @@ -86,28 +132,4 @@ extension BitSet { assert(!t.isEmpty) return false } - - public func isSubset(of other: BitSet.Counted) -> Bool { - self.isSubset(of: other._bits) - } - - /// Returns a Boolean value that indicates whether this set is a subset of - /// the given range of integers. - /// - /// Set *A* is a subset of another set *B* if every member of *A* is also a - /// member of *B*. - /// - /// let b: BitSet = [0, 1, 2] - /// let c: BitSet = [2, 3, 4] - /// b.isSubset(of: -10 ..< 4) // true - /// c.isSubset(of: -10 ..< 4) // false - /// - /// - Parameter other: An arbitrary range of integers. - /// - /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. - /// - /// - Complexity: O(*max*), where *max* is the largest item in `self`. - public func isSubset(of other: Range) -> Bool { - _read { $0.isSubset(of: other._clampedToUInt()) } - } } diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isSuperset.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isSuperset.swift index 4b286a1c..cc85e2b2 100644 --- a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isSuperset.swift +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isSuperset.swift @@ -33,43 +33,16 @@ extension BitSet { } /// Returns a Boolean value that indicates whether this set is a superset of - /// the values in a given sequence of integers. + /// the given set. /// /// Set *A* is a superset of another set *B* if every member of *B* is also a /// member of *A*. /// - /// let a = [1, 2, 3] - /// let b: BitSet = [0, 1, 2, 3, 4] - /// let c: BitSet = [0, 1, 2] - /// b.isSuperset(of: a) // true - /// c.isSuperset(of: a) // false + /// - Parameter other: A counted bit set. /// - /// - Parameter other: A sequence of arbitrary integers. + /// - Returns: `true` if the set is a superset of `other`; otherwise, `false`. /// - /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. - /// - /// - Complexity: The same as the complexity of iterating over all elements - /// in `other`. - @inlinable - public func isSuperset(of other: S) -> Bool - where S.Element == Int - { - if S.self == BitSet.self { - return self.isSuperset(of: other as! BitSet) - } - if S.self == BitSet.Counted.self { - return self.isSuperset(of: other as! BitSet.Counted) - } - if S.self == Range.self { - return self.isSuperset(of: other as! Range) - } - for i in other { - guard let i = UInt(exactly: i) else { return false } - if !_contains(i) { return false } - } - return true - } - + /// - Complexity: O(*max*), where *max* is the largest item in `other`. public func isSuperset(of other: BitSet.Counted) -> Bool { isSuperset(of: other._bits) } @@ -94,4 +67,43 @@ extension BitSet { guard let r = other._toUInt() else { return false } return _read { $0.isSuperset(of: r) } } + + /// Returns a Boolean value that indicates whether this set is a superset of + /// the values in a given sequence of integers. + /// + /// Set *A* is a superset of another set *B* if every member of *B* is also a + /// member of *A*. + /// + /// let a = [1, 2, 3] + /// let b: BitSet = [0, 1, 2, 3, 4] + /// let c: BitSet = [0, 1, 2] + /// b.isSuperset(of: a) // true + /// c.isSuperset(of: a) // false + /// + /// - Parameter other: A sequence of arbitrary integers, some of whose members + /// may appear more than once. (Duplicate items are ignored.) + /// + /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. + /// + /// - Complexity: The same as the complexity of iterating over all elements + /// in `other`. + @inlinable + public func isSuperset(of other: S) -> Bool + where S.Element == Int + { + if S.self == BitSet.self { + return self.isSuperset(of: other as! BitSet) + } + if S.self == BitSet.Counted.self { + return self.isSuperset(of: other as! BitSet.Counted) + } + if S.self == Range.self { + return self.isSuperset(of: other as! Range) + } + for i in other { + guard let i = UInt(exactly: i) else { return false } + if !_contains(i) { return false } + } + return true + } } diff --git a/Sources/BitCollections/BitSet/BitSet+Sorted Collection APIs.swift b/Sources/BitCollections/BitSet/BitSet+Sorted Collection APIs.swift new file mode 100644 index 00000000..191afcf7 --- /dev/null +++ b/Sources/BitCollections/BitSet/BitSet+Sorted Collection APIs.swift @@ -0,0 +1,47 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +import _CollectionsUtilities + +extension BitSet: _SortedCollection { + /// Returns the current set (already sorted). + /// + /// - Complexity: O(1) + public func sorted() -> BitSet { self } + + /// Returns the minimum element in this set. + /// + /// Bit sets are sorted, so the minimum element is always at the first + /// position in the set. + /// + /// - Returns: The bit set's minimum element. If the sequence has no + /// elements, returns `nil`. + /// + /// - Complexity: O(1) + @warn_unqualified_access + public func min() -> Element? { + first + } + + /// Returns the maximum element in this set. + /// + /// Bit sets are sorted, so the maximum element is always at the last + /// position in the set. + /// + /// - Returns: The bit set's maximum element. If the sequence has no + /// elements, returns `nil`. + /// + /// - Complexity: O(1) + @warn_unqualified_access + public func max() -> Element? { + last + } +} diff --git a/Sources/BitCollections/BitSet/BitSet.Counted.swift b/Sources/BitCollections/BitSet/BitSet.Counted.swift index 19fffc57..7129d20c 100644 --- a/Sources/BitCollections/BitSet/BitSet.Counted.swift +++ b/Sources/BitCollections/BitSet/BitSet.Counted.swift @@ -9,6 +9,8 @@ // //===----------------------------------------------------------------------===// +import _CollectionsUtilities + extension BitSet { public struct Counted { @usableFromInline @@ -42,6 +44,8 @@ extension BitSet.Counted { #endif // COLLECTIONS_INTERNAL_CHECKS } +extension BitSet.Counted: _UniqueCollection {} + extension BitSet.Counted { public init() { self.init(BitSet()) @@ -95,7 +99,7 @@ extension BitSet { self = bits._bits } - var counted: BitSet.Counted { + public var counted: BitSet.Counted { get { BitSet.Counted(_bits: self, count: self.count) } diff --git a/Sources/BitCollections/BitSet/BitSet._UnsafeHandle.swift b/Sources/BitCollections/BitSet/BitSet._UnsafeHandle.swift index 68414b7f..a73a72a4 100644 --- a/Sources/BitCollections/BitSet/BitSet._UnsafeHandle.swift +++ b/Sources/BitCollections/BitSet/BitSet._UnsafeHandle.swift @@ -623,4 +623,33 @@ extension BitSet._UnsafeHandle { let uw = _Word(upTo: upper.bit) return _words[upper.word].intersection(uw) == uw } + + internal func isEqual(to range: Range) -> Bool { + if range.isEmpty { return self.isEmpty } + let r = range.clamped(to: 0 ..< UInt(capacity)) + guard r == range else { return false } + + let lower = Index(range.lowerBound) + let upper = Index(range.upperBound) + + guard upper.word == wordCount &- 1 else { return false } + + for w in 0 ..< lower.word { + guard _words[w].isEmpty else { return false } + } + + if lower.word == upper.word { + let w = _Word(from: lower.bit, to: upper.bit) + return _words[lower.word] == w + } + let lw = _Word(upTo: lower.bit).complement() + guard _words[lower.word] == lw else { return false } + + for w in lower.word + 1 ..< upper.word { + guard _words[w].isFull else { return false } + } + + let uw = _Word(upTo: upper.bit) + return _words[upper.word] == uw + } } diff --git a/Sources/BitCollections/CMakeLists.txt b/Sources/BitCollections/CMakeLists.txt index e7f62c45..2e9c3681 100644 --- a/Sources/BitCollections/CMakeLists.txt +++ b/Sources/BitCollections/CMakeLists.txt @@ -47,6 +47,7 @@ add_library(BitCollections "BitSet/BitSet+SetAlgebra formUnion.swift" "BitSet/BitSet+SetAlgebra intersection.swift" "BitSet/BitSet+SetAlgebra isDisjoint.swift" + "BitSet/BitSet+SetAlgebra isEqual.swift" "BitSet/BitSet+SetAlgebra isStrictSubset.swift" "BitSet/BitSet+SetAlgebra isStrictSuperset.swift" "BitSet/BitSet+SetAlgebra isSubset.swift" diff --git a/Sources/DequeModule/Deque+Testing.swift b/Sources/DequeModule/Deque+Testing.swift index 2c1a0e0a..bbc1fbf9 100644 --- a/Sources/DequeModule/Deque+Testing.swift +++ b/Sources/DequeModule/Deque+Testing.swift @@ -15,6 +15,12 @@ import _CollectionsUtilities // testing. extension Deque { + /// True if consistency checking is enabled in the implementation of this + /// type, false otherwise. + /// + /// Documented performance promises are null and void when this property + /// returns true -- for example, operations that are documented to take + /// O(1) time might take O(*n*) time, or worse. public static var _isConsistencyCheckingEnabled: Bool { _isCollectionsInternalCheckingEnabled } diff --git a/Sources/HeapModule/Heap+Invariants.swift b/Sources/HeapModule/Heap+Invariants.swift index ab1d891a..12e9192a 100644 --- a/Sources/HeapModule/Heap+Invariants.swift +++ b/Sources/HeapModule/Heap+Invariants.swift @@ -12,11 +12,17 @@ import _CollectionsUtilities extension Heap { + /// True if consistency checking is enabled in the implementation of this + /// type, false otherwise. + /// + /// Documented performance promises are null and void when this property + /// returns true -- for example, operations that are documented to take + /// O(1) time might take O(*n*) time, or worse. public static var _isConsistencyCheckingEnabled: Bool { _isCollectionsInternalCheckingEnabled } - #if COLLECTIONS_INTERNAL_CHECKSx + #if COLLECTIONS_INTERNAL_CHECKS /// Visits each item in the heap in depth-first order, verifying that the /// contents satisfy the min-max heap property. @inlinable diff --git a/Sources/HeapModule/Heap+UnsafeHandle.swift b/Sources/HeapModule/Heap+UnsafeHandle.swift index d20f10c0..601a5ec6 100644 --- a/Sources/HeapModule/Heap+UnsafeHandle.swift +++ b/Sources/HeapModule/Heap+UnsafeHandle.swift @@ -352,20 +352,31 @@ extension Heap._UnsafeHandle { extension Heap._UnsafeHandle { @inlinable internal func heapify() { + // This is Floyd's linear-time heap construction algorithm. + // (https://en.wikipedia.org/wiki/Heapsort#Floyd's_heap_construction). + // + // FIXME: See if a more cache friendly algorithm would be faster. + let limit = count / 2 // The first offset without a left child var level = _Node.level(forOffset: limit &- 1) while level >= 0 { let nodes = _Node.allNodes(onLevel: level, limit: limit) - if _Node.isMinLevel(level) { - nodes?._forEach { node in - trickleDownMin(node) - } - } else { - nodes?._forEach { node in - trickleDownMax(node) - } - } + _heapify(level, nodes) level &-= 1 } } + + @inlinable + internal func _heapify(_ level: Int, _ nodes: ClosedRange<_Node>?) { + guard let nodes = nodes else { return } + if _Node.isMinLevel(level) { + nodes._forEach { node in + trickleDownMin(node) + } + } else { + nodes._forEach { node in + trickleDownMax(node) + } + } + } } diff --git a/Sources/HeapModule/Heap.swift b/Sources/HeapModule/Heap.swift index 310c7099..995c3208 100644 --- a/Sources/HeapModule/Heap.swift +++ b/Sources/HeapModule/Heap.swift @@ -70,7 +70,7 @@ extension Heap { /// Inserts the given element into the heap. /// - /// - Complexity: O(log `count`) + /// - Complexity: O(log(`count`)) element comparisons @inlinable public mutating func insert(_ element: Element) { _storage.append(element) @@ -110,7 +110,7 @@ extension Heap { /// Removes and returns the element with the lowest priority, if available. /// - /// - Complexity: O(log `count`) + /// - Complexity: O(log(`count`)) element comparisons @inlinable public mutating func popMin() -> Element? { guard _storage.count > 0 else { return nil } @@ -131,7 +131,7 @@ extension Heap { /// Removes and returns the element with the highest priority, if available. /// - /// - Complexity: O(log `count`) + /// - Complexity: O(log(`count`)) element comparisons @inlinable public mutating func popMax() -> Element? { guard _storage.count > 2 else { return _storage.popLast() } @@ -158,7 +158,7 @@ extension Heap { /// /// The heap *must not* be empty. /// - /// - Complexity: O(log `count`) + /// - Complexity: O(log(`count`)) element comparisons @inlinable public mutating func removeMin() -> Element { return popMin()! @@ -168,7 +168,7 @@ extension Heap { /// /// The heap *must not* be empty. /// - /// - Complexity: O(log `count`) + /// - Complexity: O(log(`count`)) element comparisons @inlinable public mutating func removeMax() -> Element { return popMax()! @@ -183,7 +183,7 @@ extension Heap { /// minimum value. /// - Returns: The original minimum value before the replacement. /// - /// - Complexity: O(log `count`) + /// - Complexity: O(log(`count`)) element comparisons @inlinable @discardableResult public mutating func replaceMin(with replacement: Element) -> Element { @@ -208,7 +208,7 @@ extension Heap { /// value. /// - Returns: The original maximum value before the replacement. /// - /// - Complexity: O(log `count`) + /// - Complexity: O(log(`count`)) element comparisons @inlinable @discardableResult public mutating func replaceMax(with replacement: Element) -> Element { @@ -239,14 +239,9 @@ extension Heap { extension Heap { /// Initializes a heap from a sequence. /// - /// - Complexity: O(*n*), where *n* is the length of `elements`. + /// - Complexity: O(*n*), where *n* is the number of items in `elements`. @inlinable public init(_ elements: S) where S.Element == Element { - // This is Floyd's linear-time heap construction algorithm. - // (https://en.wikipedia.org/wiki/Heapsort#Floyd's_heap_construction). - // - // FIXME: See if a more cache friendly algorithm would be faster. - _storage = ContiguousArray(elements) guard _storage.count > 1 else { return } diff --git a/Sources/HeapModule/_Node.swift b/Sources/HeapModule/_Node.swift index 02927814..a6763960 100644 --- a/Sources/HeapModule/_Node.swift +++ b/Sources/HeapModule/_Node.swift @@ -154,7 +154,7 @@ extension _Node { guard first.offset < limit else { return nil } var last = self.lastNode(onLevel: level) if last.offset >= limit { - last = _Node(offset: limit &- 1, level: level) + last.offset = limit &- 1 } return ClosedRange(uncheckedBounds: (first, last)) } diff --git a/Sources/OrderedCollections/CMakeLists.txt b/Sources/OrderedCollections/CMakeLists.txt index e6408926..f1cd5271 100644 --- a/Sources/OrderedCollections/CMakeLists.txt +++ b/Sources/OrderedCollections/CMakeLists.txt @@ -8,14 +8,16 @@ See https://swift.org/LICENSE.txt for license information #]] add_library(OrderedCollections + "HashTable/_HashTable.swift" "HashTable/_HashTable+Bucket.swift" "HashTable/_HashTable+BucketIterator.swift" "HashTable/_HashTable+Constants.swift" "HashTable/_HashTable+CustomStringConvertible.swift" + "HashTable/_Hashtable+Header.swift" "HashTable/_HashTable+Testing.swift" "HashTable/_HashTable+UnsafeHandle.swift" - "HashTable/_HashTable.swift" - "HashTable/_Hashtable+Header.swift" + "OrderedDictionary/OrderedDictionary.Elements.swift" + "OrderedDictionary/OrderedDictionary.swift" "OrderedDictionary/OrderedDictionary+Codable.swift" "OrderedDictionary/OrderedDictionary+CustomReflectable.swift" "OrderedDictionary/OrderedDictionary+Deprecations.swift" @@ -31,8 +33,7 @@ add_library(OrderedCollections "OrderedDictionary/OrderedDictionary+Sendable.swift" "OrderedDictionary/OrderedDictionary+Sequence.swift" "OrderedDictionary/OrderedDictionary+Values.swift" - "OrderedDictionary/OrderedDictionary.Elements.swift" - "OrderedDictionary/OrderedDictionary.swift" + "OrderedSet/OrderedSet.swift" "OrderedSet/OrderedSet+Codable.swift" "OrderedSet/OrderedSet+CustomReflectable.swift" "OrderedSet/OrderedSet+Descriptions.swift" @@ -45,9 +46,14 @@ add_library(OrderedCollections "OrderedSet/OrderedSet+Invariants.swift" "OrderedSet/OrderedSet+Partial MutableCollection.swift" "OrderedSet/OrderedSet+Partial RangeReplaceableCollection.swift" + "OrderedSet/OrderedSet+Partial SetAlgebra isDisjoint.swift" + "OrderedSet/OrderedSet+Partial SetAlgebra isEqual.swift" + "OrderedSet/OrderedSet+Partial SetAlgebra isStrictSubset.swift" + "OrderedSet/OrderedSet+Partial SetAlgebra isStrictSuperset.swift" + "OrderedSet/OrderedSet+Partial SetAlgebra isSubset.swift" + "OrderedSet/OrderedSet+Partial SetAlgebra isSuperset.swift" "OrderedSet/OrderedSet+Partial SetAlgebra+Basics.swift" "OrderedSet/OrderedSet+Partial SetAlgebra+Operations.swift" - "OrderedSet/OrderedSet+Partial SetAlgebra+Predicates.swift" "OrderedSet/OrderedSet+RandomAccessCollection.swift" "OrderedSet/OrderedSet+ReserveCapacity.swift" "OrderedSet/OrderedSet+Sendable.swift" @@ -55,7 +61,6 @@ add_library(OrderedCollections "OrderedSet/OrderedSet+Testing.swift" "OrderedSet/OrderedSet+UnorderedView.swift" "OrderedSet/OrderedSet+UnstableInternals.swift" - "OrderedSet/OrderedSet.swift" "Utilities/_UnsafeBitset.swift" ) target_link_libraries(OrderedCollections PRIVATE diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Invariants.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Invariants.swift index fa3d01fe..58964d22 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Invariants.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Invariants.swift @@ -9,7 +9,19 @@ // //===----------------------------------------------------------------------===// +import _CollectionsUtilities + extension OrderedDictionary { + /// True if consistency checking is enabled in the implementation of this + /// type, false otherwise. + /// + /// Documented performance promises are null and void when this property + /// returns true -- for example, operations that are documented to take + /// O(1) time might take O(*n*) time, or worse. + public static var _isConsistencyCheckingEnabled: Bool { + _isCollectionsInternalCheckingEnabled + } + #if COLLECTIONS_INTERNAL_CHECKS @inline(never) @_effects(releasenone) public func _checkInvariants() { diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial MutableCollection.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial MutableCollection.swift index c01e9686..f43d6993 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial MutableCollection.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial MutableCollection.swift @@ -82,7 +82,7 @@ extension OrderedDictionary { /// and `c` are incomparable, then `a` and `c` are also incomparable. /// (Transitive incomparability) /// - /// The sorting algorithm is not guaranteed to be stable. A stable sort + /// The sorting algorithm is guaranteed to be stable. A stable sort /// preserves the relative order of elements for which /// `areInIncreasingOrder` does not establish an order. /// @@ -116,8 +116,8 @@ extension OrderedDictionary where Key: Comparable { /// sorted in ascending order. (`Value` doesn't need to conform to /// `Comparable` because the keys are guaranteed to be unique.) /// - /// The sorting algorithm is not guaranteed to be stable. A stable sort - /// preserves the relative order of elements that compare equal. + /// The sorting algorithm is guaranteed to be stable. A stable sort + /// preserves the relative order of elements that compare as equal. /// /// - Complexity: O(*n* log *n*), where *n* is the length of the collection. @inlinable diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.Elements.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.Elements.swift index bcddb1a9..a759aaef 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.Elements.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.Elements.swift @@ -439,7 +439,7 @@ extension OrderedDictionary.Elements { /// and `c` are incomparable, then `a` and `c` are also incomparable. /// (Transitive incomparability) /// - /// The sorting algorithm is not guaranteed to be stable. A stable sort + /// The sorting algorithm is guaranteed to be stable. A stable sort /// preserves the relative order of elements for which /// `areInIncreasingOrder` does not establish an order. /// @@ -467,8 +467,8 @@ extension OrderedDictionary.Elements where Key: Comparable { /// sorted in ascending order. (`Value` doesn't need to conform to /// `Comparable` because the keys are guaranteed to be unique.) /// - /// The sorting algorithm is not guaranteed to be stable. A stable sort - /// preserves the relative order of elements that compare equal. + /// The sorting algorithm is guaranteed to be stable. A stable sort + /// preserves the relative order of elements that compare as equal. /// /// - Complexity: O(*n* log *n*), where *n* is the length of the collection. @inlinable diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Equatable.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Equatable.swift index 1190cd6e..2c6dee53 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Equatable.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Equatable.swift @@ -15,6 +15,11 @@ extension OrderedSet: Equatable { /// Two ordered sets are considered equal if they contain the same /// elements in the same order. /// + /// - Note: This operator implements different behavior than the + /// `isEqual(to:)` method -- the latter implements an unordered + /// comparison, to match the behavior of members like `isSubset(of:)`, + /// `isStrictSuperset(of:)` etc. + /// /// - Complexity: O(`min(left.count, right.count)`) @inlinable public static func ==(left: Self, right: Self) -> Bool { diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Initializers.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Initializers.swift index e4cf7e94..e9b68df6 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Initializers.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Initializers.swift @@ -49,11 +49,13 @@ extension OrderedSet { /// Creates a new set from a finite sequence of items. /// /// - Parameter elements: The elements to use as members of the new set. + /// The sequence is allowed to contain duplicate elements, but only + /// the first duplicate instance is preserved in the result. /// /// - Complexity: This operation is expected to perform O(*n*) - /// comparisons on average (where *n* is the number of elements - /// in the sequence), provided that `Element` implements - /// high-quality hashing. + /// hashing and equality comparisons on average (where *n* + /// is the number of elements in the sequence), provided that + /// `Element` properly implements hashing. @inlinable public init(_ elements: S) where S.Element == Element { if S.self == Self.self { diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Invariants.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Invariants.swift index 51c853b7..53de455e 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Invariants.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Invariants.swift @@ -9,7 +9,19 @@ // //===----------------------------------------------------------------------===// +import _CollectionsUtilities + extension OrderedSet { + /// True if consistency checking is enabled in the implementation of this + /// type, false otherwise. + /// + /// Documented performance promises are null and void when this property + /// returns true -- for example, operations that are documented to take + /// O(1) time might take O(*n*) time, or worse. + public static var _isConsistencyCheckingEnabled: Bool { + _isCollectionsInternalCheckingEnabled + } + #if COLLECTIONS_INTERNAL_CHECKS @inlinable @inline(never) @_effects(releasenone) diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial MutableCollection.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial MutableCollection.swift index 5bbcefb5..bbc139bb 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial MutableCollection.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial MutableCollection.swift @@ -218,7 +218,7 @@ extension OrderedSet { /// and `c` are incomparable, then `a` and `c` are also incomparable. /// (Transitive incomparability) /// - /// The sorting algorithm is not guaranteed to be stable. A stable sort + /// The sorting algorithm is guaranteed to be stable. A stable sort /// preserves the relative order of elements for which /// `areInIncreasingOrder` does not establish an order. /// @@ -268,8 +268,8 @@ extension OrderedSet where Element: Comparable { /// print(students) /// // Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]" /// - /// The sorting algorithm is not guaranteed to be stable. A stable sort - /// preserves the relative order of elements that compare equal. + /// The sorting algorithm is guaranteed to be stable. A stable sort + /// preserves the relative order of elements that compare as equal. /// /// - Complexity: O(*n* log *n*), where *n* is the length of the collection. @inlinable diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isDisjoint.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isDisjoint.swift new file mode 100644 index 00000000..8c2f1340 --- /dev/null +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isDisjoint.swift @@ -0,0 +1,128 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +import _CollectionsUtilities + +// `OrderedSet` does not directly conform to `SetAlgebra` because its definition +// of equality conflicts with `SetAlgebra` requirements. However, it still +// implements most `SetAlgebra` requirements (except `insert`, which is replaced +// by `append`). +// +// `OrderedSet` also provides an `unordered` view that explicitly conforms to +// `SetAlgebra`. That view implements `Equatable` by ignoring element order, +// so it can satisfy `SetAlgebra` requirements. + +extension OrderedSet { + /// Returns a Boolean value that indicates whether the set has no members in + /// common with the given set. + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: OrderedSet = [5, 6] + /// a.isDisjoint(with: b) // true + /// + /// - Parameter other: Another set. + /// + /// - Returns: `true` if `self` has no elements in common with `other`; + /// otherwise, `false`. + /// + /// - Complexity: Expected to be O(min(`self.count`, `other.count`)) on + /// average, if `Element` implements high-quality hashing. + @inlinable + public func isDisjoint(with other: Self) -> Bool { + guard !self.isEmpty && !other.isEmpty else { return true } + if self.count <= other.count { + for item in self { + if other.contains(item) { return false } + } + } else { + for item in other { + if self.contains(item) { return false } + } + } + return true + } + + // Generalizations + + /// Returns a Boolean value that indicates whether the set has no members in + /// common with the given set. + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: OrderedSet = [5, 6] + /// a.isDisjoint(with: b.unordered) // true + /// + /// - Parameter other: Another set. + /// + /// - Returns: `true` if `self` has no elements in common with `other`; + /// otherwise, `false`. + /// + /// - Complexity: Expected to be O(min(`self.count`, `other.count`)) on + /// average, if `Element` implements high-quality hashing. + @inlinable + @inline(__always) + public func isDisjoint(with other: UnorderedView) -> Bool { + isDisjoint(with: other._base) + } + + /// Returns a Boolean value that indicates whether the set has no members in + /// common with the given set. + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: Set = [5, 6] + /// a.isDisjoint(with: b) // true + /// + /// - Parameter other: Another set. + /// + /// - Returns: `true` if `self` has no elements in common with `other`; + /// otherwise, `false`. + /// + /// - Complexity: Expected to be O(min(`self.count`, `other.count`)) on + /// average, if `Element` implements high-quality hashing. + @inlinable + public func isDisjoint(with other: Set) -> Bool { + guard !self.isEmpty && !other.isEmpty else { return true } + if self.count <= other.count { + for item in self { + if other.contains(item) { return false } + } + } else { + for item in other { + if self.contains(item) { return false } + } + } + return true + } + + /// Returns a Boolean value that indicates whether the set has no members in + /// common with the given sequence. + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: Array = [5, 6] + /// a.isDisjoint(with: b) // true + /// + /// - Parameter other: A finite sequence of elements. + /// + /// - Returns: `true` if `self` has no elements in common with `other`; + /// otherwise, `false`. + /// + /// - Complexity: Expected to be O(*n*) on average, where *n* is the number of + /// elements in `other`, if `Element` implements high-quality hashing. + @inlinable + public func isDisjoint( + with other: S + ) -> Bool where S.Element == Element { + guard !self.isEmpty else { return true } + for item in other { + if self.contains(item) { return false } + } + return true + } +} diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isEqual.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isEqual.swift new file mode 100644 index 00000000..8f63fe72 --- /dev/null +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isEqual.swift @@ -0,0 +1,80 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +import _CollectionsUtilities + +extension OrderedSet { + /// Returns a Boolean value indicating whether two set values contain the + /// same elements, but not necessarily in the same order. + /// + /// - Note: This member implements different behavior than the `==(_:_:)` + /// operator -- the latter implements an ordered comparison, matching + /// the stricter concept of equality expected of an ordered collection + /// type. + /// + /// - Complexity: O(`min(left.count, right.count)`), as long as`Element` + /// properly implements hashing. + public func isEqual(to other: Self) -> Bool { + self.unordered == other.unordered + } + + /// Returns a Boolean value indicating whether two set values contain the + /// same elements, but not necessarily in the same order. + /// + /// - Complexity: O(`min(left.count, right.count)`), as long as`Element` + /// properly implements hashing. + public func isEqual(to other: UnorderedView) -> Bool { + self.unordered == other + } + + /// Returns a Boolean value indicating whether an ordered set contains the + /// same values as a given sequence, but not necessarily in the same + /// order. + /// + /// Duplicate items in `other` do not prevent it from comparing equal to + /// `self`. + /// + /// - Complexity: O(*n*), where *n* is the number of items in + /// `other`, as long as`Element` properly implements hashing. + public func isEqual(to other: S) -> Bool + where S.Element == Element { + if S.self == Self.self { + return isEqual(to: other as! Self) + } + + if self.isEmpty { + return other.allSatisfy { _ in false } + } + + if other is _UniqueCollection { + // We don't need to create a temporary set. + guard other.underestimatedCount <= self.count else { return false } + var seen = 0 + for item in other { + guard self.contains(item) else { return false } + seen &+= 1 + } + precondition( + seen <= self.count, + // Otherwise other.underestimatedCount != other.count + "Invalid Collection '\(S.self)' (bad underestimatedCount)") + return seen == self.count + } + + return _UnsafeBitset.withTemporaryBitset(capacity: count) { seen in + for item in other { + guard let index = _find(item).index else { return false } + _ = seen.insert(index) // Ignore dupes + } + return seen.count == count + } + } +} diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isStrictSubset.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isStrictSubset.swift new file mode 100644 index 00000000..b73ba5f6 --- /dev/null +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isStrictSubset.swift @@ -0,0 +1,154 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +// `OrderedSet` does not directly conform to `SetAlgebra` because its definition +// of equality conflicts with `SetAlgebra` requirements. However, it still +// implements most `SetAlgebra` requirements (except `insert`, which is replaced +// by `append`). +// +// `OrderedSet` also provides an `unordered` view that explicitly conforms to +// `SetAlgebra`. That view implements `Equatable` by ignoring element order, +// so it can satisfy `SetAlgebra` requirements. + +extension OrderedSet { + /// Returns a Boolean value that indicates whether the set is a strict subset + /// of the given set. + /// + /// Set *A* is a strict subset of another set *B* if every member of *A* is + /// also a member of *B* and *B* contains at least one element that is not a + /// member of *A*. (Ignoring the order the elements appear in the sets.) + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: OrderedSet = [4, 2, 1] + /// b.isStrictSubset(of: a) // true + /// + /// - Parameter other: Another set. + /// + /// - Returns: `true` if `self` is a strict subset of `other`; otherwise, + /// `false`. + /// + /// - Complexity: Expected to be O(`self.count`) on average, if `Element` + /// implements high-quality hashing. + @inlinable + public func isStrictSubset(of other: Self) -> Bool { + self.count < other.count && self.isSubset(of: other) + } + + // Generalizations + + /// Returns a Boolean value that indicates whether the set is a strict subset + /// of the given set. + /// + /// Set *A* is a strict subset of another set *B* if every member of *A* is + /// also a member of *B* and *B* contains at least one element that is not a + /// member of *A*. (Ignoring the order the elements appear in the sets.) + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: OrderedSet = [4, 2, 1] + /// b.isStrictSubset(of: a.unordered) // true + /// + /// - Parameter other: Another set. + /// + /// - Returns: `true` if `self` is a strict subset of `other`; otherwise, + /// `false`. + /// + /// - Complexity: Expected to be O(`self.count`) on average, if `Element` + /// implements high-quality hashing. + @inlinable + @inline(__always) + public func isStrictSubset(of other: UnorderedView) -> Bool { + isStrictSubset(of: other._base) + } + + /// Returns a Boolean value that indicates whether the set is a strict subset + /// of the given set. + /// + /// Set *A* is a strict subset of another set *B* if every member of *A* is + /// also a member of *B* and *B* contains at least one element that is not a + /// member of *A*. (Ignoring the order the elements appear in the sets.) + /// + /// let a: Set = [1, 2, 3, 4] + /// let b: OrderedSet = [4, 2, 1] + /// b.isStrictSubset(of: a) // true + /// + /// - Parameter other: Another set. + /// + /// - Returns: `true` if `self` is a strict subset of `other`; otherwise, + /// `false`. + /// + /// - Complexity: Expected to be O(`self.count`) on average, if `Element` + /// implements high-quality hashing. + @inlinable + public func isStrictSubset(of other: Set) -> Bool { + self.count < other.count && self.isSubset(of: other) + } + + /// Returns a Boolean value that indicates whether the set is a strict subset + /// of the given sequence. + /// + /// Set *A* is a strict subset of another set *B* if every member of *A* is + /// also a member of *B* and *B* contains at least one element that is not a + /// member of *A*. (Ignoring the order the elements appear in the sets.) + /// + /// let a: Array = [1, 2, 3, 4] + /// let b: OrderedSet = [4, 2, 1] + /// b.isStrictSubset(of: a) // true + /// + /// - Parameter other: A finite sequence of elements. + /// + /// - Returns: `true` if `self` is a strict subset of `other`; otherwise, + /// `false`. + /// + /// - Complexity: Expected to be O(`self.count` + *n*) on average, where *n* + /// is the number of elements in `other`, if `Element` implements + /// high-quality hashing. + @inlinable + public func isStrictSubset( + of other: S + ) -> Bool where S.Element == Element { + if S.self == Self.self { + return self.isStrictSubset(of: other as! Self) + } + if S.self == Set.self { + return self.isStrictSubset(of: other as! Set) + } + + var it = self.makeIterator() + guard let first = it.next() else { + return other.contains(where: { _ in true }) + } + if let match = other._customContainsEquatableElement(first) { + // Fast path: the sequence has fast containment checks. + guard match else { return false } + while let item = it.next() { + guard other.contains(item) else { return false } + } + return !other.allSatisfy { self.contains($0) } + } + + return _UnsafeBitset.withTemporaryBitset(capacity: count) { seen in + // Mark elements in `self` that we've seen in `other`. + var isKnownStrict = false + for item in other { + if let index = _find(item).index { + if seen.insert(index), seen.count == self.count, isKnownStrict { + // We've seen enough. + return true + } + } else { + if !isKnownStrict, seen.count == self.count { return true } + isKnownStrict = true + } + } + return false + } + } +} diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isStrictSuperset.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isStrictSuperset.swift new file mode 100644 index 00000000..53f98b4a --- /dev/null +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isStrictSuperset.swift @@ -0,0 +1,152 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +// `OrderedSet` does not directly conform to `SetAlgebra` because its definition +// of equality conflicts with `SetAlgebra` requirements. However, it still +// implements most `SetAlgebra` requirements (except `insert`, which is replaced +// by `append`). +// +// `OrderedSet` also provides an `unordered` view that explicitly conforms to +// `SetAlgebra`. That view implements `Equatable` by ignoring element order, +// so it can satisfy `SetAlgebra` requirements. + +extension OrderedSet { + /// Returns a Boolean value that indicates whether the set is a strict + /// superset of the given set. + /// + /// Set *A* is a strict superset of another set *B* if every member of *B* is + /// also a member of *A* and *A* contains at least one element that is *not* + /// a member of *B*. (Ignoring the order the elements appear in the sets.) + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: OrderedSet = [4, 2, 1] + /// a.isStrictSuperset(of: b) // true + /// + /// - Parameter other: Another set. + /// + /// - Returns: `true` if `self` is a strict superset of `other`; otherwise, + /// `false`. + /// + /// - Complexity: Expected to be O(`other.count`) on average, if `Element` + /// implements high-quality hashing. + @inlinable + public func isStrictSuperset(of other: Self) -> Bool { + self.count > other.count && other.isSubset(of: self) + } + + // Generalizations + + /// Returns a Boolean value that indicates whether the set is a strict + /// superset of the given set. + /// + /// Set *A* is a strict superset of another set *B* if every member of *B* is + /// also a member of *A* and *A* contains at least one element that is *not* + /// a member of *B*. (Ignoring the order the elements appear in the sets.) + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: OrderedSet = [4, 2, 1] + /// a.isStrictSuperset(of: b.unordered) // true + /// + /// - Parameter other: Another set. + /// + /// - Returns: `true` if `self` is a strict superset of `other`; otherwise, + /// `false`. + /// + /// - Complexity: Expected to be O(`other.count`) on average, if `Element` + /// implements high-quality hashing. + @inlinable + @inline(__always) + public func isStrictSuperset(of other: UnorderedView) -> Bool { + isStrictSuperset(of: other._base) + } + + /// Returns a Boolean value that indicates whether the set is a strict + /// superset of the given set. + /// + /// Set *A* is a strict superset of another set *B* if every member of *B* is + /// also a member of *A* and *A* contains at least one element that is *not* + /// a member of *B*. (Ignoring the order the elements appear in the sets.) + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: Set = [4, 2, 1] + /// a.isStrictSuperset(of: b) // true + /// + /// - Parameter other: Another set. + /// + /// - Returns: `true` if `self` is a strict superset of `other`; otherwise, + /// `false`. + /// + /// - Complexity: Expected to be O(`other.count`) on average, if `Element` + /// implements high-quality hashing. + @inlinable + public func isStrictSuperset(of other: Set) -> Bool { + self.count > other.count && other.isSubset(of: self) + } + + /// Returns a Boolean value that indicates whether the set is a strict + /// superset of the given sequence. + /// + /// Set *A* is a strict superset of another set *B* if every member of *B* is + /// also a member of *A* and *A* contains at least one element that is *not* + /// a member of *B*. (Ignoring the order the elements appear in the sets.) + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: Array = [4, 2, 1] + /// a.isStrictSuperset(of: b) // true + /// + /// - Parameter other: A finite sequence of elements, some of whose members + /// may appear more than once. (Duplicate items are ignored.) + /// + /// - Returns: `true` if `self` is a strict superset of `other`; otherwise, + /// `false`. + /// + /// - Complexity: Expected to be O(`self.count` + *n*) on average, where *n* + /// is the number of elements in `other`, if `Element` implements + /// high-quality hashing. + @inlinable + public func isStrictSuperset( + of other: S + ) -> Bool where S.Element == Element { + if S.self == Self.self { + return self.isStrictSuperset(of: other as! Self) + } + if S.self == Set.self { + return self.isStrictSuperset(of: other as! Set) + } + + var it = self.makeIterator() + guard let first = it.next() else { return false } + if let match = other._customContainsEquatableElement(first) { + // Fast path: the sequence has fast containment checks. + guard other.allSatisfy({ self.contains($0) }) else { return false } + guard match else { return true } + while let item = it.next() { + guard other.contains(item) else { return true } + } + return false + } + + return _UnsafeBitset.withTemporaryBitset(capacity: count) { seen in + // Mark elements in `self` that we've seen in `other`. + for item in other { + guard let index = _find(item).index else { + return false + } + if seen.insert(index), seen.count == self.count { + // We've seen enough. + return false + } + } + return seen.count < self.count + } + } +} + diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isSubset.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isSubset.swift new file mode 100644 index 00000000..0fc3d599 --- /dev/null +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isSubset.swift @@ -0,0 +1,147 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +// `OrderedSet` does not directly conform to `SetAlgebra` because its definition +// of equality conflicts with `SetAlgebra` requirements. However, it still +// implements most `SetAlgebra` requirements (except `insert`, which is replaced +// by `append`). +// +// `OrderedSet` also provides an `unordered` view that explicitly conforms to +// `SetAlgebra`. That view implements `Equatable` by ignoring element order, +// so it can satisfy `SetAlgebra` requirements. + +extension OrderedSet { + /// Returns a Boolean value that indicates whether this set is a subset of + /// the given set. + /// + /// Set *A* is a subset of another set *B* if every member of *A* is also a + /// member of *B*, ignoring the order they appear in the two sets. + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: OrderedSet = [4, 2, 1] + /// b.isSubset(of: a) // true + /// + /// - Parameter other: Another set. + /// + /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. + /// + /// - Complexity: Expected to be O(`self.count`) on average, if `Element` + /// implements high-quality hashing. + @inlinable + public func isSubset(of other: Self) -> Bool { + guard other.count >= self.count else { return false } + for item in self { + guard other.contains(item) else { return false } + } + return true + } + + // Generalizations + + /// Returns a Boolean value that indicates whether this set is a subset of + /// the given set. + /// + /// Set *A* is a subset of another set *B* if every member of *A* is also a + /// member of *B*, ignoring the order they appear in the two sets. + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: OrderedSet = [4, 2, 1] + /// b.isSubset(of: a.unordered) // true + /// + /// - Parameter other: Another set. + /// + /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. + /// + /// - Complexity: Expected to be O(`self.count`) on average, if `Element` + /// implements high-quality hashing. + @inlinable + @inline(__always) + public func isSubset(of other: UnorderedView) -> Bool { + isSubset(of: other._base) + } + + /// Returns a Boolean value that indicates whether this set is a subset of + /// the given set. + /// + /// Set *A* is a subset of another set *B* if every member of *A* is also a + /// member of *B*, ignoring the order they appear in the two sets. + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: Set = [4, 2, 1] + /// b.isSubset(of: a) // true + /// + /// - Parameter other: Another set. + /// + /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. + /// + /// - Complexity: Expected to be O(`self.count`) on average, if `Element` + /// implements high-quality hashing. + @inlinable + public func isSubset(of other: Set) -> Bool { + guard other.count >= self.count else { return false } + for item in self { + guard other.contains(item) else { return false } + } + return true + } + + /// Returns a Boolean value that indicates whether this set is a subset of + /// the elements in the given sequence. + /// + /// Set *A* is a subset of another set *B* if every member of *A* is also a + /// member of *B*, ignoring the order they appear in the two sets. + /// + /// let a: Array = [1, 2, 3, 4] + /// let b: OrderedSet = [4, 2, 1] + /// b.isSubset(of: a) // true + /// + /// - Parameter other: A finite sequence. + /// + /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. + /// + /// - Complexity: Expected to be O(`self.count` + *n*) on average, where *n* + /// is the number of elements in `other`, if `Element` implements + /// high-quality hashing. + @inlinable + public func isSubset( + of other: S + ) -> Bool where S.Element == Element { + guard !isEmpty else { return true } + + if S.self == Self.self { + return isSubset(of: other as! Self) + } + + var it = self.makeIterator() + let first = it.next()! + if let match = other._customContainsEquatableElement(first) { + // Fast path: the sequence has fast containment checks. + guard match else { return false } + while let item = it.next() { + guard other.contains(item) else { return false } + } + return true + } + + return _UnsafeBitset.withTemporaryBitset(capacity: count) { seen in + // Mark elements in `self` that we've seen in `other`. + for item in other { + if let index = _find(item).index { + if seen.insert(index), seen.count == self.count { + // We've seen enough. + return true + } + } + } + return false + } + } +} diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isSuperset.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isSuperset.swift new file mode 100644 index 00000000..2cb62aca --- /dev/null +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isSuperset.swift @@ -0,0 +1,124 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +// `OrderedSet` does not directly conform to `SetAlgebra` because its definition +// of equality conflicts with `SetAlgebra` requirements. However, it still +// implements most `SetAlgebra` requirements (except `insert`, which is replaced +// by `append`). +// +// `OrderedSet` also provides an `unordered` view that explicitly conforms to +// `SetAlgebra`. That view implements `Equatable` by ignoring element order, +// so it can satisfy `SetAlgebra` requirements. + +extension OrderedSet { + /// Returns a Boolean value that indicates whether this set is a superset of + /// the given set. + /// + /// Set *A* is a superset of another set *B* if every member of *B* is also a + /// member of *A*, ignoring the order they appear in the two sets. + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: OrderedSet = [4, 2, 1] + /// a.isSuperset(of: b) // true + /// + /// - Parameter other: Another set. + /// + /// - Returns: `true` if the set is a superset of `other`; otherwise, `false`. + /// + /// - Complexity: Expected to be O(`other.count`) on average, if `Element` + /// implements high-quality hashing. + @inlinable + public func isSuperset(of other: Self) -> Bool { + other.isSubset(of: self) + } + + // Generalizations + + /// Returns a Boolean value that indicates whether this set is a superset of + /// the given set. + /// + /// Set *A* is a superset of another set *B* if every member of *B* is also a + /// member of *A*, ignoring the order they appear in the two sets. + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: Set = [4, 2, 1] + /// a.isSuperset(of: b) // true + /// + /// - Parameter other: Another set. + /// + /// - Returns: `true` if the set is a superset of `other`; otherwise, `false`. + /// + /// - Complexity: Expected to be O(`other.count`) on average, if `Element` + /// implements high-quality hashing. + @inlinable + public func isSuperset(of other: UnorderedView) -> Bool { + isSuperset(of: other._base) + } + + /// Returns a Boolean value that indicates whether this set is a superset of + /// the given set. + /// + /// Set *A* is a superset of another set *B* if every member of *B* is also a + /// member of *A*, ignoring the order they appear in the two sets. + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: Set = [4, 2, 1] + /// a.isSuperset(of: b) // true + /// + /// - Parameter other: Another set. + /// + /// - Returns: `true` if the set is a superset of `other`; otherwise, `false`. + /// + /// - Complexity: Expected to be O(`other.count`) on average, if `Element` + /// implements high-quality hashing. + @inlinable + public func isSuperset(of other: Set) -> Bool { + guard self.count >= other.count else { return false } + return _isSuperset(of: other) + } + + /// Returns a Boolean value that indicates whether this set is a superset of + /// the given sequence. + /// + /// Set *A* is a superset of another set *B* if every member of *B* is also a + /// member of *A*, ignoring the order they appear in the two sets. + /// + /// let a: OrderedSet = [1, 2, 3, 4] + /// let b: Array = [4, 2, 1] + /// a.isSuperset(of: b) // true + /// + /// - Parameter other: A finite sequence of elements, some of whose members + /// may appear more than once. (Duplicate items are ignored.) + /// + /// - Returns: `true` if the set is a superset of `other`; otherwise, `false`. + /// + /// - Complexity: Expected to be O(*n*) on average, where *n* is the number of + /// elements in `other`, if `Element` implements high-quality hashing. + @inlinable + public func isSuperset( + of other: S + ) -> Bool where S.Element == Element { + _isSuperset(of: other) + } + + @inlinable + internal func _isSuperset( + of other: S + ) -> Bool where S.Element == Element { + if S.self == Self.self { + return self.isSuperset(of: other as! Self) + } + for item in other { + guard self.contains(item) else { return false } + } + return true + } +} diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra+Basics.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra+Basics.swift index cd303b02..ecc6f7b5 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra+Basics.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra+Basics.swift @@ -55,7 +55,7 @@ extension OrderedSet { /// /// - Returns: The element equal to `member` if `member` is contained in the /// set; otherwise, `nil`. In some cases, the returned element may be - /// distinguishable from `newMember` by identity comparison or some other + /// distinguishable from `member` by identity comparison or some other /// means. /// /// - Complexity: O(`count`). Removing an element from the middle of the diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra+Predicates.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra+Predicates.swift deleted file mode 100644 index e975a0b4..00000000 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra+Predicates.swift +++ /dev/null @@ -1,551 +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 { - /// Returns a Boolean value that indicates whether this set is a subset of - /// the given set. - /// - /// Set *A* is a subset of another set *B* if every member of *A* is also a - /// member of *B*, ignoring the order they appear in the two sets. - /// - /// let a: OrderedSet = [1, 2, 3, 4] - /// let b: OrderedSet = [4, 2, 1] - /// b.isSubset(of: a) // true - /// - /// - Parameter other: Another set. - /// - /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. - /// - /// - Complexity: Expected to be O(`self.count`) on average, if `Element` - /// implements high-quality hashing. - @inlinable - public func isSubset(of other: Self) -> Bool { - guard other.count >= self.count else { return false } - for item in self { - guard other.contains(item) else { return false } - } - return true - } - - // Generalizations - - /// Returns a Boolean value that indicates whether this set is a subset of - /// the given set. - /// - /// Set *A* is a subset of another set *B* if every member of *A* is also a - /// member of *B*, ignoring the order they appear in the two sets. - /// - /// let a: OrderedSet = [1, 2, 3, 4] - /// let b: OrderedSet = [4, 2, 1] - /// b.isSubset(of: a.unordered) // true - /// - /// - Parameter other: Another set. - /// - /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. - /// - /// - Complexity: Expected to be O(`self.count`) on average, if `Element` - /// implements high-quality hashing. - @inlinable - @inline(__always) - public func isSubset(of other: UnorderedView) -> Bool { - isSubset(of: other._base) - } - - /// Returns a Boolean value that indicates whether this set is a subset of - /// the given set. - /// - /// Set *A* is a subset of another set *B* if every member of *A* is also a - /// member of *B*, ignoring the order they appear in the two sets. - /// - /// let a: OrderedSet = [1, 2, 3, 4] - /// let b: Set = [4, 2, 1] - /// b.isSubset(of: a) // true - /// - /// - Parameter other: Another set. - /// - /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. - /// - /// - Complexity: Expected to be O(`self.count`) on average, if `Element` - /// implements high-quality hashing. - @inlinable - public func isSubset(of other: Set) -> Bool { - guard other.count >= self.count else { return false } - for item in self { - guard other.contains(item) else { return false } - } - return true - } - - /// Returns a Boolean value that indicates whether this set is a subset of - /// the elements in the given sequence. - /// - /// Set *A* is a subset of another set *B* if every member of *A* is also a - /// member of *B*, ignoring the order they appear in the two sets. - /// - /// let a: Array = [1, 2, 3, 4] - /// let b: OrderedSet = [4, 2, 1] - /// b.isSubset(of: a) // true - /// - /// - Parameter other: A finite sequence. - /// - /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. - /// - /// - Complexity: Expected to be O(`self.count` + *n*) on average, where *n* - /// is the number of elements in `other`, if `Element` implements - /// high-quality hashing. - @inlinable - public func isSubset( - of other: S - ) -> Bool where S.Element == Element { - guard !isEmpty else { return true } - return _UnsafeBitset.withTemporaryBitset(capacity: count) { seen in - // Mark elements in `self` that we've seen in `other`. - for item in other { - if let index = _find(item).index { - if seen.insert(index), seen.count == self.count { - // We've seen enough. - return true - } - } - } - return false - } - } -} - -extension OrderedSet { - /// Returns a Boolean value that indicates whether this set is a superset of - /// the given set. - /// - /// Set *A* is a superset of another set *B* if every member of *B* is also a - /// member of *A*, ignoring the order they appear in the two sets. - /// - /// let a: OrderedSet = [1, 2, 3, 4] - /// let b: OrderedSet = [4, 2, 1] - /// a.isSuperset(of: b) // true - /// - /// - Parameter other: Another set. - /// - /// - Returns: `true` if the set is a superset of `other`; otherwise, `false`. - /// - /// - Complexity: Expected to be O(`other.count`) on average, if `Element` - /// implements high-quality hashing. - @inlinable - public func isSuperset(of other: Self) -> Bool { - other.isSubset(of: self) - } - - // Generalizations - - /// Returns a Boolean value that indicates whether this set is a superset of - /// the given set. - /// - /// Set *A* is a superset of another set *B* if every member of *B* is also a - /// member of *A*, ignoring the order they appear in the two sets. - /// - /// let a: OrderedSet = [1, 2, 3, 4] - /// let b: Set = [4, 2, 1] - /// a.isSuperset(of: b) // true - /// - /// - Parameter other: Another set. - /// - /// - Returns: `true` if the set is a superset of `other`; otherwise, `false`. - /// - /// - Complexity: Expected to be O(`other.count`) on average, if `Element` - /// implements high-quality hashing. - @inlinable - public func isSuperset(of other: UnorderedView) -> Bool { - isSuperset(of: other._base) - } - - @inlinable - public func isSuperset(of other: Set) -> Bool { - guard self.count >= other.count else { return false } - return _isSuperset(of: other) - } - - /// Returns a Boolean value that indicates whether this set is a superset of - /// the given sequence. - /// - /// Set *A* is a superset of another set *B* if every member of *B* is also a - /// member of *A*, ignoring the order they appear in the two sets. - /// - /// let a: OrderedSet = [1, 2, 3, 4] - /// let b: Array = [4, 2, 1] - /// a.isSuperset(of: b) // true - /// - /// - Parameter other: A finite sequence of elements. - /// - /// - Returns: `true` if the set is a superset of `other`; otherwise, `false`. - /// - /// - Complexity: Expected to be O(*n*) on average, where *n* is the number of - /// elements in `other`, if `Element` implements high-quality hashing. - @inlinable - public func isSuperset( - of other: S - ) -> Bool where S.Element == Element { - _isSuperset(of: other) - } - - @inlinable - internal func _isSuperset( - of other: S - ) -> Bool where S.Element == Element { - for item in other { - guard self.contains(item) else { return false } - } - return true - } -} - -extension OrderedSet { - /// Returns a Boolean value that indicates whether the set is a strict subset - /// of the given set. - /// - /// Set *A* is a strict subset of another set *B* if every member of *A* is - /// also a member of *B* and *B* contains at least one element that is not a - /// member of *A*. (Ignoring the order the elements appear in the sets.) - /// - /// let a: OrderedSet = [1, 2, 3, 4] - /// let b: OrderedSet = [4, 2, 1] - /// b.isStrictSubset(of: a) // true - /// - /// - Parameter other: Another set. - /// - /// - Returns: `true` if `self` is a strict subset of `other`; otherwise, - /// `false`. - /// - /// - Complexity: Expected to be O(`self.count`) on average, if `Element` - /// implements high-quality hashing. - @inlinable - public func isStrictSubset(of other: Self) -> Bool { - self.count < other.count && self.isSubset(of: other) - } - - // Generalizations - - /// Returns a Boolean value that indicates whether the set is a strict subset - /// of the given set. - /// - /// Set *A* is a strict subset of another set *B* if every member of *A* is - /// also a member of *B* and *B* contains at least one element that is not a - /// member of *A*. (Ignoring the order the elements appear in the sets.) - /// - /// let a: OrderedSet = [1, 2, 3, 4] - /// let b: OrderedSet = [4, 2, 1] - /// b.isStrictSubset(of: a.unordered) // true - /// - /// - Parameter other: Another set. - /// - /// - Returns: `true` if `self` is a strict subset of `other`; otherwise, - /// `false`. - /// - /// - Complexity: Expected to be O(`self.count`) on average, if `Element` - /// implements high-quality hashing. - @inlinable - @inline(__always) - public func isStrictSubset(of other: UnorderedView) -> Bool { - isStrictSubset(of: other._base) - } - - /// Returns a Boolean value that indicates whether the set is a strict subset - /// of the given set. - /// - /// Set *A* is a strict subset of another set *B* if every member of *A* is - /// also a member of *B* and *B* contains at least one element that is not a - /// member of *A*. (Ignoring the order the elements appear in the sets.) - /// - /// let a: Set = [1, 2, 3, 4] - /// let b: OrderedSet = [4, 2, 1] - /// b.isStrictSubset(of: a) // true - /// - /// - Parameter other: Another set. - /// - /// - Returns: `true` if `self` is a strict subset of `other`; otherwise, - /// `false`. - /// - /// - Complexity: Expected to be O(`self.count`) on average, if `Element` - /// implements high-quality hashing. - @inlinable - public func isStrictSubset(of other: Set) -> Bool { - self.count < other.count && self.isSubset(of: other) - } - - /// Returns a Boolean value that indicates whether the set is a strict subset - /// of the given sequence. - /// - /// Set *A* is a strict subset of another set *B* if every member of *A* is - /// also a member of *B* and *B* contains at least one element that is not a - /// member of *A*. (Ignoring the order the elements appear in the sets.) - /// - /// let a: Array = [1, 2, 3, 4] - /// let b: OrderedSet = [4, 2, 1] - /// b.isStrictSubset(of: a) // true - /// - /// - Parameter other: A finite sequence of elements. - /// - /// - Returns: `true` if `self` is a strict subset of `other`; otherwise, - /// `false`. - /// - /// - Complexity: Expected to be O(`self.count` + *n*) on average, where *n* - /// is the number of elements in `other`, if `Element` implements - /// high-quality hashing. - @inlinable - public func isStrictSubset( - of other: S - ) -> Bool where S.Element == Element { - _UnsafeBitset.withTemporaryBitset(capacity: count) { seen in - // Mark elements in `self` that we've seen in `other`. - var isKnownStrict = false - for item in other { - if let index = _find(item).index { - if seen.insert(index), seen.count == self.count, isKnownStrict { - // We've seen enough. - return true - } - } else { - if !isKnownStrict, seen.count == self.count { return true } - isKnownStrict = true - } - } - return false - } - } -} - -extension OrderedSet { - /// Returns a Boolean value that indicates whether the set is a strict - /// superset of the given set. - /// - /// Set *A* is a strict superset of another set *B* if every member of *B* is - /// also a member of *A* and *A* contains at least one element that is *not* - /// a member of *B*. (Ignoring the order the elements appear in the sets.) - /// - /// let a: OrderedSet = [1, 2, 3, 4] - /// let b: OrderedSet = [4, 2, 1] - /// a.isStrictSuperset(of: b) // true - /// - /// - Parameter other: Another set. - /// - /// - Returns: `true` if `self` is a strict superset of `other`; otherwise, - /// `false`. - /// - /// - Complexity: Expected to be O(`other.count`) on average, if `Element` - /// implements high-quality hashing. - @inlinable - public func isStrictSuperset(of other: Self) -> Bool { - self.count > other.count && other.isSubset(of: self) - } - - // Generalizations - - /// Returns a Boolean value that indicates whether the set is a strict - /// superset of the given set. - /// - /// Set *A* is a strict superset of another set *B* if every member of *B* is - /// also a member of *A* and *A* contains at least one element that is *not* - /// a member of *B*. (Ignoring the order the elements appear in the sets.) - /// - /// let a: OrderedSet = [1, 2, 3, 4] - /// let b: OrderedSet = [4, 2, 1] - /// a.isStrictSuperset(of: b.unordered) // true - /// - /// - Parameter other: Another set. - /// - /// - Returns: `true` if `self` is a strict superset of `other`; otherwise, - /// `false`. - /// - /// - Complexity: Expected to be O(`other.count`) on average, if `Element` - /// implements high-quality hashing. - @inlinable - @inline(__always) - public func isStrictSuperset(of other: UnorderedView) -> Bool { - isStrictSuperset(of: other._base) - } - - /// Returns a Boolean value that indicates whether the set is a strict - /// superset of the given set. - /// - /// Set *A* is a strict superset of another set *B* if every member of *B* is - /// also a member of *A* and *A* contains at least one element that is *not* - /// a member of *B*. (Ignoring the order the elements appear in the sets.) - /// - /// let a: OrderedSet = [1, 2, 3, 4] - /// let b: Set = [4, 2, 1] - /// a.isStrictSuperset(of: b) // true - /// - /// - Parameter other: Another set. - /// - /// - Returns: `true` if `self` is a strict superset of `other`; otherwise, - /// `false`. - /// - /// - Complexity: Expected to be O(`other.count`) on average, if `Element` - /// implements high-quality hashing. - @inlinable - public func isStrictSuperset(of other: Set) -> Bool { - self.count > other.count && other.isSubset(of: self) - } - - /// Returns a Boolean value that indicates whether the set is a strict - /// superset of the given sequence. - /// - /// Set *A* is a strict superset of another set *B* if every member of *B* is - /// also a member of *A* and *A* contains at least one element that is *not* - /// a member of *B*. (Ignoring the order the elements appear in the sets.) - /// - /// let a: OrderedSet = [1, 2, 3, 4] - /// let b: Array = [4, 2, 1] - /// a.isStrictSuperset(of: b) // true - /// - /// - Parameter other: A finite sequence of elements. - /// - /// - Returns: `true` if `self` is a strict superset of `other`; otherwise, - /// `false`. - /// - /// - Complexity: Expected to be O(`self.count` + *n*) on average, where *n* - /// is the number of elements in `other`, if `Element` implements - /// high-quality hashing. - @inlinable - public func isStrictSuperset( - of other: S - ) -> Bool where S.Element == Element { - _UnsafeBitset.withTemporaryBitset(capacity: count) { seen in - // Mark elements in `self` that we've seen in `other`. - for item in other { - guard let index = _find(item).index else { - return false - } - if seen.insert(index), seen.count == self.count { - // We've seen enough. - return false - } - } - return seen.count < self.count - } - } -} - -extension OrderedSet { - /// Returns a Boolean value that indicates whether the set has no members in - /// common with the given set. - /// - /// let a: OrderedSet = [1, 2, 3, 4] - /// let b: OrderedSet = [5, 6] - /// a.isDisjoint(with: b) // true - /// - /// - Parameter other: Another set. - /// - /// - Returns: `true` if `self` has no elements in common with `other`; - /// otherwise, `false`. - /// - /// - Complexity: Expected to be O(min(`self.count`, `other.count`)) on - /// average, if `Element` implements high-quality hashing. - @inlinable - public func isDisjoint(with other: Self) -> Bool { - guard !self.isEmpty && !other.isEmpty else { return true } - if self.count <= other.count { - for item in self { - if other.contains(item) { return false } - } - } else { - for item in other { - if self.contains(item) { return false } - } - } - return true - } - - // Generalizations - - /// Returns a Boolean value that indicates whether the set has no members in - /// common with the given set. - /// - /// let a: OrderedSet = [1, 2, 3, 4] - /// let b: OrderedSet = [5, 6] - /// a.isDisjoint(with: b.unordered) // true - /// - /// - Parameter other: Another set. - /// - /// - Returns: `true` if `self` has no elements in common with `other`; - /// otherwise, `false`. - /// - /// - Complexity: Expected to be O(min(`self.count`, `other.count`)) on - /// average, if `Element` implements high-quality hashing. - @inlinable - @inline(__always) - public func isDisjoint(with other: UnorderedView) -> Bool { - isDisjoint(with: other._base) - } - - /// Returns a Boolean value that indicates whether the set has no members in - /// common with the given set. - /// - /// let a: OrderedSet = [1, 2, 3, 4] - /// let b: Set = [5, 6] - /// a.isDisjoint(with: b) // true - /// - /// - Parameter other: Another set. - /// - /// - Returns: `true` if `self` has no elements in common with `other`; - /// otherwise, `false`. - /// - /// - Complexity: Expected to be O(min(`self.count`, `other.count`)) on - /// average, if `Element` implements high-quality hashing. - @inlinable - public func isDisjoint(with other: Set) -> Bool { - guard !self.isEmpty && !other.isEmpty else { return true } - if self.count <= other.count { - for item in self { - if other.contains(item) { return false } - } - } else { - for item in other { - if self.contains(item) { return false } - } - } - return true - } - - /// Returns a Boolean value that indicates whether the set has no members in - /// common with the given sequence. - /// - /// let a: OrderedSet = [1, 2, 3, 4] - /// let b: Array = [5, 6] - /// a.isDisjoint(with: b) // true - /// - /// - Parameter other: A finite sequence of elements. - /// - /// - Returns: `true` if `self` has no elements in common with `other`; - /// otherwise, `false`. - /// - /// - Complexity: Expected to be O(*n*) on average, where *n* is the number of - /// elements in `other`, if `Element` implements high-quality hashing. - @inlinable - public func isDisjoint( - with other: S - ) -> Bool where S.Element == Element { - guard !self.isEmpty else { return true } - for item in other { - if self.contains(item) { return false } - } - return true - } -} - diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+RandomAccessCollection.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+RandomAccessCollection.swift index 7e5eed85..c8b5dc8b 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+RandomAccessCollection.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+RandomAccessCollection.swift @@ -9,6 +9,8 @@ // //===----------------------------------------------------------------------===// +import _CollectionsUtilities + extension OrderedSet: Sequence { /// The type that allows iteration over an ordered set's elements. public typealias Iterator = IndexingIterator @@ -298,3 +300,5 @@ extension OrderedSet: RandomAccessCollection { _elements._failEarlyRangeCheck(range, bounds: bounds) } } + +extension OrderedSet: _UniqueCollection {} diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+SubSequence.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+SubSequence.swift index 9a537a28..e77bd27e 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+SubSequence.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+SubSequence.swift @@ -9,6 +9,8 @@ // //===----------------------------------------------------------------------===// +import _CollectionsUtilities + extension OrderedSet { /// A collection that represents a contiguous slice of an ordered set. /// @@ -103,6 +105,8 @@ extension OrderedSet.SubSequence: Sequence { } } +extension OrderedSet.SubSequence: _UniqueCollection {} + extension OrderedSet.SubSequence: RandomAccessCollection { /// The index type for ordered sets, `Int`. /// diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Debugging.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Debugging.swift index 714841df..65e7a49b 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Debugging.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Debugging.swift @@ -12,6 +12,12 @@ import _CollectionsUtilities extension PersistentDictionary { + /// True if consistency checking is enabled in the implementation of this + /// type, false otherwise. + /// + /// Documented performance promises are null and void when this property + /// returns true -- for example, operations that are documented to take + /// O(1) time might take O(*n*) time, or worse. public static var _isConsistencyCheckingEnabled: Bool { _isCollectionsInternalCheckingEnabled } diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+Debugging.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+Debugging.swift index bcbc1530..58e4cfb7 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+Debugging.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+Debugging.swift @@ -12,6 +12,12 @@ import _CollectionsUtilities extension PersistentSet { + /// True if consistency checking is enabled in the implementation of this + /// type, false otherwise. + /// + /// Documented performance promises are null and void when this property + /// returns true -- for example, operations that are documented to take + /// O(1) time might take O(*n*) time, or worse. public static var _isConsistencyCheckingEnabled: Bool { _isCollectionsInternalCheckingEnabled } diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+Equatable.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+Equatable.swift index c4c388c2..82614846 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+Equatable.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+Equatable.swift @@ -12,6 +12,16 @@ import _CollectionsUtilities extension PersistentSet: Equatable { + /// Returns a Boolean value indicating whether two values are equal. + /// + /// Two persistent sets are considered equal if they contain the same + /// elements, but not necessarily in the same order. + /// + /// - Note: This simply forwards to the ``isEqual(to:)-3m3in`` method. + /// That method has additional overloads that can be used to compare + /// persistent sets with additional types. + /// + /// - Complexity: O(`min(left.count, right.count)`) @inlinable @inline(__always) public static func == (left: Self, right: Self) -> Bool { left.isEqual(to: right) diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+ExpressibleByArrayLiteral.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+ExpressibleByArrayLiteral.swift index b5b45297..d2eb3a8b 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+ExpressibleByArrayLiteral.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+ExpressibleByArrayLiteral.swift @@ -12,19 +12,22 @@ extension PersistentSet: ExpressibleByArrayLiteral { /// Creates a new set from the contents of an array literal. /// - /// Duplicate elements in the literal are allowed, but the resulting ordered - /// set will only contain the first occurrence of each. + /// Duplicate elements in the literal are allowed, but the resulting + /// persistent set will only contain the first occurrence of each. /// /// Do not call this initializer directly. It is used by the compiler when - /// you use an array literal. Instead, create a new ordered set using an array - /// literal as its value by enclosing a comma-separated list of values in - /// square brackets. You can use an array literal anywhere an ordered set is - /// expected by the type context. + /// you use an array literal. Instead, create a new persistent set using an + /// array literal as its value by enclosing a comma-separated list of values + /// in square brackets. You can use an array literal anywhere a peristent set + /// is expected by the type context. /// - /// - Parameter elements: A variadic list of elements of the new ordered set. + /// Like the standard `Set`, persistent sets do not preserve the order of + /// elements inside the array literal. /// - /// - Complexity: O(`elements.count`) if `Element` implements - /// high-quality hashing. + /// - Parameter elements: A variadic list of elements of the new set. + /// + /// - Complexity: O(`elements.count`) if `Element` properly implements + /// hashing. public init(arrayLiteral elements: Element...) { self.init(elements) } diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+Extras.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+Extras.swift index 907bdf41..bd9ff73b 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+Extras.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+Extras.swift @@ -9,6 +9,10 @@ // //===----------------------------------------------------------------------===// +import _CollectionsUtilities + +extension PersistentSet: _UniqueCollection {} + extension PersistentSet { @discardableResult public mutating func remove(at position: Index) -> Element { @@ -18,4 +22,36 @@ extension PersistentSet { precondition(r.remainder == nil) return r.removed.key } + + /// Replace the member at the given index with a new value that compares equal + /// to it. + /// + /// This is useful when equal elements can be distinguished by identity + /// comparison or some other means. Updating a member through this method + /// does not require any hashing operations. + /// + /// Calling this method invalidates all existing indices. + /// + /// - Parameter item: The new value that should replace the original element. + /// `item` must compare equal to the original value. + /// + /// - Parameter index: The index of the element to be replaced. + /// + /// - Returns: The original element that was replaced. + /// + /// - Complexity: Amortized O(1). + public mutating func update(_ member: Element, at index: Index) -> Element { + precondition(_isValid(index), "Invalid index") + precondition(index._path.isOnItem, "Can't get element at endIndex") + _invalidateIndices() + return _UnsafeHandle.update(index._path.node) { + let p = $0.itemPtr(at: index._path.currentItemSlot) + var old = member + precondition( + member == p.pointee.key, + "The replacement item must compare equal to the original") + swap(&p.pointee.key, &old) + return old + } + } } diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+Filter.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+Filter.swift index a204ec6d..31d02a48 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+Filter.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+Filter.swift @@ -10,6 +10,16 @@ //===----------------------------------------------------------------------===// extension PersistentSet { + /// Returns a new persistent set containing the values pairs of the ordered + /// set that satisfy the given predicate. + /// + /// - Parameter isIncluded: A closure that takes a value as its + /// argument and returns a Boolean value indicating whether the value + /// should be included in the returned set. + /// + /// - Returns: A set of the values that `isIncluded` allows. + /// + /// - Complexity: O(`count`) @inlinable public func filter( _ isIncluded: (Element) throws -> Bool diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+Hashable.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+Hashable.swift index c9e3c0d1..42cbf623 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+Hashable.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+Hashable.swift @@ -10,6 +10,10 @@ //===----------------------------------------------------------------------===// extension PersistentSet: Hashable { + /// Hashes the essential components of this value by feeding them into the + /// given hasher. + /// + /// Complexity: O(`count`) @inlinable public func hash(into hasher: inout Hasher) { let copy = hasher diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra Initializers.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra Initializers.swift index 4f5414f4..66861b6e 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra Initializers.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra Initializers.swift @@ -10,11 +10,27 @@ //===----------------------------------------------------------------------===// extension PersistentSet { + /// Creates an empty set. + /// + /// This initializer is equivalent to initializing with an empty array + /// literal. + /// + /// - Complexity: O(1) @inlinable public init() { self.init(_new: ._emptyNode()) } + /// Creates a new set from a finite sequence of items. + /// + /// - Parameter items: The elements to use as members of the new set. + /// The sequence is allowed to contain duplicate elements, but only + /// the first duplicate instance is preserved in the result. + /// + /// - Complexity: This operation is expected to perform O(*n*) + /// hashing and equality comparisons on average (where *n* + /// is the number of elements in the sequence), provided that + /// `Element` properly implements hashing. @inlinable public init(_ items: __owned S) where S.Element == Element { if S.self == Self.self { @@ -27,11 +43,23 @@ extension PersistentSet { } } + /// Creates a new set from a an existing set. This is functionally the same as + /// copying the value of `items` into a new variable. + /// + /// - Parameter items: The elements to use as members of the new set. + /// + /// - Complexity: O(1) @inlinable public init(_ items: __owned Self) { self = items } + /// Creates a new persistent set from the keys view of an existing persistent + /// dictionary. + /// + /// - Parameter items: The elements to use as members of the new set. + /// + /// - Complexity: O(*items.count*) @inlinable public init( _ item: __owned PersistentDictionary.Keys diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra basics.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra basics.swift index 23a844b2..9d62afe6 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra basics.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra basics.swift @@ -12,11 +12,39 @@ import _CollectionsUtilities extension PersistentSet: SetAlgebra { + /// Returns a Boolean value that indicates whether the given element exists + /// in the set. + /// + /// - Parameter element: An element to look for in the set. + /// + /// - Returns: `true` if `member` exists in the set; otherwise, `false`. + /// + /// - Complexity: This operation is expected to perform O(1) hashing and + /// comparison operations on average, provided that `Element` implements + /// high-quality hashing. @inlinable public func contains(_ item: Element) -> Bool { _root.containsKey(.top, item, _Hash(item)) } + /// Insert a new member to this set, if the set doesn't already contain it. + /// + /// - Parameter newMember: The element to insert into the set. + /// + /// - Returns: `(true, newMember)` if `newMember` was not contained in the + /// set. If an element equal to `newMember` was already contained in the + /// set, the method returns `(false, oldMember)`, where `oldMember` is the + /// element that was equal to `newMember`. In some cases, `oldMember` may + /// be distinguishable from `newMember` by identity comparison or some + /// other means. + /// + /// - Complexity: If `newMember` is not already a member of `self`, and if + /// `self` isn't uniquely held, then this operation is expected to copy + /// at most O(log(`count`)) existing members, as long as `Element` properly implements hashing. + /// + /// In addition to this, this operation is expected to perform O(1) + /// hashing/comparison operations on the `Element` type (with the same + /// caveat.) @discardableResult @inlinable public mutating func insert( @@ -41,6 +69,18 @@ extension PersistentSet: SetAlgebra { return r.inserted } + /// Removes the given element from the set. + /// + /// - Parameter member: The element of the set to remove. + /// + /// - Returns: The element equal to `member` if `member` is contained in the + /// set; otherwise, `nil`. In some cases, the returned element may be + /// distinguishable from `newMember` by identity comparison or some other + /// means. + /// + /// - Complexity: The operation is expected to perform amortized + /// O(1) hashing/comparison operations on the `Element` type, if it + /// properly implements hashing. @discardableResult @inlinable public mutating func remove(_ member: Element) -> Element? { @@ -51,6 +91,23 @@ extension PersistentSet: SetAlgebra { return r.removed.key } + /// Inserts the given element into the set unconditionally. + /// + /// If an element equal to `newMember` is already contained in the set, + /// `newMember` replaces the existing element. + /// + /// If `newMember` was not already a member, it gets inserted. + /// + /// - Parameter newMember: An element to insert into the set. + /// + /// - Returns: The original member equal to `newMember` if the set already + /// contained such a member; otherwise, `nil`. In some cases, the returned + /// element may be distinguishable from `newMember` by identity comparison + /// or some other means. + /// + /// - Complexity: This operation is expected to perform O(1) + /// hashing/comparison operations on the element type, provided that + /// `Element` properly implements hashing. @discardableResult @inlinable public mutating func update(with newMember: __owned Element) -> Element? { diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra fluent basics.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra fluent basics.swift index 17545383..45cf7d26 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra fluent basics.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra fluent basics.swift @@ -10,6 +10,23 @@ //===----------------------------------------------------------------------===// extension PersistentSet { + /// Return a new set that contains `newMember` in addition to all existing + /// elements in this set. + /// + /// If `self` already contains `newMember`, then this simply returns self. + /// + /// - Parameter newMember: The element to insert into the set. + /// + /// - Returns: A new set containing `newMember` and all existing members of + /// `self`. + /// + /// - Complexity: The operation is expected to copy at most O(log(`count`)) + /// existing members if `newMember` is not already a member of `self`, + /// as long as `Element` properly implements hashing. + /// + /// In addition to this, this operation is expected to perform O(1) + /// hashing/comparison operations on the `Element` type (with the same + /// caveat.) @inlinable public func inserting(_ newMember: __owned Element) -> Self { let hash = _Hash(newMember) diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isDisjoint.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isDisjoint.swift index e6c40ca7..6f70f20e 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isDisjoint.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isDisjoint.swift @@ -57,7 +57,7 @@ extension PersistentSet { /// let b: PersistentSet = [5, 6] /// a.isDisjoint(with: b) // true /// - /// - Parameter other: A sequence of elements, some of whose elements may + /// - Parameter other: A finite sequence of elements, some of which may /// appear more than once. /// /// - Returns: `true` if `self` has no elements in common with `other`; @@ -69,6 +69,7 @@ extension PersistentSet { public func isDisjoint(with other: S) -> Bool where S.Element == Element { + guard !self.isEmpty else { return true } if S.self == Self.self { return isDisjoint(with: other as! Self) } diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isEqual.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isEqual.swift index b321cbbb..fa2941bd 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isEqual.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isEqual.swift @@ -9,13 +9,41 @@ // //===----------------------------------------------------------------------===// +import _CollectionsUtilities + // FIXME: These are non-standard extensions generalizing ==. extension PersistentSet { + /// Returns a Boolean value indicating whether persistent sets are equal. Two + /// persistent sets are considered equal if they contain the same elements, + /// but not necessarily in the same order. + /// + /// - Parameter other: Another set. + /// + /// - Returns: `true` if the set is equal to `other`; otherwise, `false`. + /// + /// - Complexity: Generally O(`count`), as long as`Element` properly + /// implements hashing. That said, the implementation is careful to take + /// every available shortcut to reduce complexity, e.g. by skipping + /// comparing elements in shared subtrees. @inlinable public func isEqual(to other: Self) -> Bool { _root.isEqual(to: other._root, by: { _, _ in true }) } + /// Returns a Boolean value indicating whether a persistent set compares equal + /// to the given keys view of a persistent dictionary. The two input + /// collections are considered equal if they contain the same elements, + /// but not necessarily in the same order. + /// + /// - Parameter other: The keys view of a persistent dictionary. + /// + /// - Returns: `true` if the set contains exactly the same members as `other`; + /// otherwise, `false`. + /// + /// - Complexity: Generally O(`count`), as long as`Element` properly + /// implements hashing. That said, the implementation is careful to take + /// every available shortcut to reduce complexity, e.g. by skipping + /// comparing elements in shared subtrees. @inlinable public func isEqual( to other: PersistentDictionary.Keys @@ -23,6 +51,29 @@ extension PersistentSet { _root.isEqual(to: other._base._root, by: { _, _ in true }) } + /// Returns a Boolean value indicating whether this persistent set contains + /// the same elements as the given `other` sequence, but not necessarily + /// in the same order. + /// + /// Duplicate items in `other` do not prevent it from comparing equal to + /// `self`. + /// + /// let this: PersistentSet = [0, 1, 5, 6] + /// let that = [5, 5, 0, 1, 1, 6, 5, 0, 1, 6, 6, 5] + /// + /// this.isEqual(to: that) // true + /// + /// - Parameter other: The keys view of a persistent dictionary. + /// + /// - Returns: `true` if the set contains exactly the same members as `other`; + /// otherwise, `false`. This function does not consider the order of + /// elements and it ignores duplicate items in `other`. + /// + /// - Complexity: Generally O(*n*), where *n* is the number of items in + /// `other`, as long as`Element` properly implements hashing. + /// That said, the implementation is careful to take + /// every available shortcut to reduce complexity, e.g. by skipping + /// comparing elements in shared subtrees. @inlinable public func isEqual(to other: S) -> Bool where S.Element == Element @@ -31,15 +82,42 @@ extension PersistentSet { return isEqual(to: other as! Self) } - guard other.underestimatedCount <= self.count else { return false } + if self.isEmpty { + return other.allSatisfy { _ in false } + } + + if other is _UniqueCollection { + // We don't need to create a temporary set. + guard other.underestimatedCount <= self.count else { return false } + var seen = 0 + for item in other { + guard self.contains(item) else { return false } + seen &+= 1 + } + precondition( + seen <= self.count, + // Otherwise other.underestimatedCount != other.count + "Invalid Collection '\(S.self)' (bad underestimatedCount)") + return seen == self.count + } + // FIXME: Would making this a BitSet of seen positions be better? - var seen: _Node = ._emptyNode() - for item in other { + var seen: _Node? = ._emptyNode() + var it = other.makeIterator() + while let item = it.next() { let hash = _Hash(item) guard self._root.containsKey(.top, item, hash) else { return false } - guard seen.insert(.top, (item, ()), hash).inserted - else { return false } + _ = seen!.insert(.top, (item, ()), hash) // Ignore dupes + if seen!.count == self.count { + // We've seen them all. Stop further accounting. + seen = nil + break + } } - return seen.count == self.count + guard seen == nil else { return false } + while let item = it.next() { + guard self.contains(item) else { return false } + } + return true } } diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSubset.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSubset.swift index a02b6d98..9ccb06b8 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSubset.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSubset.swift @@ -95,37 +95,46 @@ extension PersistentSet { return isStrictSubset(of: other as! Self) } - var it = self.makeIterator() - guard let first = it.next() else { - return other.contains(where: { _ in true }) - } - if let match = other._customContainsEquatableElement(first) { - guard match else { return false } - while let item = it.next() { - guard other.contains(item) else { return false } + do { + var it = self.makeIterator() + guard let first = it.next() else { + return other.contains(where: { _ in true }) + } + if let match = other._customContainsEquatableElement(first) { + // Fast path: the sequence has fast containment checks. + guard match else { return false } + while let item = it.next() { + guard other.contains(item) else { return false } + } + return !other.allSatisfy { self.contains($0) } } - return !other.allSatisfy { self.contains($0) } } // FIXME: Would making this a BitSet of seen positions be better? - var seen: _Node? = ._emptyNode() + var seen: _Node = ._emptyNode() + var doneCollecting = false var isStrict = false - for item in other { + var it = other.makeIterator() + while let item = it.next() { let hash = _Hash(item) - if self._root.containsKey(.top, item, hash), - seen?.insert(.top, (item, ()), hash).inserted == true - { - if seen?.count == self.count { + if self._root.containsKey(.top, item, hash) { + if + !doneCollecting, + seen.insert(.top, (item, ()), hash).inserted, + seen.count == self.count + { if isStrict { return true } // Stop collecting seen items -- we just need to decide // strictness now. - seen = nil + seen = ._emptyNode() + doneCollecting = true } } else { isStrict = true - if seen == nil { return true } + if doneCollecting { return true } } } + return false } } diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSuperset.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSuperset.swift index cf64000f..6625c7eb 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSuperset.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSuperset.swift @@ -78,7 +78,7 @@ extension PersistentSet { /// a.isStrictSuperset(of: b.unordered) // true /// /// - Parameter other: A sequence of elements, some of whose elements may - /// appear more than once. + /// appear more than once. (Duplicate items are ignored.) /// /// - Returns: `true` if `self` is a strict subset of `other`; otherwise, /// `false`. diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isSubset.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isSubset.swift index 732acc60..542d1df2 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isSubset.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isSubset.swift @@ -102,7 +102,7 @@ extension PersistentSet { var seen: _Node = ._emptyNode() for item in other { let hash = _Hash(item) - guard contains(item) else { continue } + guard _root.containsKey(.top, item, hash) else { continue } guard seen.insert(.top, (item, ()), hash).inserted else { continue } if seen.count == self.count { return true diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isSuperset.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isSuperset.swift index 304b81c5..58dee925 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isSuperset.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isSuperset.swift @@ -53,9 +53,9 @@ extension PersistentSet { /// e.g. by skipping over parts of the input trees. @inlinable public func isSuperset( - of other: PersistentDictionary + of other: PersistentDictionary.Keys ) -> Bool { - other._root.isSubset(.top, of: self._root) + other._base._root.isSubset(.top, of: self._root) } /// Returns a Boolean value that indicates whether this set is a superset of @@ -69,7 +69,7 @@ extension PersistentSet { /// a.isSuperset(of: b) // true /// /// - Parameter other: A sequence of elements, some of whose elements may - /// appear more than once. + /// appear more than once. (Duplicate items are ignored.) /// /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. /// diff --git a/Sources/_CollectionsTestSupport/AssertionContexts/Combinatorics.swift b/Sources/_CollectionsTestSupport/AssertionContexts/Combinatorics.swift index 6ada6e66..120c0b01 100644 --- a/Sources/_CollectionsTestSupport/AssertionContexts/Combinatorics.swift +++ b/Sources/_CollectionsTestSupport/AssertionContexts/Combinatorics.swift @@ -212,3 +212,68 @@ public func withHiddenCopies< checker(copy) return result } + +/// Run the supplied closure with all subsets `items` in a loop, +/// recording the current subset in the test trace stack. +/// +/// The subsets are generated so that they contain elements in the same order +/// as the original collection. +public func withEverySubset( + _ label: String, + of items: C, + body: ([C.Element]) -> Void +) { + var set: [C.Element] = [] + _withEverySubset(label, of: items, extending: &set, body: body) +} + +func _withEverySubset( + _ label: String, + of items: C, + extending set: inout [C.Element], + body: ([C.Element]) -> Void +) { + guard let item = items.first else { + let entry = TestContext.current.push("\(label): \(set)") + defer { TestContext.current.pop(entry) } + body(set) + return + } + _withEverySubset(label, of: items.dropFirst(), extending: &set, body: body) + set.append(item) + _withEverySubset(label, of: items.dropFirst(), extending: &set, body: body) + set.removeLast() +} + +public func withEveryPermutation( + _ label: String, + of items: C, + body: ([C.Element]) -> Void +) { + func send(_ items: [C.Element]) { + let entry = TestContext.current.push("\(label): \(items)") + body(items) + TestContext.current.pop(entry) + } + + // Heap's algorithm. + var items = Array(items) + send(items) + var i = 1 + var c = [Int](repeating: 0, count: items.count) + while i < items.count { + if c[i] < i { + if i.isMultiple(of: 2) { + items.swapAt(0, i) + } else { + items.swapAt(c[i], i) + } + send(items) + c[i] += 1 + i = 1 + } else { + c[i] = 0 + i += 1 + } + } +} diff --git a/Sources/_CollectionsTestSupport/Utilities/SetAPIChecker.swift b/Sources/_CollectionsTestSupport/Utilities/SetAPIChecker.swift index 691245ac..fede96d9 100644 --- a/Sources/_CollectionsTestSupport/Utilities/SetAPIChecker.swift +++ b/Sources/_CollectionsTestSupport/Utilities/SetAPIChecker.swift @@ -66,13 +66,17 @@ public protocol SetAPIChecker { mutating func formSymmetricDifference(_ other: __owned S) where S.Element == Element - - #if false - // Non-standard extensions - func isEqual(to other: Self) -> Bool - public func isEqual(to other: S) -> Bool - where S.Element == Element - #endif } extension Set: SetAPIChecker {} + + +public protocol SetAPIExtras: SetAPIChecker { + // Non-standard extensions + + mutating func update(_ member: Element, at index: Index) -> Element + + func isEqual(to other: Self) -> Bool + func isEqual(to other: S) -> Bool + where S.Element == Element +} diff --git a/Sources/_CollectionsTestSupport/Utilities/SortedCollectionAPIChecker.swift b/Sources/_CollectionsTestSupport/Utilities/SortedCollectionAPIChecker.swift new file mode 100644 index 00000000..97cd75a4 --- /dev/null +++ b/Sources/_CollectionsTestSupport/Utilities/SortedCollectionAPIChecker.swift @@ -0,0 +1,29 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +import _CollectionsUtilities + +/// This protocol simply lists Collection/Sequence extensions that ought to be +/// customized for sorted collections. +/// +/// Conforming to this protocol admittedly doesn't do much, as the default +/// implementations already exist for most of these requirements +/// (but they aren't doing the right thing). +public protocol SortedCollectionAPIChecker: Collection, _SortedCollection +where Element: Comparable { + // This one actually does not come with a default implementation. + func sorted() -> Self + + // These are also defined on `Sequence`, but the default implementation does + // a linear search, which isn't what we want. + func min() -> Element? + func max() -> Element? +} diff --git a/Sources/_CollectionsTestSupport/MinimalTypes/StringConvertibleValue.swift b/Sources/_CollectionsTestSupport/Utilities/StringConvertibleValue.swift similarity index 100% rename from Sources/_CollectionsTestSupport/MinimalTypes/StringConvertibleValue.swift rename to Sources/_CollectionsTestSupport/Utilities/StringConvertibleValue.swift diff --git a/Sources/_CollectionsUtilities/CMakeLists.txt b/Sources/_CollectionsUtilities/CMakeLists.txt index fd24b7e4..e3572ef5 100644 --- a/Sources/_CollectionsUtilities/CMakeLists.txt +++ b/Sources/_CollectionsUtilities/CMakeLists.txt @@ -8,6 +8,8 @@ See https://swift.org/LICENSE.txt for license information #]] add_library(_CollectionsUtilities + "_SortedCollection.swift" + "_UniqueCollection.swift" "Array+WithContiguousStorage Compatibility.swift" "Debugging.swift" "Descriptions.swift" diff --git a/Sources/_CollectionsUtilities/Debugging.swift b/Sources/_CollectionsUtilities/Debugging.swift index 0006548e..90470b0d 100644 --- a/Sources/_CollectionsUtilities/Debugging.swift +++ b/Sources/_CollectionsUtilities/Debugging.swift @@ -9,6 +9,12 @@ // //===----------------------------------------------------------------------===// +/// True if consistency checking is enabled in the implementation of the +/// Swift Collections package, false otherwise. +/// +/// Documented performance promises are null and void when this property +/// returns true -- for example, operations that are documented to take +/// O(1) time might take O(*n*) time, or worse. @inlinable @inline(__always) public var _isCollectionsInternalCheckingEnabled: Bool { #if COLLECTIONS_INTERNAL_CHECKS diff --git a/Sources/_CollectionsUtilities/_SortedCollection.swift b/Sources/_CollectionsUtilities/_SortedCollection.swift new file mode 100644 index 00000000..22ba8b8b --- /dev/null +++ b/Sources/_CollectionsUtilities/_SortedCollection.swift @@ -0,0 +1,27 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +/// A Collection type that is guaranteed to contain elements in monotonically +/// increasing order. (Duplicates are still allowed unless the collection +/// also conforms to `_UniqueCollection`.) +/// +/// Types conforming to this protocol must also conform to `Collection`, +/// with an `Element` type that conforms to `Comparable`. +/// (However, this protocol does not specify these as explicit requirements, +/// to allow simple conformance tests such as `someValue is _SortedCollection` +/// to be possible.) +/// +/// For any two valid indices `i` and `j` for a conforming collection `c` +/// (both below the end index), it must hold true that if `i < j`, then +/// `c[i] <= c[j]`. +public protocol _SortedCollection {} + +extension Slice: _SortedCollection where Base: _SortedCollection {} diff --git a/Sources/_CollectionsUtilities/_UniqueCollection.swift b/Sources/_CollectionsUtilities/_UniqueCollection.swift new file mode 100644 index 00000000..577b2f28 --- /dev/null +++ b/Sources/_CollectionsUtilities/_UniqueCollection.swift @@ -0,0 +1,37 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +/// A Collection type that is guaranteed not to contain any duplicate elements. +/// +/// Types conforming to this protocol must also conform to `Collection`, +/// with an `Element` type that conforms to `Equatable`. +/// (However, this protocol does not specify these as explicit requirements, +/// to allow simple conformance tests such as `someValue is _SortedCollection` +/// to be possible.) +/// +/// For any two valid indices `i` and `j` in a conforming collection `c` +/// (both below the end index), it must hold true that if `i != j` then +/// `c[i] != c[j]`. +/// +/// Types that conform to this protocol should also implement the following +/// underscored requirements in a way that they never return nil values: +/// +/// - `Sequence._customContainsEquatableElement` +/// - `Collection._customIndexOfEquatableElement` +/// - `Collection._customLastIndexOfEquatableElement` +/// +/// The idea with these is that presumably a collection that can guarantee +/// element uniqueness has a way to quickly find existing elements. +public protocol _UniqueCollection {} + +extension Set: _UniqueCollection {} +extension Dictionary.Keys: _UniqueCollection {} +extension Slice: _UniqueCollection where Base: _UniqueCollection {} diff --git a/Tests/BitCollectionsTests/BitSetTests.swift b/Tests/BitCollectionsTests/BitSetTests.swift index 4cd7659a..dc6599af 100644 --- a/Tests/BitCollectionsTests/BitSetTests.swift +++ b/Tests/BitCollectionsTests/BitSetTests.swift @@ -12,8 +12,15 @@ import XCTest import _CollectionsTestSupport import BitCollections +import OrderedCollections -extension BitSet: SetAPIChecker {} +extension BitSet: SetAPIExtras { + public mutating func update(_ member: Int, at index: Index) -> Int { + fatalError("Not this one though") + } +} + +extension BitSet: SortedCollectionAPIChecker {} final class BitSetTest: CollectionTestCase { func test_empty_initializer() { @@ -976,6 +983,97 @@ final class BitSetTest: CollectionTestCase { } } + func test_isEqual_to_integer_range() { + let a = BitSet(200 ..< 400) + expectTrue(a.isEqual(to: 200 ..< 400)) + expectFalse(a.isEqual(to: 201 ..< 401)) + expectFalse(a.isEqual(to: -1 ..< 200)) + expectFalse(a.isEqual(to: 0 ..< 0)) + expectFalse(a.isEqual(to: 0 ..< 1000)) + expectFalse(a.isEqual(to: 0 ..< 250)) + expectFalse(a.isEqual(to: 270 ..< 400)) + + var b = a + b.remove(300) + expectFalse(b.isEqual(to: 200 ..< 400)) + + let c = BitSet(130 ..< 160) + expectTrue(c.isEqual(to: 130 ..< 160)) + } + + func test_isEqual_to_counted_BitSet() { + let a = BitSet(200 ..< 400) + expectTrue(a.isEqual(to: a.counted)) + } + + func test_isEqual_to_Sequence() { + func check( + _ bits: BitSet, + _ items: S + ) -> Bool where S.Element == Int { + bits.isEqual(to: items) + } + + let bits: BitSet = [3, 6, 8, 11] + expectTrue(check(bits, bits)) + expectTrue(check(bits, bits.counted)) + expectFalse(check(bits, 0 ..< 10)) + + expectFalse(check(bits, [3, 6, 8] as OrderedSet)) + expectTrue(check(bits, [3, 6, 8, 11] as OrderedSet)) + expectFalse(check(bits, [3, 6, 8, 11, 2] as OrderedSet)) + expectFalse(check(bits, [3, 6, 8, 20] as OrderedSet)) + expectFalse(check(bits, [3, 6, 8, -1] as OrderedSet)) + + expectTrue(check([], [] as BitSet)) + expectTrue(check([], [] as BitSet.Counted)) + expectTrue(check([], [] as Set)) + expectTrue(check([], MinimalSequence(elements: []))) + + expectFalse(check([], [1] as BitSet)) + expectFalse(check([], [1] as BitSet.Counted)) + expectFalse(check([], [1] as Set)) + expectFalse( + check([], + MinimalSequence(elements: [1], underestimatedCount: .value(0)))) + + let x1 = MinimalSequence( + elements: [3, 6, 8, 11], + underestimatedCount: .value(0)) + expectTrue(check(bits, x1)) + + let x2 = MinimalSequence( + elements: [3, 6, -1], + underestimatedCount: .value(0)) + expectFalse(check(bits, x2)) + + let x3 = MinimalSequence( + elements: [3, 6, 0], + underestimatedCount: .value(0)) + expectFalse(check(bits, x3)) + + let x4 = MinimalSequence( + elements: [3, 6, 8], + underestimatedCount: .value(0)) + expectFalse(check(bits, x4)) + + let x5 = MinimalSequence( + elements: [3, 6, 8, 11, 3, 6, 8, 11], + underestimatedCount: .value(0)) + expectTrue(check(bits, x5)) // Dupes are okay! + + let x6 = MinimalSequence( + elements: [3, 6, 8, 11, -1], + underestimatedCount: .value(0)) + expectFalse(check(bits, x6)) + + let x7 = MinimalSequence( + elements: [3, 6, 8, 11, 100], + underestimatedCount: .value(0)) + expectFalse(check(bits, x7)) + } + + func test_isSubset() { withEvery("step", in: [1, 5, 16, 23, 24, UInt.bitWidth]) { step in @@ -1014,9 +1112,18 @@ final class BitSetTest: CollectionTestCase { if test.range.lowerBound >= 0 { expectEqual(set.isSubset(of: BitSet(test.range)), expected) expectEqual(forceSequence(BitSet(test.range)), expected) + + expectEqual( + set.isSubset(of: BitSet.Counted(test.range)), expected) + expectEqual( + forceSequence(BitSet.Counted(test.range)), expected) } - expectEqual(set.isSubset(of: Array(test.range)), expected) + let a = Array(test.range) + + expectEqual(set.isSubset(of: a), expected) + expectEqual(set.isSubset(of: a + a), expected) + expectEqual(set.isSubset(of: Set(test.range)), expected) expectEqual(set.isSubset(of: test.range), expected) expectEqual(forceSequence(test.range), expected) @@ -1063,9 +1170,17 @@ final class BitSetTest: CollectionTestCase { if test.range.lowerBound >= 0 { expectEqual(set.isStrictSubset(of: BitSet(test.range)), expected) expectEqual(forceSequence(BitSet(test.range)), expected) + + expectEqual( + set.isStrictSubset(of: BitSet.Counted(test.range)), expected) + expectEqual( + forceSequence(BitSet.Counted(test.range)), expected) } - expectEqual(set.isStrictSubset(of: Array(test.range)), expected) + let a = Array(test.range) + + expectEqual(set.isStrictSubset(of: a), expected) + expectEqual(set.isStrictSubset(of: a + a), expected) expectEqual(set.isStrictSubset(of: test.range), expected) expectEqual(forceSequence(test.range), expected) @@ -1112,9 +1227,17 @@ final class BitSetTest: CollectionTestCase { if test.range.lowerBound >= 0 { expectEqual(set.isSuperset(of: BitSet(test.range)), expected) expectEqual(forceSequence(BitSet(test.range)), expected) + + expectEqual( + set.isSuperset(of: BitSet.Counted(test.range)), expected) + expectEqual( + forceSequence(BitSet.Counted(test.range)), expected) } - expectEqual(set.isSuperset(of: Array(test.range)), expected) + let a = Array(test.range) + + expectEqual(set.isSuperset(of: a), expected) + expectEqual(set.isSuperset(of: a + a), expected) expectEqual(set.isSuperset(of: test.range), expected) expectEqual(forceSequence(test.range), expected) @@ -1161,9 +1284,17 @@ final class BitSetTest: CollectionTestCase { if test.range.lowerBound >= 0 { expectEqual(set.isStrictSuperset(of: BitSet(test.range)), expected) expectEqual(forceSequence(BitSet(test.range)), expected) + + expectEqual( + set.isStrictSuperset(of: BitSet.Counted(test.range)), expected) + expectEqual( + forceSequence(BitSet.Counted(test.range)), expected) } - expectEqual(set.isStrictSuperset(of: Array(test.range)), expected) + let a = Array(test.range) + + expectEqual(set.isStrictSuperset(of: a), expected) + expectEqual(set.isStrictSuperset(of: a + a), expected) expectEqual(set.isStrictSuperset(of: test.range), expected) expectEqual(forceSequence(test.range), expected) @@ -1212,9 +1343,16 @@ final class BitSetTest: CollectionTestCase { if test.range.lowerBound >= 0 { expectEqual(set.isDisjoint(with: BitSet(test.range)), expected) expectEqual(forceSequence(BitSet(test.range)), expected) + + expectEqual( + set.isDisjoint(with: BitSet.Counted(test.range)), expected) + expectEqual( + forceSequence(BitSet.Counted(test.range)), expected) } - expectEqual(set.isDisjoint(with: Array(test.range)), expected) + let a = Array(test.range) + expectEqual(set.isDisjoint(with: a), expected) + expectEqual(set.isDisjoint(with: a + a), expected) expectEqual(set.isDisjoint(with: test.range), expected) expectEqual(forceSequence(test.range), expected) diff --git a/Tests/CollectionsTestSupportTests/CombinatoricsChecks.swift b/Tests/CollectionsTestSupportTests/CombinatoricsChecks.swift new file mode 100644 index 00000000..3309fa0a --- /dev/null +++ b/Tests/CollectionsTestSupportTests/CombinatoricsChecks.swift @@ -0,0 +1,51 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +import XCTest +import _CollectionsTestSupport + +class CombinatoricsTests: CollectionTestCase { + func testEverySubset_smoke() { + func collectSubsets(of set: [Int]) -> Set<[Int]> { + var result: Set<[Int]> = [] + withEverySubset("subset", of: set) { subset in + let r = result.insert(subset) + expectTrue(r.inserted) + } + return result + } + + expectEqual(collectSubsets(of: []), [[]]) + expectEqual(collectSubsets(of: [0]), [[], [0]]) + expectEqual(collectSubsets(of: [0, 1]), [[], [0], [1], [0, 1]]) + expectEqual( + collectSubsets(of: [0, 1, 2]), + [[], [0], [1], [2], [0, 1], [0, 2], [1, 2], [0, 1, 2]]) + } + + func testEveryPermutation_smoke() { + func collectPermutations(of items: [Int]) -> Set<[Int]> { + var result: Set<[Int]> = [] + withEveryPermutation("permutation", of: items) { permutation in + let r = result.insert(permutation) + expectTrue(r.inserted) + } + return result + } + + expectEqual(collectPermutations(of: []), [[]]) + expectEqual(collectPermutations(of: [0]), [[0]]) + expectEqual(collectPermutations(of: [0, 1]), [[0, 1], [1, 0]]) + expectEqual( + collectPermutations(of: [0, 1, 2]), + [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]]) + } +} diff --git a/Tests/HeapTests/HeapTests.swift b/Tests/HeapTests/HeapTests.swift index 4f51b4c8..45792c7e 100644 --- a/Tests/HeapTests/HeapTests.swift +++ b/Tests/HeapTests/HeapTests.swift @@ -10,6 +10,7 @@ //===----------------------------------------------------------------------===// import XCTest +import _CollectionsTestSupport import HeapModule extension Heap { @@ -35,35 +36,35 @@ extension Heap { } } -final class HeapTests: XCTestCase { +final class HeapTests: CollectionTestCase { func test_isEmpty() { var heap = Heap() - XCTAssertTrue(heap.isEmpty) + expectTrue(heap.isEmpty) heap.insert(42) - XCTAssertFalse(heap.isEmpty) + expectFalse(heap.isEmpty) let _ = heap.popMin() - XCTAssertTrue(heap.isEmpty) + expectTrue(heap.isEmpty) } func test_count() { var heap = Heap() - XCTAssertEqual(heap.count, 0) + expectEqual(heap.count, 0) heap.insert(20) - XCTAssertEqual(heap.count, 1) + expectEqual(heap.count, 1) heap.insert(40) - XCTAssertEqual(heap.count, 2) + expectEqual(heap.count, 2) _ = heap.popMin() - XCTAssertEqual(heap.count, 1) + expectEqual(heap.count, 1) } func test_unordered() { let heap = Heap((1...10)) - XCTAssertEqual(Set(heap.unordered), Set(1...10)) + expectEqual(Set(heap.unordered), Set(1...10)) } struct Task: Comparable { @@ -78,26 +79,43 @@ final class HeapTests: XCTestCase { func test_insert() { var heap = Heap() - XCTAssertEqual(heap.count, 0) + expectEqual(heap.count, 0) heap.insert(Task(name: "Hello, world", priority: 50)) - XCTAssertEqual(heap.count, 1) + expectEqual(heap.count, 1) + } + + func test_insert_random() { + let c = 128 + withEvery("seed", in: 0 ..< 5_000) { seed in + var rng = RepeatableRandomNumberGenerator(seed: seed) + let input = (0 ..< c).shuffled(using: &rng) + var heap: Heap = [] + var i = 0 + withEvery("value", in: input) { value in + expectEqual(heap.count, i) + heap.insert(value) + i += 1 + expectEqual(heap.count, i) + } + expectEqualElements(heap.itemsInAscendingOrder(), 0 ..< c) + } } func test_insert_contentsOf() { var heap = Heap() heap.insert(contentsOf: (1...10).shuffled()) - XCTAssertEqual(heap.count, 10) - XCTAssertEqual(heap.popMax(), 10) - XCTAssertEqual(heap.popMin(), 1) + expectEqual(heap.count, 10) + expectEqual(heap.popMax(), 10) + expectEqual(heap.popMin(), 1) heap.insert(contentsOf: (21...50).shuffled()) - XCTAssertEqual(heap.count, 38) - XCTAssertEqual(heap.max(), 50) - XCTAssertEqual(heap.min(), 2) + expectEqual(heap.count, 38) + expectEqual(heap.max(), 50) + expectEqual(heap.min(), 2) heap.insert(contentsOf: [-10, -9, -8, -7, -6, -5].shuffled()) - XCTAssertEqual(heap.count, 44) - XCTAssertEqual(heap.min(), -10) + expectEqual(heap.count, 44) + expectEqual(heap.min(), -10) } func test_insert_contentsOf_withSequenceFunction() { @@ -107,333 +125,344 @@ final class HeapTests: XCTestCase { let evens = sequence(first: 0, next: addTwo(_:)).prefix(20) var heap = Heap(evens) - XCTAssertEqual(heap.count, 20) + expectEqual(heap.count, 20) heap.insert(contentsOf: sequence(first: 1, next: addTwo(_:)).prefix(20)) - XCTAssertEqual(heap.count, 40) + expectEqual(heap.count, 40) - var i = 0 - while let min = heap.popMin() { - XCTAssertEqual(min, i) - i += 1 + withEvery("i", in: 0 ..< 40) { i in + expectNotNil(heap.popMin()) { min in + expectEqual(min, i) + } + } + expectNil(heap.popMin()) + } + + func test_insert_contentsOf_exhaustive() { + withEvery("c", in: 0 ..< 15) { c in + withEverySubset("a", of: 0 ..< c) { a in + let startInput = (0 ..< c).filter { !a.contains($0) } + var heap = Heap(startInput) + heap.insert(contentsOf: a.shuffled()) + expectEqualElements(heap.itemsInAscendingOrder(), 0 ..< c) + } } - XCTAssertEqual(i, 40) } func test_min() { var heap = Heap() - XCTAssertNil(heap.min()) + expectNil(heap.min()) heap.insert(5) - XCTAssertEqual(5, heap.min()) + expectEqual(5, heap.min()) heap.insert(12) - XCTAssertEqual(5, heap.min()) + expectEqual(5, heap.min()) heap.insert(2) - XCTAssertEqual(2, heap.min()) + expectEqual(2, heap.min()) heap.insert(1) - XCTAssertEqual(1, heap.min()) + expectEqual(1, heap.min()) } func test_max() { var heap = Heap() - XCTAssertNil(heap.max()) + expectNil(heap.max()) heap.insert(42) - XCTAssertEqual(42, heap.max()) + expectEqual(42, heap.max()) heap.insert(20) - XCTAssertEqual(42, heap.max()) + expectEqual(42, heap.max()) heap.insert(63) - XCTAssertEqual(63, heap.max()) + expectEqual(63, heap.max()) heap.insert(90) - XCTAssertEqual(90, heap.max()) + expectEqual(90, heap.max()) } func test_popMin() { var heap = Heap() - XCTAssertNil(heap.popMin()) + expectNil(heap.popMin()) heap.insert(7) - XCTAssertEqual(heap.popMin(), 7) + expectEqual(heap.popMin(), 7) heap.insert(12) heap.insert(9) - XCTAssertEqual(heap.popMin(), 9) + expectEqual(heap.popMin(), 9) heap.insert(13) heap.insert(1) heap.insert(4) - XCTAssertEqual(heap.popMin(), 1) + expectEqual(heap.popMin(), 1) for i in (1...20).shuffled() { heap.insert(i) } - XCTAssertEqual(heap.popMin(), 1) - XCTAssertEqual(heap.popMin(), 2) - XCTAssertEqual(heap.popMin(), 3) - XCTAssertEqual(heap.popMin(), 4) - XCTAssertEqual(heap.popMin(), 4) // One 4 was still in the heap from before - XCTAssertEqual(heap.popMin(), 5) - XCTAssertEqual(heap.popMin(), 6) - XCTAssertEqual(heap.popMin(), 7) - XCTAssertEqual(heap.popMin(), 8) - XCTAssertEqual(heap.popMin(), 9) - XCTAssertEqual(heap.popMin(), 10) - XCTAssertEqual(heap.popMin(), 11) - XCTAssertEqual(heap.popMin(), 12) - XCTAssertEqual(heap.popMin(), 12) // One 12 was still in the heap from before - XCTAssertEqual(heap.popMin(), 13) - XCTAssertEqual(heap.popMin(), 13) // One 13 was still in the heap from before - XCTAssertEqual(heap.popMin(), 14) - XCTAssertEqual(heap.popMin(), 15) - XCTAssertEqual(heap.popMin(), 16) - XCTAssertEqual(heap.popMin(), 17) - XCTAssertEqual(heap.popMin(), 18) - XCTAssertEqual(heap.popMin(), 19) - XCTAssertEqual(heap.popMin(), 20) + expectEqual(heap.popMin(), 1) + expectEqual(heap.popMin(), 2) + expectEqual(heap.popMin(), 3) + expectEqual(heap.popMin(), 4) + expectEqual(heap.popMin(), 4) // One 4 was still in the heap from before + expectEqual(heap.popMin(), 5) + expectEqual(heap.popMin(), 6) + expectEqual(heap.popMin(), 7) + expectEqual(heap.popMin(), 8) + expectEqual(heap.popMin(), 9) + expectEqual(heap.popMin(), 10) + expectEqual(heap.popMin(), 11) + expectEqual(heap.popMin(), 12) + expectEqual(heap.popMin(), 12) // One 12 was still in the heap from before + expectEqual(heap.popMin(), 13) + expectEqual(heap.popMin(), 13) // One 13 was still in the heap from before + expectEqual(heap.popMin(), 14) + expectEqual(heap.popMin(), 15) + expectEqual(heap.popMin(), 16) + expectEqual(heap.popMin(), 17) + expectEqual(heap.popMin(), 18) + expectEqual(heap.popMin(), 19) + expectEqual(heap.popMin(), 20) - XCTAssertNil(heap.popMin()) + expectNil(heap.popMin()) } func test_popMax() { var heap = Heap() - XCTAssertNil(heap.popMax()) + expectNil(heap.popMax()) heap.insert(7) - XCTAssertEqual(heap.popMax(), 7) + expectEqual(heap.popMax(), 7) heap.insert(12) heap.insert(9) - XCTAssertEqual(heap.popMax(), 12) + expectEqual(heap.popMax(), 12) heap.insert(13) heap.insert(1) heap.insert(4) - XCTAssertEqual(heap.popMax(), 13) + expectEqual(heap.popMax(), 13) for i in (1...20).shuffled() { heap.insert(i) } - XCTAssertEqual(heap.popMax(), 20) - XCTAssertEqual(heap.popMax(), 19) - XCTAssertEqual(heap.popMax(), 18) - XCTAssertEqual(heap.popMax(), 17) - XCTAssertEqual(heap.popMax(), 16) - XCTAssertEqual(heap.popMax(), 15) - XCTAssertEqual(heap.popMax(), 14) - XCTAssertEqual(heap.popMax(), 13) - XCTAssertEqual(heap.popMax(), 12) - XCTAssertEqual(heap.popMax(), 11) - XCTAssertEqual(heap.popMax(), 10) - XCTAssertEqual(heap.popMax(), 9) - XCTAssertEqual(heap.popMax(), 9) // One 9 was still in the heap from before - XCTAssertEqual(heap.popMax(), 8) - XCTAssertEqual(heap.popMax(), 7) - XCTAssertEqual(heap.popMax(), 6) - XCTAssertEqual(heap.popMax(), 5) - XCTAssertEqual(heap.popMax(), 4) - XCTAssertEqual(heap.popMax(), 4) // One 4 was still in the heap from before - XCTAssertEqual(heap.popMax(), 3) - XCTAssertEqual(heap.popMax(), 2) - XCTAssertEqual(heap.popMax(), 1) - XCTAssertEqual(heap.popMax(), 1) // One 1 was still in the heap from before + expectEqual(heap.popMax(), 20) + expectEqual(heap.popMax(), 19) + expectEqual(heap.popMax(), 18) + expectEqual(heap.popMax(), 17) + expectEqual(heap.popMax(), 16) + expectEqual(heap.popMax(), 15) + expectEqual(heap.popMax(), 14) + expectEqual(heap.popMax(), 13) + expectEqual(heap.popMax(), 12) + expectEqual(heap.popMax(), 11) + expectEqual(heap.popMax(), 10) + expectEqual(heap.popMax(), 9) + expectEqual(heap.popMax(), 9) // One 9 was still in the heap from before + expectEqual(heap.popMax(), 8) + expectEqual(heap.popMax(), 7) + expectEqual(heap.popMax(), 6) + expectEqual(heap.popMax(), 5) + expectEqual(heap.popMax(), 4) + expectEqual(heap.popMax(), 4) // One 4 was still in the heap from before + expectEqual(heap.popMax(), 3) + expectEqual(heap.popMax(), 2) + expectEqual(heap.popMax(), 1) + expectEqual(heap.popMax(), 1) // One 1 was still in the heap from before - XCTAssertNil(heap.popMax()) + expectNil(heap.popMax()) } func test_removeMin() { var heap = Heap((1...20).shuffled()) - XCTAssertEqual(heap.removeMin(), 1) - XCTAssertEqual(heap.removeMin(), 2) - XCTAssertEqual(heap.removeMin(), 3) - XCTAssertEqual(heap.removeMin(), 4) - XCTAssertEqual(heap.removeMin(), 5) - XCTAssertEqual(heap.removeMin(), 6) - XCTAssertEqual(heap.removeMin(), 7) - XCTAssertEqual(heap.removeMin(), 8) - XCTAssertEqual(heap.removeMin(), 9) - XCTAssertEqual(heap.removeMin(), 10) - XCTAssertEqual(heap.removeMin(), 11) - XCTAssertEqual(heap.removeMin(), 12) - XCTAssertEqual(heap.removeMin(), 13) - XCTAssertEqual(heap.removeMin(), 14) - XCTAssertEqual(heap.removeMin(), 15) - XCTAssertEqual(heap.removeMin(), 16) - XCTAssertEqual(heap.removeMin(), 17) - XCTAssertEqual(heap.removeMin(), 18) - XCTAssertEqual(heap.removeMin(), 19) - XCTAssertEqual(heap.removeMin(), 20) + expectEqual(heap.removeMin(), 1) + expectEqual(heap.removeMin(), 2) + expectEqual(heap.removeMin(), 3) + expectEqual(heap.removeMin(), 4) + expectEqual(heap.removeMin(), 5) + expectEqual(heap.removeMin(), 6) + expectEqual(heap.removeMin(), 7) + expectEqual(heap.removeMin(), 8) + expectEqual(heap.removeMin(), 9) + expectEqual(heap.removeMin(), 10) + expectEqual(heap.removeMin(), 11) + expectEqual(heap.removeMin(), 12) + expectEqual(heap.removeMin(), 13) + expectEqual(heap.removeMin(), 14) + expectEqual(heap.removeMin(), 15) + expectEqual(heap.removeMin(), 16) + expectEqual(heap.removeMin(), 17) + expectEqual(heap.removeMin(), 18) + expectEqual(heap.removeMin(), 19) + expectEqual(heap.removeMin(), 20) } func test_removeMax() { var heap = Heap((1...20).shuffled()) - XCTAssertEqual(heap.removeMax(), 20) - XCTAssertEqual(heap.removeMax(), 19) - XCTAssertEqual(heap.removeMax(), 18) - XCTAssertEqual(heap.removeMax(), 17) - XCTAssertEqual(heap.removeMax(), 16) - XCTAssertEqual(heap.removeMax(), 15) - XCTAssertEqual(heap.removeMax(), 14) - XCTAssertEqual(heap.removeMax(), 13) - XCTAssertEqual(heap.removeMax(), 12) - XCTAssertEqual(heap.removeMax(), 11) - XCTAssertEqual(heap.removeMax(), 10) - XCTAssertEqual(heap.removeMax(), 9) - XCTAssertEqual(heap.removeMax(), 8) - XCTAssertEqual(heap.removeMax(), 7) - XCTAssertEqual(heap.removeMax(), 6) - XCTAssertEqual(heap.removeMax(), 5) - XCTAssertEqual(heap.removeMax(), 4) - XCTAssertEqual(heap.removeMax(), 3) - XCTAssertEqual(heap.removeMax(), 2) - XCTAssertEqual(heap.removeMax(), 1) + expectEqual(heap.removeMax(), 20) + expectEqual(heap.removeMax(), 19) + expectEqual(heap.removeMax(), 18) + expectEqual(heap.removeMax(), 17) + expectEqual(heap.removeMax(), 16) + expectEqual(heap.removeMax(), 15) + expectEqual(heap.removeMax(), 14) + expectEqual(heap.removeMax(), 13) + expectEqual(heap.removeMax(), 12) + expectEqual(heap.removeMax(), 11) + expectEqual(heap.removeMax(), 10) + expectEqual(heap.removeMax(), 9) + expectEqual(heap.removeMax(), 8) + expectEqual(heap.removeMax(), 7) + expectEqual(heap.removeMax(), 6) + expectEqual(heap.removeMax(), 5) + expectEqual(heap.removeMax(), 4) + expectEqual(heap.removeMax(), 3) + expectEqual(heap.removeMax(), 2) + expectEqual(heap.removeMax(), 1) } func test_minimumReplacement() { var heap = Heap(stride(from: 0, through: 27, by: 3).shuffled()) - XCTAssertEqual( + expectEqual( heap.itemsInAscendingOrder(), [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]) - XCTAssertEqual(heap.min(), 0) + expectEqual(heap.min(), 0) // No change heap.replaceMin(with: 0) - XCTAssertEqual( + expectEqual( heap.itemsInAscendingOrder(), [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]) - XCTAssertEqual(heap.min(), 0) + expectEqual(heap.min(), 0) // Even smaller heap.replaceMin(with: -1) - XCTAssertEqual( + expectEqual( heap.itemsInAscendingOrder(), [-1, 3, 6, 9, 12, 15, 18, 21, 24, 27]) - XCTAssertEqual(heap.min(), -1) + expectEqual(heap.min(), -1) // Larger, but not enough to usurp heap.replaceMin(with: 2) - XCTAssertEqual( + expectEqual( heap.itemsInAscendingOrder(), [2, 3, 6, 9, 12, 15, 18, 21, 24, 27]) - XCTAssertEqual(heap.min(), 2) + expectEqual(heap.min(), 2) // Larger, moving another element to be the smallest heap.replaceMin(with: 5) - XCTAssertEqual( + expectEqual( heap.itemsInAscendingOrder(), [3, 5, 6, 9, 12, 15, 18, 21, 24, 27]) - XCTAssertEqual(heap.min(), 3) + expectEqual(heap.min(), 3) } func test_maximumReplacement() { var heap = Heap(stride(from: 0, through: 27, by: 3).shuffled()) - XCTAssertEqual( + expectEqual( heap.itemsInAscendingOrder(), [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]) - XCTAssertEqual(heap.max(), 27) + expectEqual(heap.max(), 27) // No change heap.replaceMax(with: 27) - XCTAssertEqual( + expectEqual( heap.itemsInAscendingOrder(), [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]) - XCTAssertEqual(heap.max(), 27) + expectEqual(heap.max(), 27) // Even larger heap.replaceMax(with: 28) - XCTAssertEqual( + expectEqual( heap.itemsInAscendingOrder(), [0, 3, 6, 9, 12, 15, 18, 21, 24, 28]) - XCTAssertEqual(heap.max(), 28) + expectEqual(heap.max(), 28) // Smaller, but not enough to usurp heap.replaceMax(with: 26) - XCTAssertEqual( + expectEqual( heap.itemsInAscendingOrder(), [0, 3, 6, 9, 12, 15, 18, 21, 24, 26]) - XCTAssertEqual(heap.max(), 26) + expectEqual(heap.max(), 26) // Smaller, moving another element to be the largest heap.replaceMax(with: 23) - XCTAssertEqual( + expectEqual( heap.itemsInAscendingOrder(), [0, 3, 6, 9, 12, 15, 18, 21, 23, 24]) - XCTAssertEqual(heap.max(), 24) + expectEqual(heap.max(), 24) // Check the finer details. As these peek into the stored structure, they // may need to be updated whenever the internal format changes. var heap2 = Heap(raw: [1]) - XCTAssertEqual(heap2.max(), 1) - XCTAssertEqual(Array(heap2.unordered), [1]) - XCTAssertEqual(heap2.replaceMax(with: 2), 1) - XCTAssertEqual(heap2.max(), 2) - XCTAssertEqual(Array(heap2.unordered), [2]) + expectEqual(heap2.max(), 1) + expectEqual(Array(heap2.unordered), [1]) + expectEqual(heap2.replaceMax(with: 2), 1) + expectEqual(heap2.max(), 2) + expectEqual(Array(heap2.unordered), [2]) heap2 = Heap(raw: [1, 2]) - XCTAssertEqual(heap2.max(), 2) - XCTAssertEqual(Array(heap2.unordered), [1, 2]) - XCTAssertEqual(heap2.replaceMax(with: 3), 2) - XCTAssertEqual(heap2.max(), 3) - XCTAssertEqual(Array(heap2.unordered), [1, 3]) - XCTAssertEqual(heap2.replaceMax(with: 0), 3) - XCTAssertEqual(heap2.max(), 1) - XCTAssertEqual(Array(heap2.unordered), [0, 1]) + expectEqual(heap2.max(), 2) + expectEqual(Array(heap2.unordered), [1, 2]) + expectEqual(heap2.replaceMax(with: 3), 2) + expectEqual(heap2.max(), 3) + expectEqual(Array(heap2.unordered), [1, 3]) + expectEqual(heap2.replaceMax(with: 0), 3) + expectEqual(heap2.max(), 1) + expectEqual(Array(heap2.unordered), [0, 1]) heap2 = Heap(raw: [5, 20, 31, 16, 8, 7, 18]) - XCTAssertEqual(heap2.max(), 31) - XCTAssertEqual(Array(heap2.unordered), [5, 20, 31, 16, 8, 7, 18]) - XCTAssertEqual(heap2.replaceMax(with: 29), 31) - XCTAssertEqual(Array(heap2.unordered), [5, 20, 29, 16, 8, 7, 18]) - XCTAssertEqual(heap2.max(), 29) - XCTAssertEqual(heap2.replaceMax(with: 19), 29) - XCTAssertEqual(Array(heap2.unordered), [5, 20, 19, 16, 8, 7, 18]) - XCTAssertEqual(heap2.max(), 20) - XCTAssertEqual(heap2.replaceMax(with: 15), 20) - XCTAssertEqual(Array(heap2.unordered), [5, 16, 19, 15, 8, 7, 18]) - XCTAssertEqual(heap2.max(), 19) - XCTAssertEqual(heap2.replaceMax(with: 4), 19) - XCTAssertEqual(Array(heap2.unordered), [4, 16, 18, 15, 8, 7, 5]) - XCTAssertEqual(heap2.max(), 18) + expectEqual(heap2.max(), 31) + expectEqual(Array(heap2.unordered), [5, 20, 31, 16, 8, 7, 18]) + expectEqual(heap2.replaceMax(with: 29), 31) + expectEqual(Array(heap2.unordered), [5, 20, 29, 16, 8, 7, 18]) + expectEqual(heap2.max(), 29) + expectEqual(heap2.replaceMax(with: 19), 29) + expectEqual(Array(heap2.unordered), [5, 20, 19, 16, 8, 7, 18]) + expectEqual(heap2.max(), 20) + expectEqual(heap2.replaceMax(with: 15), 20) + expectEqual(Array(heap2.unordered), [5, 16, 19, 15, 8, 7, 18]) + expectEqual(heap2.max(), 19) + expectEqual(heap2.replaceMax(with: 4), 19) + expectEqual(Array(heap2.unordered), [4, 16, 18, 15, 8, 7, 5]) + expectEqual(heap2.max(), 18) } // MARK: - func test_min_struct() { var heap = Heap() - XCTAssertNil(heap.min()) + expectNil(heap.min()) let firstTask = Task(name: "Do something", priority: 10) heap.insert(firstTask) - XCTAssertEqual(heap.min(), firstTask) + expectEqual(heap.min(), firstTask) let higherPriorityTask = Task(name: "Urgent", priority: 100) heap.insert(higherPriorityTask) - XCTAssertEqual(heap.min(), firstTask) + expectEqual(heap.min(), firstTask) let lowerPriorityTask = Task(name: "Get this done today", priority: 1) heap.insert(lowerPriorityTask) - XCTAssertEqual(heap.min(), lowerPriorityTask) + expectEqual(heap.min(), lowerPriorityTask) } func test_max_struct() { var heap = Heap() - XCTAssertNil(heap.max()) + expectNil(heap.max()) let firstTask = Task(name: "Do something", priority: 10) heap.insert(firstTask) - XCTAssertEqual(heap.max(), firstTask) + expectEqual(heap.max(), firstTask) let lowerPriorityTask = Task(name: "Get this done today", priority: 1) heap.insert(lowerPriorityTask) - XCTAssertEqual(heap.max(), firstTask) + expectEqual(heap.max(), firstTask) let higherPriorityTask = Task(name: "Urgent", priority: 100) heap.insert(higherPriorityTask) - XCTAssertEqual(heap.max(), higherPriorityTask) + expectEqual(heap.max(), higherPriorityTask) } func test_popMin_struct() { var heap = Heap() - XCTAssertNil(heap.popMin()) + expectNil(heap.popMin()) let lowPriorityTask = Task(name: "Do something when you have time", priority: 1) heap.insert(lowPriorityTask) @@ -444,15 +473,15 @@ final class HeapTests: XCTestCase { let urgentTask = Task(name: "Urgent", priority: 100) heap.insert(urgentTask) - XCTAssertEqual(heap.popMin(), lowPriorityTask) - XCTAssertEqual(heap.popMin(), highPriorityTask) - XCTAssertEqual(heap.popMin(), urgentTask) - XCTAssertNil(heap.popMin()) + expectEqual(heap.popMin(), lowPriorityTask) + expectEqual(heap.popMin(), highPriorityTask) + expectEqual(heap.popMin(), urgentTask) + expectNil(heap.popMin()) } func test_popMax_struct() { var heap = Heap() - XCTAssertNil(heap.popMax()) + expectNil(heap.popMax()) let lowPriorityTask = Task(name: "Do something when you have time", priority: 1) heap.insert(lowPriorityTask) @@ -463,53 +492,74 @@ final class HeapTests: XCTestCase { let urgentTask = Task(name: "Urgent", priority: 100) heap.insert(urgentTask) - XCTAssertEqual(heap.popMax(), urgentTask) - XCTAssertEqual(heap.popMax(), highPriorityTask) - XCTAssertEqual(heap.popMax(), lowPriorityTask) - XCTAssertNil(heap.popMax()) + expectEqual(heap.popMax(), urgentTask) + expectEqual(heap.popMax(), highPriorityTask) + expectEqual(heap.popMax(), lowPriorityTask) + expectNil(heap.popMax()) } // MARK: - func test_initializer_fromCollection() { var heap = Heap((1...20).shuffled()) - XCTAssertEqual(heap.max(), 20) + expectEqual(heap.max(), 20) - XCTAssertEqual(heap.popMin(), 1) - XCTAssertEqual(heap.popMax(), 20) - XCTAssertEqual(heap.popMin(), 2) - XCTAssertEqual(heap.popMax(), 19) - XCTAssertEqual(heap.popMin(), 3) - XCTAssertEqual(heap.popMax(), 18) - XCTAssertEqual(heap.popMin(), 4) - XCTAssertEqual(heap.popMax(), 17) - XCTAssertEqual(heap.popMin(), 5) - XCTAssertEqual(heap.popMax(), 16) - XCTAssertEqual(heap.popMin(), 6) - XCTAssertEqual(heap.popMax(), 15) - XCTAssertEqual(heap.popMin(), 7) - XCTAssertEqual(heap.popMax(), 14) - XCTAssertEqual(heap.popMin(), 8) - XCTAssertEqual(heap.popMax(), 13) - XCTAssertEqual(heap.popMin(), 9) - XCTAssertEqual(heap.popMax(), 12) - XCTAssertEqual(heap.popMin(), 10) - XCTAssertEqual(heap.popMax(), 11) + expectEqual(heap.popMin(), 1) + expectEqual(heap.popMax(), 20) + expectEqual(heap.popMin(), 2) + expectEqual(heap.popMax(), 19) + expectEqual(heap.popMin(), 3) + expectEqual(heap.popMax(), 18) + expectEqual(heap.popMin(), 4) + expectEqual(heap.popMax(), 17) + expectEqual(heap.popMin(), 5) + expectEqual(heap.popMax(), 16) + expectEqual(heap.popMin(), 6) + expectEqual(heap.popMax(), 15) + expectEqual(heap.popMin(), 7) + expectEqual(heap.popMax(), 14) + expectEqual(heap.popMin(), 8) + expectEqual(heap.popMax(), 13) + expectEqual(heap.popMin(), 9) + expectEqual(heap.popMax(), 12) + expectEqual(heap.popMin(), 10) + expectEqual(heap.popMax(), 11) } func test_initializer_fromSequence() { let heap = Heap((1...).prefix(20)) - XCTAssertEqual(heap.count, 20) + expectEqual(heap.count, 20) } func test_initializer_fromArrayLiteral() { var heap: Heap = [1, 3, 5, 7, 9] - XCTAssertEqual(heap.count, 5) + expectEqual(heap.count, 5) - XCTAssertEqual(heap.popMax(), 9) - XCTAssertEqual(heap.popMax(), 7) - XCTAssertEqual(heap.popMax(), 5) - XCTAssertEqual(heap.popMax(), 3) - XCTAssertEqual(heap.popMax(), 1) + expectEqual(heap.popMax(), 9) + expectEqual(heap.popMax(), 7) + expectEqual(heap.popMax(), 5) + expectEqual(heap.popMax(), 3) + expectEqual(heap.popMax(), 1) + } + + func test_initializer_fromSequence_random() { + withEvery("c", in: 0 ... 128) { c in + withEvery( + "seed", in: 0 ..< Swift.min((c + 2) * (c + 1), 100) + ) { seed in + var rng = RepeatableRandomNumberGenerator(seed: seed) + let input = (0 ..< c).shuffled(using: &rng) + let heap = Heap(input) + if c > 0 { + expectEqual(heap.min(), 0) + expectEqual(heap.max(), c - 1) + expectEqualElements(heap.itemsInAscendingOrder(), 0 ..< c) + } else { + expectNil(heap.min()) + expectNil(heap.max()) + expectEqualElements(heap.itemsInAscendingOrder(), []) + } + } + } } } diff --git a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSet.UnorderedView Tests.swift b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSet.UnorderedView Tests.swift index b9021ca6..4d166253 100644 --- a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSet.UnorderedView Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSet.UnorderedView Tests.swift @@ -13,6 +13,9 @@ import XCTest @_spi(Testing) import OrderedCollections import _CollectionsTestSupport +// Note: This cannot really work unless `UnorderedView` becomes a Collection. +// extension OrderedSet.UnorderedView: SetAPIChecker {} + class OrderedSetUnorderedViewTests: CollectionTestCase { func test_unordered_insert() { withEvery("count", in: 0 ..< 20) { count in diff --git a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift index a0f09547..fbec54fa 100644 --- a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift +++ b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift @@ -13,7 +13,7 @@ import XCTest @_spi(Testing) import OrderedCollections import _CollectionsTestSupport -extension OrderedSet: SetAPIChecker {} +extension OrderedSet: SetAPIExtras {} class OrderedSetTests: CollectionTestCase { func test_init_uncheckedUniqueElements_concrete() { @@ -1198,167 +1198,176 @@ class OrderedSetTests: CollectionTestCase { } } - func test_isSubset_Self() { + func test_isEqual() { + withEvery("unit", in: [1, 3, 7, 10, 20, 50]) { unit in + SampleRanges(unit: unit).withEveryPair { r1, r2 in + let expected = Set(r1) == Set(r2) + let a = OrderedSet(r1) + let b = OrderedSet(r2) + let c = Set(r2) + let d = Array(r2) + + func checkSequence( + _ set: OrderedSet, + _ other: S + ) -> Bool where S.Element == Int { + set.isEqual(to: other) + } + + expectEqual(a.isEqual(to: b), expected) + expectEqual(a.isEqual(to: b.unordered), expected) + expectEqual(a.isEqual(to: c), expected) + + expectEqual(checkSequence(a, b), expected) + expectEqual(checkSequence(a, c), expected) + expectEqual(a.isEqual(to: d), expected) + expectEqual(a.isEqual(to: d + d), expected) + expectEqual(a.isEqual(to: r2), expected) + } + } + } + + func test_isSubset() { withEvery("unit", in: [1, 3, 7, 10, 20, 50]) { unit in SampleRanges(unit: unit).withEveryPair { r1, r2 in let expected = Set(r1).isSubset(of: r2) let a = OrderedSet(r1) let b = OrderedSet(r2) + let c = Set(r2) + let d = Array(r2) + + func checkSequence( + _ set: OrderedSet, + _ other: S + ) -> Bool where S.Element == Int { + set.isSubset(of: other) + } + expectEqual(a.isSubset(of: b), expected) + expectEqual(a.isSubset(of: b.unordered), expected) + expectEqual(a.isSubset(of: c), expected) + + expectEqual(checkSequence(a, b), expected) + expectEqual(checkSequence(a, c), expected) + expectEqual(a.isSubset(of: d), expected) + expectEqual(a.isSubset(of: d + d), expected) + expectEqual(a.isSubset(of: r2), expected) } } } - func test_isSubset_Set() { - withEvery("unit", in: [1, 3, 7, 10, 20, 50]) { unit in - SampleRanges(unit: unit).withEveryPair { r1, r2 in - let expected = Set(r1).isSubset(of: r2) - let a = OrderedSet(r1) - let b = Set(r2) - expectEqual(a.isSubset(of: b), expected) - } - } - } - - func test_isSubset_generic() { - withEvery("unit", in: [1, 3, 7, 10, 20, 50]) { unit in - SampleRanges(unit: unit).withEveryPair { r1, r2 in - let expected = Set(r1).isSubset(of: r2) - let a = OrderedSet(r1) - let b = r2 - expectEqual(a.isSubset(of: b), expected) - } - } - } - - func test_isSuperset_Self() { + func test_isSuperset() { withEvery("unit", in: [1, 3, 7, 10, 20, 50]) { unit in SampleRanges(unit: unit).withEveryPair { r1, r2 in let expected = Set(r1).isSuperset(of: r2) let a = OrderedSet(r1) let b = OrderedSet(r2) + let c = Set(r2) + let d = Array(r2) + + func checkSequence( + _ set: OrderedSet, + _ other: S + ) -> Bool where S.Element == Int { + set.isSuperset(of: other) + } + expectEqual(a.isSuperset(of: b), expected) + expectEqual(a.isSuperset(of: b.unordered), expected) + expectEqual(a.isSuperset(of: c), expected) + + expectEqual(checkSequence(a, b), expected) + expectEqual(checkSequence(a, c), expected) + expectEqual(a.isSuperset(of: d), expected) + expectEqual(a.isSuperset(of: d + d), expected) + expectEqual(a.isSuperset(of: r2), expected) } } } - func test_isSuperset_Set() { - withEvery("unit", in: [1, 3, 7, 10, 20, 50]) { unit in - SampleRanges(unit: unit).withEveryPair { r1, r2 in - let expected = Set(r1).isSuperset(of: r2) - let a = OrderedSet(r1) - let b = Set(r2) - expectEqual(a.isSuperset(of: b), expected) - } - } - } - - func test_isSuperset_generic() { - withEvery("unit", in: [1, 3, 7, 10, 20, 50]) { unit in - SampleRanges(unit: unit).withEveryPair { r1, r2 in - let expected = Set(r1).isSuperset(of: r2) - let a = OrderedSet(r1) - let b = r2 - expectEqual(a.isSuperset(of: b), expected) - } - } - } - - func test_isStrictSubset_Self() { + func test_isStrictSubset() { withEvery("unit", in: [1, 3, 7, 10, 20, 50]) { unit in SampleRanges(unit: unit).withEveryPair { r1, r2 in let expected = Set(r1).isStrictSubset(of: r2) let a = OrderedSet(r1) let b = OrderedSet(r2) + let c = Set(r2) + let d = Array(r2) + + func checkSequence( + _ set: OrderedSet, + _ other: S + ) -> Bool where S.Element == Int { + set.isStrictSubset(of: other) + } + expectEqual(a.isStrictSubset(of: b), expected) + expectEqual(a.isStrictSubset(of: b.unordered), expected) + expectEqual(a.isStrictSubset(of: c), expected) + + expectEqual(checkSequence(a, b), expected) + expectEqual(checkSequence(a, c), expected) + expectEqual(a.isStrictSubset(of: d), expected) + expectEqual(a.isStrictSubset(of: d + d), expected) + expectEqual(a.isStrictSubset(of: r2), expected) } } } - func test_isStrictSubset_Set() { - withEvery("unit", in: [1, 3, 7, 10, 20, 50]) { unit in - SampleRanges(unit: unit).withEveryPair { r1, r2 in - let expected = Set(r1).isStrictSubset(of: r2) - let a = OrderedSet(r1) - let b = Set(r2) - expectEqual(a.isStrictSubset(of: b), expected) - } - } - } - - func test_isStrictSubset_generic() { - withEvery("unit", in: [1, 3, 7, 10, 20, 50]) { unit in - SampleRanges(unit: unit).withEveryPair { r1, r2 in - let expected = Set(r1).isStrictSubset(of: r2) - let a = OrderedSet(r1) - let b = r2 - expectEqual(a.isStrictSubset(of: b), expected) - } - } - } - - func test_isStrictSuperset_Self() { + func test_isStrictSuperset() { withEvery("unit", in: [1, 3, 7, 10, 20, 50]) { unit in SampleRanges(unit: unit).withEveryPair { r1, r2 in let expected = Set(r1).isStrictSuperset(of: r2) let a = OrderedSet(r1) let b = OrderedSet(r2) + let c = Set(r2) + let d = Array(r2) + + func checkSequence( + _ set: OrderedSet, + _ other: S + ) -> Bool where S.Element == Int { + set.isStrictSuperset(of: other) + } + expectEqual(a.isStrictSuperset(of: b), expected) + expectEqual(a.isStrictSuperset(of: b.unordered), expected) + expectEqual(a.isStrictSuperset(of: c), expected) + + expectEqual(checkSequence(a, b), expected) + expectEqual(checkSequence(a, c), expected) + expectEqual(a.isStrictSuperset(of: d), expected) + expectEqual(a.isStrictSuperset(of: d + d), expected) + expectEqual(a.isStrictSuperset(of: r2), expected) } } } - func test_isStrictSuperset_Set() { - withEvery("unit", in: [1, 3, 7, 10, 20, 50]) { unit in - SampleRanges(unit: unit).withEveryPair { r1, r2 in - let expected = Set(r1).isStrictSuperset(of: r2) - let a = OrderedSet(r1) - let b = Set(r2) - expectEqual(a.isStrictSuperset(of: b), expected) - } - } - } - - func test_isStrictSuperset_generic() { - withEvery("unit", in: [1, 3, 7, 10, 20, 50]) { unit in - SampleRanges(unit: unit).withEveryPair { r1, r2 in - let expected = Set(r1).isStrictSuperset(of: r2) - let a = OrderedSet(r1) - let b = r2 - expectEqual(a.isStrictSuperset(of: b), expected) - } - } - } - - func test_isDisjoint_Self() { + func test_isDisjoint() { withEvery("unit", in: [1, 3, 7, 10, 20, 50]) { unit in SampleRanges(unit: unit).withEveryPair { r1, r2 in let expected = Set(r1).isDisjoint(with: r2) let a = OrderedSet(r1) let b = OrderedSet(r2) - expectEqual(a.isDisjoint(with: b), expected) - } - } - } + let c = Set(r2) + let d = Array(r2) - func test_isDisjoint_Set() { - withEvery("unit", in: [1, 3, 7, 10, 20, 50]) { unit in - SampleRanges(unit: unit).withEveryPair { r1, r2 in - let expected = Set(r1).isDisjoint(with: r2) - let a = OrderedSet(r1) - let b = Set(r2) - expectEqual(a.isDisjoint(with: b), expected) - } - } - } + func checkSequence( + _ set: OrderedSet, + _ other: S + ) -> Bool where S.Element == Int { + set.isDisjoint(with: other) + } - func test_isDisjoint_generic() { - withEvery("unit", in: [1, 3, 7, 10, 20, 50]) { unit in - SampleRanges(unit: unit).withEveryPair { r1, r2 in - let expected = Set(r1).isDisjoint(with: r2) - let a = OrderedSet(r1) - let b = r2 expectEqual(a.isDisjoint(with: b), expected) + expectEqual(a.isDisjoint(with: b.unordered), expected) + expectEqual(a.isDisjoint(with: c), expected) + + expectEqual(checkSequence(a, b), expected) + expectEqual(checkSequence(a, c), expected) + expectEqual(a.isDisjoint(with: d), expected) + expectEqual(a.isDisjoint(with: d + d), expected) + expectEqual(a.isDisjoint(with: r2), expected) } } } diff --git a/Tests/PersistentCollectionsTests/PersistentSet Tests.swift b/Tests/PersistentCollectionsTests/PersistentSet Tests.swift index 380504f6..796893b0 100644 --- a/Tests/PersistentCollectionsTests/PersistentSet Tests.swift +++ b/Tests/PersistentCollectionsTests/PersistentSet Tests.swift @@ -12,7 +12,7 @@ import _CollectionsTestSupport import PersistentCollections -extension PersistentSet: SetAPIChecker {} +extension PersistentSet: SetAPIExtras {} class PersistentSetTests: CollectionTestCase { func test_init_empty() { @@ -205,6 +205,7 @@ class PersistentSetTests: CollectionTestCase { withEverySubset("b", of: testItems) { b in let y = PersistentSet(b) let v = Set(b) + let z = PersistentDictionary(uniqueKeysWithValues: b.map { ($0, $0) }) let reference = (u == v) @@ -217,9 +218,11 @@ class PersistentSetTests: CollectionTestCase { } expectEqual(x.isEqual(to: y), reference) + expectEqual(x.isEqual(to: z.keys), reference) expectEqual(checkSequence(x, y), reference) expectEqual(x.isEqual(to: v), reference) expectEqual(x.isEqual(to: b), reference) + expectEqual(x.isEqual(to: b + b), reference) } } } @@ -232,6 +235,7 @@ class PersistentSetTests: CollectionTestCase { withEverySubset("b", of: testItems) { b in let y = PersistentSet(b) let v = Set(b) + let z = PersistentDictionary(uniqueKeysWithValues: b.map { ($0, $0) }) let reference = u.isSubset(of: v) @@ -244,9 +248,11 @@ class PersistentSetTests: CollectionTestCase { } expectEqual(x.isSubset(of: y), reference) + expectEqual(x.isSubset(of: z.keys), reference) expectEqual(checkSequence(x, y), reference) expectEqual(x.isSubset(of: v), reference) expectEqual(x.isSubset(of: b), reference) + expectEqual(x.isSubset(of: b + b), reference) } } } @@ -259,6 +265,7 @@ class PersistentSetTests: CollectionTestCase { withEverySubset("b", of: testItems) { b in let y = PersistentSet(b) let v = Set(b) + let z = PersistentDictionary(uniqueKeysWithValues: b.map { ($0, $0) }) let reference = u.isSuperset(of: v) @@ -271,14 +278,16 @@ class PersistentSetTests: CollectionTestCase { } expectEqual(x.isSuperset(of: y), reference) + expectEqual(x.isSuperset(of: z.keys), reference) expectEqual(checkSequence(x, y), reference) expectEqual(x.isSuperset(of: v), reference) expectEqual(x.isSuperset(of: b), reference) + expectEqual(x.isSuperset(of: b + b), reference) } } } - func test_isStrictsubset_exhaustive() { + func test_isStrictSubset_exhaustive() { withEverySubset("a", of: testItems) { a in let x = PersistentSet(a) let u = Set(a) @@ -286,6 +295,7 @@ class PersistentSetTests: CollectionTestCase { withEverySubset("b", of: testItems) { b in let y = PersistentSet(b) let v = Set(b) + let z = PersistentDictionary(uniqueKeysWithValues: b.map { ($0, $0) }) let reference = u.isStrictSubset(of: v) @@ -298,9 +308,11 @@ class PersistentSetTests: CollectionTestCase { } expectEqual(x.isStrictSubset(of: y), reference) + expectEqual(x.isStrictSubset(of: z.keys), reference) expectEqual(checkSequence(x, y), reference) expectEqual(x.isStrictSubset(of: v), reference) expectEqual(x.isStrictSubset(of: b), reference) + expectEqual(x.isStrictSubset(of: b + b), reference) } } } @@ -313,6 +325,7 @@ class PersistentSetTests: CollectionTestCase { withEverySubset("b", of: testItems) { b in let y = PersistentSet(b) let v = Set(b) + let z = PersistentDictionary(uniqueKeysWithValues: b.map { ($0, $0) }) let reference = u.isStrictSuperset(of: v) @@ -325,9 +338,11 @@ class PersistentSetTests: CollectionTestCase { } expectEqual(x.isStrictSuperset(of: y), reference) + expectEqual(x.isStrictSuperset(of: z.keys), reference) expectEqual(checkSequence(x, y), reference) expectEqual(x.isStrictSuperset(of: v), reference) expectEqual(x.isStrictSuperset(of: b), reference) + expectEqual(x.isStrictSuperset(of: b + b), reference) } } } @@ -340,7 +355,7 @@ class PersistentSetTests: CollectionTestCase { withEverySubset("b", of: testItems) { b in let y = PersistentSet(b) let v = Set(b) - + let z = PersistentDictionary(uniqueKeysWithValues: b.map { ($0, $0) }) let reference = u.isDisjoint(with: v) func checkSequence( @@ -352,9 +367,11 @@ class PersistentSetTests: CollectionTestCase { } expectEqual(x.isDisjoint(with: y), reference) + expectEqual(x.isDisjoint(with: z.keys), reference) expectEqual(checkSequence(x, y), reference) expectEqual(x.isDisjoint(with: v), reference) expectEqual(x.isDisjoint(with: b), reference) + expectEqual(x.isDisjoint(with: b + b), reference) } } } @@ -476,4 +493,23 @@ class PersistentSetTests: CollectionTestCase { } } } + + func test_update_at() { + withEverySubset("a", of: testItems) { a in + withEvery("offset", in: 0 ..< a.count) { offset in + withEvery("isShared", in: [false, true]) { isShared in + withLifetimeTracking { tracker in + var x = PersistentSet(tracker.instances(for: a)) + let i = x.firstIndex { $0.payload == a[offset] }! + let replacement = tracker.instance(for: a[offset]) + withHiddenCopies(if: isShared, of: &x) { x in + let old = x.update(replacement, at: i) + expectEqual(old, replacement) + expectNotIdentical(old, replacement) + } + } + } + } + } + } } diff --git a/Tests/PersistentCollectionsTests/Utilities.swift b/Tests/PersistentCollectionsTests/Utilities.swift index 676e1d3b..428ee13a 100644 --- a/Tests/PersistentCollectionsTests/Utilities.swift +++ b/Tests/PersistentCollectionsTests/Utilities.swift @@ -241,30 +241,3 @@ func mutate( ) rethrows -> R { try body(&value) } - -func withEverySubset( - _ label: String, - of items: C, - body: ([C.Element]) -> Void -) { - var set: [C.Element] = [] - _withEverySubset(label, of: items, extending: &set, body: body) -} - -func _withEverySubset( - _ label: String, - of items: C, - extending set: inout [C.Element], - body: ([C.Element]) -> Void -) { - guard let item = items.first else { - let entry = TestContext.current.push("\(label): \(set)") - defer { TestContext.current.pop(entry) } - body(set) - return - } - _withEverySubset(label, of: items.dropFirst(), extending: &set, body: body) - set.append(item) - _withEverySubset(label, of: items.dropFirst(), extending: &set, body: body) - set.removeLast() -}