diff --git a/.swiftpm/xcode/xcshareddata/xcschemes/UniquedModule.xcscheme b/.swiftpm/xcode/xcshareddata/xcschemes/UniquedModule.xcscheme deleted file mode 100644 index 76faf301..00000000 --- a/.swiftpm/xcode/xcshareddata/xcschemes/UniquedModule.xcscheme +++ /dev/null @@ -1,78 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Package.swift b/Package.swift index b53b55dd..868936e1 100644 --- a/Package.swift +++ b/Package.swift @@ -54,7 +54,6 @@ let package = Package( .library(name: "Collections", targets: ["Collections"]), .library(name: "DequeModule", targets: ["DequeModule"]), .library(name: "OrderedCollections", targets: ["OrderedCollections"]), - .library(name: "UniquedModule", targets: ["UniquedModule"]), .executable(name: "swift-collections-benchmark", targets: ["swift-collections-benchmark"]), ], @@ -126,16 +125,6 @@ let package = Package( name: "OrderedCollectionsTests", dependencies: ["OrderedCollections", "CollectionsTestSupport"], swiftSettings: settings), - - // Uniqued - .target( - name: "UniquedModule", - dependencies: ["DequeModule"], - swiftSettings: settings), - .testTarget( - name: "UniquedTests", - dependencies: ["UniquedModule", "CollectionsTestSupport"], - swiftSettings: settings), ], cxxLanguageStandard: .cxx1z ) diff --git a/Sources/UniquedModule/RandomAccessCollection+Offsets.swift b/Sources/UniquedModule/RandomAccessCollection+Offsets.swift deleted file mode 100644 index 2b14f016..00000000 --- a/Sources/UniquedModule/RandomAccessCollection+Offsets.swift +++ /dev/null @@ -1,27 +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 -// -//===----------------------------------------------------------------------===// - -extension RandomAccessCollection { - @inline(__always) - internal func _index(at offset: Int) -> Index { - index(startIndex, offsetBy: offset) - } - - @inline(__always) - internal func _offset(of index: Index) -> Int { - distance(from: startIndex, to: index) - } - - @inline(__always) - internal subscript(_offset offset: Int) -> Element { - self[_index(at: offset)] - } -} diff --git a/Sources/UniquedModule/Uniqued+Codable.swift b/Sources/UniquedModule/Uniqued+Codable.swift deleted file mode 100644 index 56b04540..00000000 --- a/Sources/UniquedModule/Uniqued+Codable.swift +++ /dev/null @@ -1,51 +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 -// -//===----------------------------------------------------------------------===// - -extension Uniqued: Encodable where Base: Encodable { - /// Encodes the elements of this deque into the given encoder in an unkeyed - /// container. - /// - /// This function throws an error if any values are invalid for the given - /// encoder's format. - /// - /// - Parameter encoder: The encoder to write data to. - public func encode(to encoder: Encoder) throws { - var container = encoder.singleValueContainer() - try container.encode(_elements) - } -} - -extension Uniqued: Decodable where Base: Decodable { - /// Creates a new uniqued collection by decoding from the given decoder. - /// - /// This initializer throws an error if reading from the decoder fails, or - /// if the decoded contents contain duplicate values. - /// - /// - Parameter decoder: The decoder to read data from. - public init(from decoder: Decoder) throws { - let container = try decoder.singleValueContainer() - let elements = try container.decode(Base.self) - - let (storage, end) = _HashTableStorage.create( - from: elements, - stoppingOnFirstDuplicateValue: true) - guard end == elements.endIndex else { - let offset = elements._offset(of: end) - let context = DecodingError.Context( - codingPath: container.codingPath, - debugDescription: "Decoded elements aren't unique (first duplicate at offset \(offset))") - throw DecodingError.dataCorrupted(context) - } - self.init( - _uniqueElements: elements, - storage: elements.count > _UnsafeHashTable.maximumUnhashedCount ? storage : nil) - } -} diff --git a/Sources/UniquedModule/Uniqued+CustomDebugStringConvertible.swift b/Sources/UniquedModule/Uniqued+CustomDebugStringConvertible.swift deleted file mode 100644 index e36a2cd4..00000000 --- a/Sources/UniquedModule/Uniqued+CustomDebugStringConvertible.swift +++ /dev/null @@ -1,38 +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 -// -//===----------------------------------------------------------------------===// - -extension Uniqued: CustomDebugStringConvertible { - public var debugDescription: String { - _debugDescription(typeName: _debugTypeName()) - } - - internal func _debugTypeName() -> String { - // Prefer the name "OrderedSet" when Base is a regular array. - Base.self == [Element].self - ? "OrderedSet<\(Element.self)>" - : "Uniqued<\(Base.self)>" - } - - internal func _debugDescription(typeName: String) -> String { - var result = "\(typeName)([" - var first = true - for item in self { - if first { - first = false - } else { - result += ", " - } - debugPrint(item, terminator: "", to: &result) - } - result += "])" - return result - } -} diff --git a/Sources/UniquedModule/Uniqued+CustomReflectable.swift b/Sources/UniquedModule/Uniqued+CustomReflectable.swift deleted file mode 100644 index c3614594..00000000 --- a/Sources/UniquedModule/Uniqued+CustomReflectable.swift +++ /dev/null @@ -1,16 +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 -// -//===----------------------------------------------------------------------===// - -extension Uniqued: CustomReflectable { - public var customMirror: Mirror { - Mirror(self, unlabeledChildren: _elements, displayStyle: .collection) - } -} diff --git a/Sources/UniquedModule/Uniqued+CustomStringConvertible.swift b/Sources/UniquedModule/Uniqued+CustomStringConvertible.swift deleted file mode 100644 index 53b4d265..00000000 --- a/Sources/UniquedModule/Uniqued+CustomStringConvertible.swift +++ /dev/null @@ -1,27 +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 -// -//===----------------------------------------------------------------------===// - -extension Uniqued: CustomStringConvertible { - public var description: String { - var result = "[" - var first = true - for item in self { - if first { - first = false - } else { - result += ", " - } - print(item, terminator: "", to: &result) - } - result += "]" - return result - } -} diff --git a/Sources/UniquedModule/Uniqued+Equatable.swift b/Sources/UniquedModule/Uniqued+Equatable.swift deleted file mode 100644 index 885c5580..00000000 --- a/Sources/UniquedModule/Uniqued+Equatable.swift +++ /dev/null @@ -1,16 +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 -// -//===----------------------------------------------------------------------===// - -extension Uniqued: Equatable where Element: Equatable { - public static func ==(left: Self, right: Self) -> Bool { - left.elementsEqual(right) - } -} diff --git a/Sources/UniquedModule/Uniqued+ExpressibleByArrayLiteral.swift b/Sources/UniquedModule/Uniqued+ExpressibleByArrayLiteral.swift deleted file mode 100644 index acdbef17..00000000 --- a/Sources/UniquedModule/Uniqued+ExpressibleByArrayLiteral.swift +++ /dev/null @@ -1,20 +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 -// -//===----------------------------------------------------------------------===// - -extension Uniqued: ExpressibleByArrayLiteral where Base: RangeReplaceableCollection -{ - // Note: we need the `RangeReplaceableCollection` conformance to be able to - // de-dupe contents & convert the input array into `Base`. - - public init(arrayLiteral elements: Element...) { - self.init(elements) - } -} diff --git a/Sources/UniquedModule/Uniqued+Hashable.swift b/Sources/UniquedModule/Uniqued+Hashable.swift deleted file mode 100644 index 1b44b9f4..00000000 --- a/Sources/UniquedModule/Uniqued+Hashable.swift +++ /dev/null @@ -1,19 +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 -// -//===----------------------------------------------------------------------===// - -extension Uniqued: Hashable where Element: Hashable { - public func hash(into hasher: inout Hasher) { - hasher.combine(count) // Discriminator - for item in _elements { - hasher.combine(item) - } - } -} diff --git a/Sources/UniquedModule/Uniqued+Initializers.swift b/Sources/UniquedModule/Uniqued+Initializers.swift deleted file mode 100644 index 3e64bf23..00000000 --- a/Sources/UniquedModule/Uniqued+Initializers.swift +++ /dev/null @@ -1,53 +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 -// -//===----------------------------------------------------------------------===// - -extension Uniqued { - public init(uncheckedUniqueElements elements: Base) { - guard elements.count > _UnsafeHashTable.maximumUnhashedCount else { - self.init(_uniqueElements: elements, storage: nil) - return - } - let storage = _HashTableStorage.create( - from: elements, - stoppingOnFirstDuplicateValue: false).storage - self.init(_uniqueElements: elements, storage: storage) - } - - public init(uniqueElements elements: Base) { - let (storage, index) = _HashTableStorage.create( - from: elements, - stoppingOnFirstDuplicateValue: true) - guard index == elements.endIndex else { - let offset = elements._offset(of: index) - preconditionFailure("Duplicate element at offset \(offset)") - } - self.init( - _uniqueElements: elements, - storage: elements.count > _UnsafeHashTable.maximumUnhashedCount ? storage : nil) - } -} - -extension Uniqued where Base: RangeReplaceableCollection { - public init(minimumCapacity: Int) { - self.init() - self.reserveCapacity(minimumCapacity) - } - - public init(uncheckedUniqueElements elements: S) - where S.Element == Element { - self.init(uncheckedUniqueElements: Base(elements)) - } - - public init(uniqueElements elements: S) - where S.Element == Element { - self.init(uniqueElements: Base(elements)) - } -} diff --git a/Sources/UniquedModule/Uniqued+Insertions.swift b/Sources/UniquedModule/Uniqued+Insertions.swift deleted file mode 100644 index 943ea944..00000000 --- a/Sources/UniquedModule/Uniqued+Insertions.swift +++ /dev/null @@ -1,214 +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 -// -//===----------------------------------------------------------------------===// - -extension Uniqued where Base: RangeReplaceableCollection { - @_spi(UnsafeInternals) - public mutating func _appendNew(_ item: Element) { - assert(!contains(item)) - _elements.append(item) - guard _elements.count <= _capacity else { - _regenerateHashTable() - return - } - guard _storage != nil else { return } - _ensureUnique() - _storage!.update { hashTable in - var it = hashTable.bucketIterator(for: item) - it.advanceToNextUnoccupiedBucket() - it.currentValue = _elements.count - 1 - } - } - - @_spi(UnsafeInternals) - public mutating func _appendNew(_ item: Element, in bucket: _Bucket) { - _elements.append(item) - - guard _elements.count < _capacity else { - _regenerateHashTable() - return - } - guard _storage != nil else { return } - _ensureUnique() - _storage!.update { hashTable in - hashTable[bucket] = _elements.count - 1 - } - } - - @_spi(UnsafeInternals) - @discardableResult - public mutating func _append(_ item: Element) -> (inserted: Bool, index: Base.Index) { - let (index, bucket) = _find(item) - if let index = index { return (false, index) } - _appendNew(item, in: bucket) - return (true, _elements.index(before: _elements.endIndex)) - } - - @discardableResult - public mutating func append(_ item: Element) -> (inserted: Bool, index: Base.Index) { - let result = _append(item) - _checkInvariants() - return result - } - - public mutating func append( - contentsOf elements: S - ) where S.Element == Element { - for item in elements { - _append(item) - } - _checkInvariants() - } -} - -extension Uniqued where Base: RangeReplaceableCollection { - internal mutating func _prependNew(_ item: Element, in bucket: _Bucket) { - _elements.insert(item, at: _elements.startIndex) - - guard _elements.count < _capacity else { - _regenerateHashTable() - return - } - guard _storage != nil else { return } - _ensureUnique() - _storage!.update { hashTable in - hashTable.bias &+= 1 - hashTable[bucket] = 0 - } - } - - @discardableResult - public mutating func prepend(_ item: Element) -> (inserted: Bool, index: Base.Index) { - let (index, bucket) = _find(item) - if let index = index { return (false, index) } - - _prependNew(item, in: bucket) - return (true, _elements.startIndex) - } - - public mutating func prepend( - contentsOf elements: S - ) where S.Element == Element { - var new = Self() - for item in elements { - guard !self.contains(item) else { continue } - new._append(item) - } - let inserted = new._elements.count - guard inserted > 0 else { return } - _elements.insert(contentsOf: new._elements, at: _elements.startIndex) - defer { _checkInvariants() } - if _elements.count > _capacity { - _regenerateHashTable() - return - } - if _storage == nil { - return - } - _ensureUnique() - _storage!.update { hashTable in - hashTable.bias += inserted - var i = 0 - while i != inserted { - var it = hashTable.bucketIterator(for: _elements[_elements._index(at: i)]) - it.advanceToNextUnoccupiedBucket() - it.currentValue = i - i += 1 - } - } - } -} - -extension Uniqued where Base: RangeReplaceableCollection { - internal mutating func _insertNew( - _ item: Element, - at index: Index, - bucket: _Bucket - ) -> Int { - let offset = _elements._offset(of: index) - guard _elements.count < _capacity else { - _elements.insert(item, at: index) - _regenerateHashTable() - return offset - } - guard _storage != nil else { - _elements.insert(item, at: index) - return offset - } - - _storage!.update { hashTable in - hashTable.adjustContents(preparingForInsertionOfElementAtOffset: offset, in: _elements) - hashTable[bucket] = offset - } - _elements.insert(item, at: index) - _checkInvariants() - return offset - } - - public mutating func insert( - _ item: Element, at index: Index - ) -> (inserted: Bool, index: Index) { - let (existing, bucket) = _find(item) - if let existing = existing { return (false, existing) } - - let offset = _insertNew(item, at: index, bucket: bucket) - return (true, _elements._index(at: offset)) - } -} - -extension Uniqued where Base: MutableCollection { - /// 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. - /// - /// This method does not invalidate any indices in `self`. - /// - /// - Complexity: O(1) if the collection instance has no outstanding copies. - /// Otherwise O(n) where _n_ is `self.count`. - /// - /// - Parameter index: The index of the element to be replaced. - /// - Parameter item: The new value that should replace the original element. - /// `item` must compare equal to the original value. - /// - Returns: The original element that was replaced. - @discardableResult - public mutating func update(at index: Index, with item: Element) -> Element { - let old = _elements[index] - precondition(item == old, "The replacement item must compare equal to the original") - _elements[index] = item - return old - } -} - -extension Uniqued where Base: RangeReplaceableCollection & MutableCollection { - /// Inserts the given element into the set unconditionally, either appending - /// it to the set, or replacing an existing value if it's already present. - /// - /// This is useful when equal elements can be distinguished by identity - /// comparison or some other means. - /// - /// This method does not invalidate indices when the return value is non-`nil`. - /// Otherwise indices in `self` may get invalidated, depending on the - /// behavior of the `append` method of the underlying `Base` collection. - /// - /// - Complexity: O(1) on average, amortized over many calls on the same collection. - /// - /// - Parameter item: The value to append or replace. - /// - Returns: The original element that was replaced by this operation, or `nil` if the value was appended to the end of the collection. - public mutating func updateOrAppend(_ item: Element) -> Element? { - let (inserted, index) = _append(item) - if inserted { return nil } - let old = _elements[index] - _elements[index] = item - _checkInvariants() - return old - } -} diff --git a/Sources/UniquedModule/Uniqued+Invariants.swift b/Sources/UniquedModule/Uniqued+Invariants.swift deleted file mode 100644 index 5eb0888b..00000000 --- a/Sources/UniquedModule/Uniqued+Invariants.swift +++ /dev/null @@ -1,54 +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 -// -//===----------------------------------------------------------------------===// - -extension Uniqued { - #if COLLECTIONS_INTERNAL_CHECKS - @_spi(Testing) - @inline(never) @_effects(releasenone) - public func _checkInvariants() { - if _storage == nil { - precondition(_elements.count <= _UnsafeHashTable.maximumUnhashedCount, - "Oversized set without a hash table") - precondition(Set(_elements).count == _elements.count, - "Duplicate items in set") - return - } - // Check that each element in _elements can be found in the hash table. - for index in _elements.indices { - let item = _elements[index] - let (found, _, offset) = _find(item) - precondition(found, "Element '\(item)' not found in hash table") - precondition( - _index(at: offset) == index, - "Offset of element '\(item)' in hash table differs from its position") - } - // Check that the hash table has exactly as many entries as there are elements. - _storage!.read { hashTable in - var it = hashTable.bucketIterator(startingAt: _Bucket(offset: 0)) - var c = 0 - repeat { - it.advance() - if it.isOccupied { c += 1 } - } while it.currentBucket.offset != 0 - precondition( - c == _elements.count, - """ - Number of entries in hash table (\(c)) differs - from number of elements (\(_elements.count)) - """) - } - } - #else - @_spi(Testing) - @inline(__always) @inlinable - public func _checkInvariants() {} - #endif // COLLECTIONS_INTERNAL_CHECKS -} diff --git a/Sources/UniquedModule/Uniqued+Partial MutableCollection.swift b/Sources/UniquedModule/Uniqued+Partial MutableCollection.swift deleted file mode 100644 index 47a13f6e..00000000 --- a/Sources/UniquedModule/Uniqued+Partial MutableCollection.swift +++ /dev/null @@ -1,210 +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 -// -//===----------------------------------------------------------------------===// - -// The parts of MutableCollection that Uniqued is able to implement. - -extension Uniqued where Base: MutableCollection { - public mutating func swapAt(_ i: Index, _ j: Index) { - guard i != j else { return } - _elements.swapAt(i, j) - guard _storage != nil else { return } - _ensureUnique() - _storage!.update { hashTable in - let iOffset = _elements._offset(of: i) - let jOffset = _elements._offset(of: j) - hashTable.swapBucketValues(for: _elements[i], withCurrentValue: jOffset, - and: _elements[j], withCurrentValue: iOffset) - } - _checkInvariants() - } - - public mutating func partition( - by belongsInSecondPartition: (Element) throws -> Bool - ) rethrows -> Index { - try _partition(by: belongsInSecondPartition, callback: { a, b in }) - } -} - -extension Uniqued where Base: MutableCollection { - public mutating func _partition( - by belongsInSecondPartition: (Element) throws -> Bool, - callback: (Int, Int) -> Void - ) rethrows -> Index { - guard _storage != nil else { - return try _elements.partition(by: belongsInSecondPartition) - } - _ensureUnique() - let result: Index = try _storage!.update { hashTable in - let maybeOffset: Int? = try _elements.withContiguousMutableStorageIfAvailable { buffer in - let pivot = try buffer._partition( - with: hashTable, - by: belongsInSecondPartition, - callback: callback) - return pivot - buffer.startIndex - } - if let offset = maybeOffset { - return _elements.index(startIndex, offsetBy: offset) - } - return try _elements._partition( - with: hashTable, - by: belongsInSecondPartition, - callback: callback) - } - _checkInvariants() - return result - } -} - -extension MutableCollection where Self: RandomAccessCollection, Element: Hashable { - internal mutating func _partition( - with hashTable: _UnsafeHashTable, - by belongsInSecondPartition: (Element) throws -> Bool, - callback: (Int, Int) -> Void - ) rethrows -> Index { - var low = startIndex - var high = endIndex - - while true { - // Invariants at this point: - // - low <= high - // - all elements in `startIndex ..< low` belong in the first partition - // - all elements in `high ..< endIndex` belong in the second partition - - // Find next element from `lo` that may not be in the right place. - while true { - if low == high { return low } - if try belongsInSecondPartition(self[low]) { break } - formIndex(after: &low) - } - - // Find next element down from `hi` that we can swap `lo` with. - while true { - formIndex(before: &high) - if low == high { return low } - if try !belongsInSecondPartition(self[high]) { break } - } - - // Swap the two elements as well as their associated hash table buckets. - swapAt(low, high) - hashTable.swapBucketValues(for: self[low], withCurrentValue: _offset(of: high), - and: self[high], withCurrentValue: _offset(of: low)) - callback(_offset(of: low), _offset(of: high)) - - formIndex(after: &low) - } - } -} - -extension _UnsafeHashTable { - func swapBucketValues( - for left: Element, withCurrentValue leftValue: Int, - and right: Element, withCurrentValue rightValue: Int - ) { - var it = bucketIterator(for: left) - it.advance(until: leftValue) - assert(it.isOccupied) - it.currentValue = rightValue - - it = bucketIterator(for: right) - it.advance(until: rightValue) - assert(it.isOccupied) - // Note: this second update may mistake the bucket for `right` with the - // bucket for `left` whose value we just updated. The second update will - // restore the original hash table contents in this case. This is okay! - // When this happens, the lookup chains for both elements include each - // other, so leaving the hash table unchanged still leaves us with a - // working hash table. - it.currentValue = leftValue - } -} - -extension Uniqued where Base: MutableCollection { - public mutating func sort( - by areInIncreasingOrder: (Element, Element) throws -> Bool - ) rethrows { - defer { - // Note: This assumes that `sort(by:)` won't leave duplicate/missing - // elements in the table when the closure throws. This matches the - // stdlib's behavior in Swift 5.3, and it seems like a reasonable - // long-term assumption. - _regenerateExistingHashTable() - _checkInvariants() - } - try _elements.sort(by: areInIncreasingOrder) - } -} - -extension Uniqued where Base: MutableCollection, Element: Comparable { - public mutating func sort() { - sort(by: <) - } -} - -extension Uniqued where Base: MutableCollection { - public mutating func shuffle() { - var generator = SystemRandomNumberGenerator() - shuffle(using: &generator) - } - - public mutating func shuffle( - using generator: inout T - ) { - _elements.shuffle(using: &generator) - _regenerateHashTable() - _checkInvariants() - } -} - -extension Uniqued { - @_spi(UnsafeInternals) - public mutating func _partition( - values: UnsafeMutableBufferPointer, - by belongsInSecondPartition: ((key: Key, value: Value)) throws -> Bool - ) rethrows -> Int - where Base == ContiguousArray { - let storage = _uniqueStorage() - return try _elements.withUnsafeMutableBufferPointer { keys in - assert(keys.count == values.count) - var low = keys.startIndex - var high = keys.endIndex - - while true { - // Invariants at this point: - // - low <= high - // - all elements in `startIndex ..< low` belong in the first partition - // - all elements in `high ..< endIndex` belong in the second partition - - // Find next element from `lo` that may not be in the right place. - while true { - if low == high { return low } - if try belongsInSecondPartition((keys[low], values[low])) { break } - low += 1 - } - - // Find next element down from `hi` that we can swap `lo` with. - while true { - high -= 1 - if low == high { return low } - if try !belongsInSecondPartition((keys[high], values[high])) { break } - } - - // Swap the two elements as well as their associated hash table buckets. - keys.swapAt(low, high) - values.swapAt(low, high) - storage?.update { hashTable in - hashTable.swapBucketValues(for: keys[low], withCurrentValue: high, - and: keys[high], withCurrentValue: low) - } - low += 1 - } - } - } -} diff --git a/Sources/UniquedModule/Uniqued+Partial RangeReplaceableCollection.swift b/Sources/UniquedModule/Uniqued+Partial RangeReplaceableCollection.swift deleted file mode 100644 index 171d1600..00000000 --- a/Sources/UniquedModule/Uniqued+Partial RangeReplaceableCollection.swift +++ /dev/null @@ -1,115 +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 -// -//===----------------------------------------------------------------------===// - -// The parts of RangeReplaceableCollection that Uniqued is able to implement. - -extension Uniqued where Base: RangeReplaceableCollection { - public mutating func reserveCapacity(_ minimumCapacity: Int) { - precondition(minimumCapacity >= 0, "Minimum capacity cannot be negative") - _elements.reserveCapacity(minimumCapacity) - let currentScale = _scale - let newScale = _UnsafeHashTable.scale(forCapacity: minimumCapacity) - let minScale = _UnsafeHashTable.scale(forCapacity: self.count) - if currentScale < newScale { - // Grow the table. - _regenerateHashTable(scale: newScale, reservedScale: newScale) - } else if newScale < currentScale, minScale < currentScale { - // Shrink the table. - _regenerateHashTable(scale: minScale, reservedScale: newScale) - } - if _reservedScale != newScale { - // Remember reserved scale. - _ensureUnique() - _storage!.header.reservedScale = newScale - } - _checkInvariants() - } - - public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { - _elements.removeAll(keepingCapacity: keepCapacity) - guard keepCapacity else { - _storage = nil - return - } - _ensureUnique() - _storage!.update { hashTable in - hashTable.clear() - } - } - - public mutating func remove(at index: Index) -> Self.Element { - _elements._failEarlyRangeCheck(index, bounds: startIndex ..< endIndex) - let bucket = _bucket(for: index) - return _removeExistingMember(at: index, bucket: bucket) - } - - public mutating func removeSubrange(_ bounds: Range) { - _elements._failEarlyRangeCheck(bounds, bounds: _elements.startIndex ..< _elements.endIndex) - guard _storage != nil else { - _elements.removeSubrange(bounds) - _checkInvariants() - return - } - let startOffset = _elements._offset(of: bounds.lowerBound) - let endOffset = _elements._offset(of: bounds.upperBound) - let c = endOffset - startOffset - guard c > 0 else { return } - let remainingCount = _elements.count - c - if remainingCount <= count / 2 || remainingCount < _minimumCapacity { - // Just generate a new table from scratch. - _elements.removeSubrange(bounds) - _regenerateHashTable() - _checkInvariants() - return - } - - _ensureUnique() - _storage!.update { hashTable in - // Delete the hash table entries for all members we're removing. - for item in _elements[bounds] { - let (offset, bucket) = hashTable._find(item, in: _elements) - precondition(offset != nil, "Corrupt hash table") - hashTable.delete( - bucket: bucket, - hashValueGenerator: { offset, seed in - let index = _elements._index(at: offset) - return _elements[index]._rawHashValue(seed: seed) - }) - } - hashTable.adjustContents(preparingForRemovalOf: bounds, in: _elements) - } - _elements.removeSubrange(bounds) - _checkInvariants() - } - - public mutating func removeLast() -> Element { - precondition(!isEmpty, "Cannot remove last element of an empty collection") - return remove(at: self._index(at: count - 1)) - } - - public mutating func removeLast(_ n: Int) { - precondition(n >= 0, "Can't remove a negative number of elements") - precondition(n <= count, "Can't remove more elements than there are in the collection") - removeSubrange(self._index(at: count - n) ..< self._index(at: count)) - } - - @discardableResult - public mutating func removeFirst() -> Element { - precondition(!isEmpty, "Cannot remove first element of an empty collection") - return remove(at: startIndex) - } - - public mutating func removeFirst(_ n: Int) { - precondition(n >= 0, "Can't remove a negative number of elements") - precondition(n <= count, "Can't remove more elements than there are in the collection") - removeSubrange(self._index(at: 0) ..< self._index(at: n)) - } -} diff --git a/Sources/UniquedModule/Uniqued+Partial SetAlgebra.swift b/Sources/UniquedModule/Uniqued+Partial SetAlgebra.swift deleted file mode 100644 index 6510a282..00000000 --- a/Sources/UniquedModule/Uniqued+Partial SetAlgebra.swift +++ /dev/null @@ -1,514 +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 -// -//===----------------------------------------------------------------------===// - -// `Uniqued` 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`). -// -// `Uniqued` 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 Uniqued where Base: RangeReplaceableCollection { - public init() { - _storage = nil - _elements = Base() - } - - public init(_ elements: S) where S.Element == Element { - if S.self == Self.self { - self = elements as! Self - return - } - if S.self == Set.self { - // Fast path for when we know elements are all unique - self.init(uncheckedUniqueElements: Base(elements)) - return - } - - self.init() - append(contentsOf: elements) - } - - // Specializations - - public init(_ elements: Self) { - self = elements - } - - public init(_ elements: SubSequence) { - self.init(uncheckedUniqueElements: Base(elements._slice)) - } - - public init(_ elements: Set) { - self.init(uncheckedUniqueElements: Base(elements)) - } - - public init(_ elements: Base) { - let (storage, firstDupe) = _HashTableStorage.create( - from: elements, - stoppingOnFirstDuplicateValue: true) - if firstDupe == elements.endIndex { - // Fast path: `elements` consists of unique values. - self.init(_uniqueElements: elements, storage: storage) - return - } - - // Otherwise keep the elements we've processed and add the rest one by one. - var contents = elements - contents.removeLast(elements.count - elements._offset(of: firstDupe)) - self.init(_uniqueElements: contents, storage: storage) - self.append(contentsOf: elements[firstDupe...]) - } - - public init(_ elements: Dictionary.Keys) { - self._elements = Base(elements) - _regenerateHashTable() - _checkInvariants() - } -} - -extension Uniqued { - public func contains(_ element: Element) -> Bool { - guard let storage = _storage else { - return _elements.contains(element) - } - return storage.read { hashTable in - hashTable._find(element, in: _elements).offset != nil - } - } -} - -extension Uniqued where Base: RangeReplaceableCollection { - @discardableResult - public mutating func remove(_ member: Element) -> Element? { - let (idx, bucket) = _find(member) - guard let index = idx else { return nil } - return _removeExistingMember(at: index, bucket: bucket) - } -} - -extension Uniqued where Base: RangeReplaceableCollection { - public mutating func formUnion(_ other: __owned Self) { - for item in other { - append(item) - } - } - - public __consuming func union(_ other: __owned Self) -> Self { - var result = self - result.formUnion(other) - return result - } - - // Generalizations - - @inline(__always) - public mutating func formUnion(_ other: __owned UnorderedView) { - formUnion(other._base) - } - - @inline(__always) - public __consuming func union(_ other: __owned UnorderedView) -> Self { - union(other._base) - } - - public mutating func formUnion( - _ other: __owned S - ) where S.Element == Element { - for item in other { - append(item) - } - } - - public __consuming func union( - _ other: __owned S - ) -> Self where S.Element == Element { - var result = self - result.formUnion(other) - return result - } -} - -extension Uniqued where Base: RangeReplaceableCollection { - public __consuming func intersection(_ other: Self) -> Self { - var result = Self() - for item in self { - if other.contains(item) { - result._appendNew(item) - } - } - return result - } - - public mutating func formIntersection(_ other: Self) { - self = self.intersection(other) - } - - // Generalizations - - @inline(__always) - public __consuming func intersection(_ other: UnorderedView) -> Self { - intersection(other._base) - } - - @inline(__always) - public mutating func formIntersection(_ other: UnorderedView) { - formIntersection(other._base) - } - - public __consuming func intersection( - _ other: S - ) -> Self where S.Element == Element { - _UnsafeBitset.withTemporaryBitset(capacity: self.count) { bitset in - for item in other { - if let index = self.firstIndex(of: item) { - bitset.insert(_elements._offset(of: index)) - } - } - return self._extractSubset(using: bitset) - } - } - - public mutating func formIntersection( - _ other: S - ) where S.Element == Element { - self = self.intersection(other) - } -} - -extension Uniqued where Base: RangeReplaceableCollection { - public __consuming func symmetricDifference(_ other: __owned Self) -> Self { - _UnsafeBitset.withTemporaryBitset(capacity: self.count) { bitset1 in - _UnsafeBitset.withTemporaryBitset(capacity: other.count) { bitset2 in - bitset1.insertAll(upTo: self.count) - for item in other { - if let offset = self._offset(of: item) { - bitset1.remove(offset) - } - } - bitset2.insertAll(upTo: other.count) - for item in self { - if let offset = other._offset(of: item) { - bitset2.remove(offset) - } - } - var result = self._extractSubset(using: bitset1, - extraCapacity: bitset2.count) - for offset in bitset2 { - let index = other._elements._index(at: offset) - result._appendNew(other._elements[index]) - } - return result - } - } - } - - public mutating func formSymmetricDifference(_ other: __owned Self) { - self = self.symmetricDifference(other) - } - - // Generalizations - - @inline(__always) - public __consuming func symmetricDifference(_ other: __owned UnorderedView) -> Self { - symmetricDifference(other._base) - } - - @inline(__always) - public mutating func formSymmetricDifference(_ other: __owned UnorderedView) { - formSymmetricDifference(other._base) - } - - public __consuming func symmetricDifference( - _ other: __owned S - ) -> Self where S.Element == Element { - _UnsafeBitset.withTemporaryBitset(capacity: self.count) { bitset in - var new = Self() - bitset.insertAll(upTo: self.count) - for item in other { - if let offset = self._offset(of: item) { - bitset.remove(offset) - } else { - new.append(item) - } - } - var result = Self(minimumCapacity: bitset.count + new.count) - for offset in bitset { - let index = self._elements._index(at: offset) - result._appendNew(self._elements[index]) - } - for item in new._elements { - result._appendNew(item) - } - return result - } - } - - public mutating func formSymmetricDifference( - _ other: __owned S - ) where S.Element == Element { - self = self.symmetricDifference(other) - } -} - -extension Uniqued where Base: RangeReplaceableCollection { - @inline(__always) - public __consuming func subtracting(_ other: Self) -> Self { - _subtracting(other) - } - - @inline(__always) - public mutating func subtract(_ other: Self) { - self = subtracting(other) - } - - // Generalizations - - @inline(__always) - public __consuming func subtracting(_ other: UnorderedView) -> Self { - subtracting(other._base) - } - - @inline(__always) - public mutating func subtract(_ other: UnorderedView) { - subtract(other._base) - } - - @inline(__always) - public __consuming func subtracting( - _ other: S - ) -> Self where S.Element == Element { - _subtracting(other) - } - - @inline(__always) - public mutating func subtract( - _ other: S - ) where S.Element == Element { - self = _subtracting(other) - } - - __consuming func _subtracting( - _ other: S - ) -> Self where S.Element == Element { - guard count > 0 else { return Self() } - return _UnsafeBitset.withTemporaryBitset(capacity: count) { difference in - difference.insertAll(upTo: count) - for item in other { - if let offset = self._offset(of: item) { - if difference.remove(offset), difference.count == 0 { - return Self() - } - } - } - assert(difference.count > 0) - return _extractSubset(using: difference) - } - } -} - -extension Uniqued { - 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 - - @inline(__always) - public func isSubset(of other: UnorderedView) -> Bool { - isSubset(of: other._base) - } - - 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 - } - - 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 offset = _offset(of: item) { - if seen.insert(offset), seen.count == self.count { - // We've seen enough. - return true - } - } - } - return false - } - } -} - -extension Uniqued { - public func isSuperset(of other: Self) -> Bool { - other.isSubset(of: self) - } - - // Generalizations - - public func isSuperset(of other: UnorderedView) -> Bool { - isSuperset(of: other._base) - } - - public func isSuperset(of other: Set) -> Bool { - guard self.count >= other.count else { return false } - return _isSuperset(of: other) - } - - public func isSuperset( - of other: S - ) -> Bool where S.Element == Element { - _isSuperset(of: other) - } - - 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 Uniqued { - public func isStrictSubset(of other: Self) -> Bool { - self.count < other.count && self.isSubset(of: other) - } - - // Generalizations - - @inline(__always) - public func isStrictSubset(of other: UnorderedView) -> Bool { - isStrictSubset(of: other._base) - } - - public func isStrictSubset(of other: Set) -> Bool { - self.count < other.count && self.isSubset(of: other) - } - - 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 offset = _offset(of: item) { - if seen.insert(offset), 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 Uniqued { - public func isStrictSuperset(of other: Self) -> Bool { - self.count > other.count && other.isSubset(of: self) - } - - // Generalizations - - @inline(__always) - public func isStrictSuperset(of other: UnorderedView) -> Bool { - isStrictSuperset(of: other._base) - } - - public func isStrictSuperset(of other: Set) -> Bool { - self.count > other.count && other.isSubset(of: self) - } - - 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 offset = _offset(of: item) else { - return false - } - if seen.insert(offset), seen.count == self.count { - // We've seen enough. - return false - } - } - return seen.count < self.count - } - } -} - -extension Uniqued { - 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 - - @inline(__always) - public func isDisjoint(with other: UnorderedView) -> Bool { - isDisjoint(with: other._base) - } - - 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 - } - - 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/UniquedModule/Uniqued+RandomAccessCollection.swift b/Sources/UniquedModule/Uniqued+RandomAccessCollection.swift deleted file mode 100644 index 21069700..00000000 --- a/Sources/UniquedModule/Uniqued+RandomAccessCollection.swift +++ /dev/null @@ -1,77 +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 -// -//===----------------------------------------------------------------------===// - -extension Uniqued: RandomAccessCollection { - public typealias Index = Base.Index - public typealias Indices = Base.Indices - // For SubSequence, see Uniqued+SubSequence.swift. - - public var startIndex: Index { _elements.startIndex } - public var endIndex: Index { _elements.endIndex } - public var indices: Indices { _elements.indices } - - public func index(after i: Index) -> Index { _elements.index(after: i) } - public func index(before i: Index) -> Index { _elements.index(before: i) } - public func formIndex(after i: inout Index) { _elements.formIndex(after: &i) } - public func formIndex(before i: inout Index) { _elements.formIndex(before: &i) } - - public func index(_ i: Index, offsetBy distance: Int) -> Index { - _elements.index(i, offsetBy: distance) - } - - public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { - _elements.index(i, offsetBy: distance, limitedBy: limit) - } - - public func distance(from start: Index, to end: Index) -> Int { - _elements.distance(from: start, to: end) - } - - public subscript(position: Index) -> Element { - _elements[position] - } - - public subscript(bounds: Range) -> SubSequence { - _failEarlyRangeCheck(bounds, bounds: startIndex ..< endIndex) - return SubSequence(base: self, bounds: bounds) - } - - public var isEmpty: Bool { _elements.isEmpty } - public var count: Int { _elements.count } - - public func _customIndexOfEquatableElement(_ element: Element) -> Index?? { - guard let storage = _storage else { - return _elements._customIndexOfEquatableElement(element) - } - return storage.read { hashTable in - let (o, _) = hashTable._find(element, in: _elements) - guard let offset = o else { return .some(nil) } - return _elements._index(at: offset) - } - } - - public func _customLastIndexOfEquatableElement(_ element: Element) -> Index?? { - // Uniqued holds unique elements. - _customIndexOfEquatableElement(element) - } - - public func _failEarlyRangeCheck(_ index: Index, bounds: Range) { - _elements._failEarlyRangeCheck(index, bounds: bounds) - } - - public func _failEarlyRangeCheck(_ index: Index, bounds: ClosedRange) { - _elements._failEarlyRangeCheck(index, bounds: bounds) - } - - public func _failEarlyRangeCheck(_ range: Range, bounds: Range) { - _elements._failEarlyRangeCheck(range, bounds: bounds) - } -} diff --git a/Sources/UniquedModule/Uniqued+Sequence.swift b/Sources/UniquedModule/Uniqued+Sequence.swift deleted file mode 100644 index 4df06bcf..00000000 --- a/Sources/UniquedModule/Uniqued+Sequence.swift +++ /dev/null @@ -1,39 +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 -// -//===----------------------------------------------------------------------===// - -extension Uniqued: Sequence { - public typealias Element = Base.Element - public typealias Iterator = Base.Iterator - - public func makeIterator() -> Iterator { - _elements.makeIterator() - } - - public func _customContainsEquatableElement(_ element: Element) -> Bool? { - _find(element).index != nil - } - - public __consuming func _copyToContiguousArray() -> ContiguousArray { - _elements._copyToContiguousArray() - } - - public __consuming func _copyContents( - initializing ptr: UnsafeMutableBufferPointer - ) -> (Iterator, UnsafeMutableBufferPointer.Index) { - _elements._copyContents(initializing: ptr) - } - - public func withContiguousStorageIfAvailable( - _ body: (UnsafeBufferPointer) throws -> R - ) rethrows -> R? { - try _elements.withContiguousStorageIfAvailable(body) - } -} diff --git a/Sources/UniquedModule/Uniqued+SubSequence.swift b/Sources/UniquedModule/Uniqued+SubSequence.swift deleted file mode 100644 index 61a20471..00000000 --- a/Sources/UniquedModule/Uniqued+SubSequence.swift +++ /dev/null @@ -1,124 +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 -// -//===----------------------------------------------------------------------===// - -extension Uniqued { - public struct SubSequence { - internal var _startIndex: Base.Index - internal var _endIndex: Base.Index - internal var _base: Uniqued - - public init(base: Uniqued, bounds: Range) { - self._base = base - self._startIndex = bounds.lowerBound - self._endIndex = bounds.upperBound - } - } -} - -extension Uniqued.SubSequence { - internal var _slice: Base.SubSequence { - _base._elements[_startIndex ..< _endIndex] - } - - internal func _index(of element: Element) -> Index? { - guard let index = _base._find(element).index else { return nil } - guard _startIndex <= index && index < _endIndex else { return nil } - return index - } -} - -extension Uniqued.SubSequence: Sequence { - public typealias Element = Base.Element - public typealias Iterator = Base.SubSequence.Iterator - - public func makeIterator() -> Iterator { - _slice.makeIterator() - } - - public func _customContainsEquatableElement(_ element: Element) -> Bool? { - _index(of: element) != nil - } - - public __consuming func _copyToContiguousArray() -> ContiguousArray { - _slice._copyToContiguousArray() - } - - public __consuming func _copyContents( - initializing ptr: UnsafeMutableBufferPointer - ) -> (Iterator, UnsafeMutableBufferPointer.Index) { - _slice._copyContents(initializing: ptr) - } - - public func withContiguousStorageIfAvailable( - _ body: (UnsafeBufferPointer) throws -> R - ) rethrows -> R? { - try _slice.withContiguousStorageIfAvailable(body) - } -} - -extension Uniqued.SubSequence: RandomAccessCollection { - public typealias Index = Base.Index - public typealias Indices = Base.SubSequence.Indices - public typealias SubSequence = Self - - public var startIndex: Index { _startIndex } - public var endIndex: Index { _endIndex } - public var indices: Indices { _slice.indices } - - public func index(after i: Index) -> Index { _slice.index(after: i) } - public func index(before i: Index) -> Index { _slice.index(before: i) } - public func formIndex(after i: inout Index) { _slice.formIndex(after: &i) } - public func formIndex(before i: inout Index) { _slice.formIndex(before: &i) } - - public func index(_ i: Index, offsetBy distance: Int) -> Index { - _slice.index(i, offsetBy: distance) - } - - public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { - _slice.index(i, offsetBy: distance, limitedBy: limit) - } - - public func distance(from start: Index, to end: Index) -> Int { - _slice.distance(from: start, to: end) - } - - public subscript(position: Index) -> Element { - _slice[position] - } - - public subscript(bounds: Range) -> SubSequence { - _failEarlyRangeCheck(bounds, bounds: startIndex ..< endIndex) - return SubSequence(base: _base, bounds: bounds) - } - - public var isEmpty: Bool { _startIndex == _endIndex } - public var count: Int { distance(from: _startIndex, to: _endIndex) } - - public func _customIndexOfEquatableElement(_ element: Element) -> Index?? { - .some(_index(of: element)) - } - - public func _customLastIndexOfEquatableElement(_ element: Element) -> Index?? { - .some(_index(of: element)) - } - - public func _failEarlyRangeCheck(_ index: Index, bounds: Range) { - _slice._failEarlyRangeCheck(index, bounds: bounds) - } - - public func _failEarlyRangeCheck(_ index: Index, bounds: ClosedRange) { - _slice._failEarlyRangeCheck(index, bounds: bounds) - } - - public func _failEarlyRangeCheck(_ range: Range, bounds: Range) { - _slice._failEarlyRangeCheck(range, bounds: bounds) - } -} diff --git a/Sources/UniquedModule/Uniqued+Testing.swift b/Sources/UniquedModule/Uniqued+Testing.swift deleted file mode 100644 index 6094a0a9..00000000 --- a/Sources/UniquedModule/Uniqued+Testing.swift +++ /dev/null @@ -1,141 +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 -// -//===----------------------------------------------------------------------===// - -extension _Bucket: CustomStringConvertible { - public var description: String { "Bucket(@\(offset))"} -} - -extension _UnsafeHashTable: CustomStringConvertible { - public var description: String { - var d = """ - _UnsafeHashTable\(_header.pointee._description) - load factor: \(debugLoadFactor()) - """ - if bucketCount < 128 { - d += "\n " - d += debugContents() - .lazy - .map { $0 == nil ? "_" : "\($0!)" } - .joined(separator: " ") - } - return d - } - - internal func debugOccupiedCount() -> Int { - var count = 0 - var it = bucketIterator(startingAt: _Bucket(offset: 0)) - repeat { - if it.isOccupied { - count += 1 - } - it.advance() - } while it.currentBucket.offset != 0 - return count - } - - internal func debugLoadFactor() -> Double { - return Double(debugOccupiedCount()) / Double(bucketCount) - } - - internal func debugContents() -> [Int?] { - var result: [Int?] = [] - result.reserveCapacity(bucketCount) - var it = bucketIterator(startingAt: _Bucket(offset: 0)) - repeat { - result.append(it.currentValue) - it.advance() - } while it.currentBucket.offset != 0 - return result - } -} - -extension _UnsafeHashTable.BucketIterator: CustomStringConvertible { - var description: String { - func pad(_ s: String, to length: Int, by padding: Character = " ") -> String { - let c = s.count - guard c < length else { return s } - return String(repeating: padding, count: length - c) + s - } - let offset = pad(String(_currentBucket.offset), to: 4) - let value: String - if let v = currentValue { - value = pad(String(v), to: 4) - } else { - value = " nil" - } - let remainingBits = pad(String(_nextBits, radix: 2), to: _remainingBitCount, by: "0") - return "BucketIterator(scale: \(_scale), bucket: \(offset), value: \(value), bits: \(remainingBits) (\(_remainingBitCount) bits))" - } -} - -extension Uniqued { - @_spi(Testing) public var _hasHashTable: Bool { _storage != nil } - - @_spi(Testing) public var _hashTableIdentity: ObjectIdentifier? { - guard let storage = _storage else { return nil } - return ObjectIdentifier(storage) - } - - @_spi(Testing) public var _hashTableContents: [Int?] { - _storage!.read { hashTable in - hashTable.debugContents() - } - } - - @_spi(Testing) mutating public func _regenerateHashTable(bias: Int) { - _ensureUnique() - let new = _storage!.copy() - _storage!.read { source in - new.update { target in - target.bias = bias - var it = source.bucketIterator(startingAt: _Bucket(offset: 0)) - repeat { - target[it.currentBucket] = it.currentValue - it.advance() - } while it.currentBucket.offset != 0 - } - } - _storage = new - } -} - -extension Uniqued { - @_spi(Testing) public init( - _scale scale: Int, - bias: Int, - contents: Base - ) { - precondition(scale >= _UnsafeHashTable.scale(forCapacity: contents.count)) - precondition(scale <= _UnsafeHashTable.maximumScale) - precondition(bias >= 0 && _UnsafeHashTable.biasRange(scale: scale).contains(bias)) - precondition(scale >= _UnsafeHashTable.minimumScale || bias == 0) - let storage = _HashTableStorage.create(scale: Swift.max(scale, _UnsafeHashTable.minimumScale)) - storage.header.bias = bias - let (success, index) = storage.update { hashTable in - hashTable.fill(from: contents, stoppingOnFirstDuplicateValue: true) - } - precondition(success, "Duplicate element at index \(index)") - _storage = scale < _UnsafeHashTable.minimumScale ? nil : storage - _elements = contents - precondition(self._scale == scale) - precondition(self._bias == bias) - } -} - -extension Uniqued where Base: RangeReplaceableCollection { - @_spi(Testing) public init( - _scale scale: Int, - bias: Int, - contents: C - ) where C.Element == Element { - self.init(_scale: scale, bias: bias, contents: Base(contents)) - } -} diff --git a/Sources/UniquedModule/Uniqued+UnorderedView.swift b/Sources/UniquedModule/Uniqued+UnorderedView.swift deleted file mode 100644 index 1fd498d6..00000000 --- a/Sources/UniquedModule/Uniqued+UnorderedView.swift +++ /dev/null @@ -1,368 +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 -// -//===----------------------------------------------------------------------===// - -extension Uniqued { - public struct UnorderedView { - public typealias Element = Base.Element - - internal var _base: Uniqued - - internal init(_base: Uniqued) { - self._base = _base - } - } - - @inline(__always) - public init(_ view: UnorderedView) { - self = view._base - } - - public var unordered: UnorderedView { - _read { - yield UnorderedView(_base: self) - } - } -} - -extension Uniqued where Base: RangeReplaceableCollection { - public var unordered: UnorderedView { - get { - UnorderedView(_base: self) - } - _modify { - var view = UnorderedView(_base: self) - self = Uniqued() - defer { self = view._base } - yield &view - } - } -} - -extension Uniqued.UnorderedView: CustomStringConvertible { - public var description: String { - _base.description - } -} - -extension Uniqued.UnorderedView: CustomDebugStringConvertible { - public var debugDescription: String { - _base._debugDescription(typeName: "\(_base._debugTypeName()).UnorderedView") - } -} - -extension Uniqued.UnorderedView: Equatable { - public static func ==(left: Self, right: Self) -> Bool { - if left._base._hasHashTable && left._base._storage === right._base._storage { - return true - } - guard left._base.count == right._base.count else { return false } - - for item in left._base { - if !right._base.contains(item) { return false } - } - return true - } -} - -extension Uniqued.UnorderedView: Hashable { - public func hash(into hasher: inout Hasher) { - // Generate a seed from a snapshot of the hasher. This makes members' hash - // values depend on the state of the hasher, which improves hashing - // quality. (E.g., it makes it possible to resolve collisions by passing in - // a different hasher.) - let copy = hasher - let seed = copy.finalize() - - var hash = 0 - for member in _base { - hash ^= member._rawHashValue(seed: seed) - } - hasher.combine(hash) - } -} - -extension Uniqued.UnorderedView: ExpressibleByArrayLiteral where Base: RangeReplaceableCollection { - @inline(__always) - public init(arrayLiteral elements: Element...) { - _base = Uniqued(elements) - } -} - -extension Uniqued.UnorderedView: SetAlgebra -where Base: RangeReplaceableCollection & MutableCollection { -} - -extension Uniqued.UnorderedView where Base: RangeReplaceableCollection { - public init() { - _base = Uniqued() - } - - public init(_ elements: S) where S.Element == Element { - _base = Uniqued(elements) - } - - // Specializations - - public init(_ elements: Self) { - self = elements - } - - public init(_ elements: Set) { - self._base = Uniqued(elements) - } - - public init(_ elements: Dictionary.Keys) { - self._base = Uniqued(elements) - } -} - -extension Uniqued.UnorderedView { - public func contains(_ element: Element) -> Bool { - _base.contains(element) - } -} - -extension Uniqued.UnorderedView where Base: RangeReplaceableCollection { - public mutating func insert( - _ newMember: __owned Element - ) -> (inserted: Bool, memberAfterInsert: Element) { - let (inserted, index) = _base.append(newMember) - return (inserted, _base[index]) - } -} - -extension Uniqued.UnorderedView where Base: RangeReplaceableCollection & MutableCollection { - public mutating func update(with newMember: __owned Element) -> Element? { - let (inserted, index) = _base.append(newMember) - if inserted { return nil } - let old = _base._elements[index] - _base._elements[index] = newMember - return old - } -} - -extension Uniqued.UnorderedView where Base: RangeReplaceableCollection { - @inline(__always) - @discardableResult - public mutating func remove(_ member: Self.Element) -> Self.Element? { - _base.remove(member) - } -} - -extension Uniqued.UnorderedView where Base: RangeReplaceableCollection { - @inline(__always) - public mutating func formUnion(_ other: __owned Self) { - _base.formUnion(other._base) - } - - @inline(__always) - public __consuming func union(_ other: __owned Self) -> Self { - _base.union(other._base).unordered - } - - // Generalizations - - @inline(__always) - public mutating func formUnion( - _ other: __owned S - ) where S.Element == Element { - _base.formUnion(other) - } - - @inline(__always) - public __consuming func union( - _ other: __owned S - ) -> Self where S.Element == Element { - _base.union(other).unordered - } -} - -extension Uniqued.UnorderedView where Base: RangeReplaceableCollection { - @inline(__always) - public __consuming func intersection(_ other: Self) -> Self { - _base.intersection(other._base).unordered - } - - @inline(__always) - public mutating func formIntersection(_ other: Self) { - _base.formIntersection(other._base) - } - - // Generalizations - - @inline(__always) - public __consuming func intersection( - _ other: S - ) -> Self where S.Element == Element { - _base.intersection(other).unordered - } - - @inline(__always) - public mutating func formIntersection( - _ other: S - ) where S.Element == Element { - _base.formIntersection(other) - } -} - -extension Uniqued.UnorderedView where Base: RangeReplaceableCollection { - @inline(__always) - public __consuming func symmetricDifference(_ other: __owned Self) -> Self { - _base.symmetricDifference(other._base).unordered - } - - @inline(__always) - public mutating func formSymmetricDifference(_ other: __owned Self) { - _base.formSymmetricDifference(other._base) - } - - // Generalizations - - @inline(__always) - public __consuming func symmetricDifference( - _ other: __owned S - ) -> Self where S.Element == Element { - _base.symmetricDifference(other).unordered - } - - @inline(__always) - public mutating func formSymmetricDifference( - _ other: __owned S - ) where S.Element == Element { - _base.formSymmetricDifference(other) - } -} - -extension Uniqued.UnorderedView where Base: RangeReplaceableCollection { - @inline(__always) - public __consuming func subtracting(_ other: Self) -> Self { - _base.subtracting(other._base).unordered - } - - @inline(__always) - public mutating func subtract(_ other: Self) { - _base.subtract(other._base) - } - - // Generalizations - @inline(__always) - public __consuming func subtracting( - _ other: S - ) -> Self where S.Element == Element { - _base.subtracting(other).unordered - } - - @inline(__always) - public mutating func subtract( - _ other: S - ) where S.Element == Element { - _base.subtract(other) - } -} - -extension Uniqued.UnorderedView { - @inline(__always) - public func isSubset(of other: Self) -> Bool { - _base.isSubset(of: other._base) - } - - // Generalizations - - @inline(__always) - public func isSubset(of other: Set) -> Bool { - _base.isSubset(of: other) - } - - @inline(__always) - public func isSubset( - of other: S - ) -> Bool where S.Element == Element { - _base.isSubset(of: other) - } -} - -extension Uniqued.UnorderedView { - @inline(__always) - public func isSuperset(of other: Self) -> Bool { - _base.isSuperset(of: other._base) - } - - // Generalizations - - @inline(__always) - public func isSuperset(of other: Set) -> Bool { - _base.isSuperset(of: other) - } - - @inline(__always) - public func isSuperset( - of other: S - ) -> Bool where S.Element == Element { - _base.isSuperset(of: other) - } -} - -extension Uniqued.UnorderedView { - @inline(__always) - public func isStrictSubset(of other: Self) -> Bool { - _base.isStrictSubset(of: other._base) - } - - // Generalizations - - @inline(__always) - public func isStrictSubset(of other: Set) -> Bool { - _base.isStrictSubset(of: other) - } - - @inline(__always) - public func isStrictSubset( - of other: S - ) -> Bool where S.Element == Element { - _base.isStrictSubset(of: other) - } -} - -extension Uniqued.UnorderedView { - public func isStrictSuperset(of other: Self) -> Bool { - _base.isStrictSuperset(of: other._base) - } - - // Generalizations - - public func isStrictSuperset(of other: Set) -> Bool { - _base.isStrictSuperset(of: other) - } - - public func isStrictSuperset( - of other: S - ) -> Bool where S.Element == Element { - _base.isStrictSuperset(of: other) - } -} - -extension Uniqued.UnorderedView { - public func isDisjoint(with other: Self) -> Bool { - _base.isDisjoint(with: other._base) - } - - // Generalizations - - public func isDisjoint(with other: Set) -> Bool { - _base.isDisjoint(with: other) - } - - public func isDisjoint( - with other: S - ) -> Bool where S.Element == Element { - _base.isDisjoint(with: other) - } -} diff --git a/Sources/UniquedModule/Uniqued.swift b/Sources/UniquedModule/Uniqued.swift deleted file mode 100644 index b4247670..00000000 --- a/Sources/UniquedModule/Uniqued.swift +++ /dev/null @@ -1,203 +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 -// -//===----------------------------------------------------------------------===// - -/// An ordered collection of unique elements. -public struct Uniqued -where Base: RandomAccessCollection, Base.Element: Hashable -{ - internal var _storage: _HashTableStorage? - internal var _elements: Base - - internal init(_uniqueElements: Base, storage: _HashTableStorage? = nil) { - self._storage = storage - self._elements = _uniqueElements - } -} - -extension Uniqued { - public var contents: Base { - _elements - } -} - -extension Uniqued { - /// The maximum number of elements this instance can store before it needs - /// to resize its hash table. - @_spi(Testing) public var _capacity: Int { - _storage?.header.capacity ?? _UnsafeHashTable.maximumUnhashedCount - } - - @_spi(Testing) public var _minimumCapacity: Int { - if _scale == _reservedScale { return 0 } - return _UnsafeHashTable.minimumCapacity(forScale: _scale) - } - - @_spi(Testing) public var _scale: Int { - _storage?.header.scale ?? 0 - } - - @_spi(Testing) public var _reservedScale: Int { - _storage?.header.reservedScale ?? 0 - } - - @_spi(Testing) public var _bias: Int { - _storage?.header.bias ?? 0 - } -} - -extension Uniqued { - internal mutating func _regenerateHashTable(scale: Int, reservedScale: Int) { - assert(_UnsafeHashTable.maximumCapacity(forScale: scale) >= _elements.count) - assert(reservedScale == 0 || reservedScale >= _UnsafeHashTable.minimumScale) - if scale < _UnsafeHashTable.minimumScale && reservedScale == 0 { - _storage = nil - return - } - _storage = _HashTableStorage.create( - from: _elements, - scale: Swift.max(scale, reservedScale), - reservedScale: reservedScale, - stoppingOnFirstDuplicateValue: false).storage - } - - internal mutating func _regenerateHashTable() { - let reservedScale = _reservedScale - guard - _elements.count > _UnsafeHashTable.maximumUnhashedCount || reservedScale != 0 - else { - // We have too few elements; disable hashing. - _storage = nil - return - } - let scale = _UnsafeHashTable.scale(forCapacity: _elements.count) - _regenerateHashTable(scale: scale, reservedScale: reservedScale) - } - - internal mutating func _regenerateExistingHashTable() { - assert(_capacity >= _elements.count) - guard _storage != nil else { - return - } - _ensureUnique() - _storage!.update { hashTable in - hashTable.clear() - hashTable.fill(from: _elements, stoppingOnFirstDuplicateValue: false) - } - } - - internal mutating func _isUnique() -> Bool { - isKnownUniquelyReferenced(&_storage) - } - - internal mutating func _ensureUnique() { - if isKnownUniquelyReferenced(&_storage) { return } - _storage = _storage!.copy() - } - - internal mutating func _uniqueStorage() -> _HashTableStorage? { - if _storage == nil { return nil } - _ensureUnique() - return _storage - } -} - -extension Uniqued { - @_spi(UnsafeInternals) - public func _find(_ item: Element) -> (index: Index?, bucket: _Bucket) { - guard let storage = _storage else { - return (_elements.firstIndex(of: item), _Bucket(offset: 0)) - } - return storage.read { hashTable in - let (offset, bucket) = hashTable._find(item, in: _elements) - return (offset.map { _elements._index(at: $0) }, bucket) - } - } - - internal func _offset(of element: Element) -> Int? { - guard let storage = _storage else { - return _elements.firstIndex(of: element).map { _elements._offset(of: $0) } - } - return storage.read { hashTable in - hashTable._find(element, in: _elements).offset - } - } - - internal func _bucket(for index: Index) -> _Bucket { - guard let storage = _storage else { return _Bucket(offset: 0) } - return storage.read { hashTable in - var it = hashTable.bucketIterator(for: _elements[index]) - let offset = _elements._offset(of: index) - it.advance(until: offset) - precondition(it.isOccupied, "Corrupt hash table") - return it.currentBucket - } - } - - public func firstIndex(of element: Element) -> Index? { - _find(element).index - } - - public func lastIndex(of element: Element) -> Index? { - _find(element).index - } -} - -extension Uniqued where Base: RangeReplaceableCollection { - internal __consuming func _extractSubset( - using bitset: _UnsafeBitset, - extraCapacity: Int = 0 - ) -> Self { - assert(bitset.count == 0 || bitset.max()! <= count) - if bitset.count == 0 { return Self() } - if bitset.count == self.count { return self } - var result = Self() - result.reserveCapacity(bitset.count + extraCapacity) - result._storage?.header.reservedScale = 0 - for offset in bitset { - let index = _elements._index(at: offset) - result._appendNew(_elements[index]) - } - assert(result.count == bitset.count) - return result - } -} - -extension Uniqued where Base: RangeReplaceableCollection { - @_spi(UnsafeInternals) - @discardableResult - public mutating func _removeExistingMember( - at index: Index, - bucket: _Bucket - ) -> Element { - guard _elements.count - 1 >= _minimumCapacity else { - let old = _elements.remove(at: index) - _regenerateHashTable() - return old - } - guard _storage != nil else { - return _elements.remove(at: index) - } - - defer { _checkInvariants() } - _ensureUnique() - _storage!.update { hashTable in - // Delete the entry for the removed member. - hashTable.delete( - bucket: bucket, - hashValueGenerator: { offset, seed in - let index = _elements._index(at: offset) - return _elements[index]._rawHashValue(seed: seed) - }) - hashTable.adjustContents(preparingForRemovalOf: index, in: _elements) - } - return _elements.remove(at: index) - } -} diff --git a/Sources/UniquedModule/_Bucket.swift b/Sources/UniquedModule/_Bucket.swift deleted file mode 100644 index 128e7ea8..00000000 --- a/Sources/UniquedModule/_Bucket.swift +++ /dev/null @@ -1,32 +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 -// -//===----------------------------------------------------------------------===// - -/// Identifies a particular bucket within a hash table by its offset. -/// Having a dedicated wrapper type for this prevents passing a bucket number -/// to a function that expects a word index, or vice versa. -@_spi(UnsafeInternals) @_spi(Testing) -public struct _Bucket { - /// The distance of this bucket from the first bucket in the hash table. - internal var offset: Int - - @inline(__always) - internal init(offset: Int) { - assert(offset >= 0) - self.offset = offset - } -} - -extension _Bucket: Equatable { - @inline(__always) - public static func == (left: Self, right: Self) -> Bool { - left.offset == right.offset - } -} diff --git a/Sources/UniquedModule/_HashTableStorage.swift b/Sources/UniquedModule/_HashTableStorage.swift deleted file mode 100644 index dee26a99..00000000 --- a/Sources/UniquedModule/_HashTableStorage.swift +++ /dev/null @@ -1,108 +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 -// -//===----------------------------------------------------------------------===// - -/// A class holding hash table storage for a `Uniqued` collection. -/// Values in the hash table are offsets into separate element storage, so -/// this class doesn't need to be generic over `Uniqued`'s `Element` type. -internal final class _HashTableStorage: ManagedBuffer<_HashTableHeader, UInt64> { - /// Allocate a new empty hash table buffer of the specified scale. - static func create(scale: Int, reservedScale: Int = 0) -> _HashTableStorage { - assert(scale >= _UnsafeHashTable.minimumScale && scale <= _UnsafeHashTable.maximumScale) - let wordCount = _UnsafeHashTable.wordCount(forScale: scale) - let storage = self.create( - minimumCapacity: wordCount, - makingHeaderWith: { object in - #if COLLECTIONS_DETERMINISTIC_HASHING - let seed = scale << 6 - #else - let seed = Int(bitPattern: Unmanaged.passUnretained(object).toOpaque()) - #endif - return _HashTableHeader(scale: scale, reservedScale: reservedScale, seed: seed) - }) - storage.withUnsafeMutablePointerToElements { elements in - elements.initialize(repeating: 0, count: wordCount) - } - return unsafeDowncast(storage, to: _HashTableStorage.self) - } - - /// Populate a new hash table with data from `self`. - /// - /// - Parameter scale: The desired hash table scale or nil to use the minimum scale that satisfies invariants. - /// - Parameter reservedScale: The reserved scale to remember in the returned storage. - /// - Parameter duplicates: The strategy to use to handle duplicate items. - /// - Returns: `(storage, index)` where `storage` is a storage instance. The contents of `storage` reflects all elements in `contents[contents.startIndex ..< index]`. `index` is usually `contents.endIndex`, except when the function was asked to reject duplicates, in which case `index` addresses the first duplicate element in `contents` (if any). - static func create( - from contents: C, - scale: Int? = nil, - reservedScale: Int = 0, - stoppingOnFirstDuplicateValue: Bool = true - ) -> (storage: _HashTableStorage, end: C.Index) - where C.Element: Hashable { - let minScale = _UnsafeHashTable.scale(forCapacity: contents.count) - let scale = scale ?? Swift.max(Swift.max(minScale, reservedScale), - _UnsafeHashTable.minimumScale) - assert(scale >= minScale && scale >= reservedScale) - let storage = _HashTableStorage.create(scale: scale, reservedScale: reservedScale) - let (_, index) = storage.update { hashTable in - hashTable.fill( - from: contents, - stoppingOnFirstDuplicateValue: stoppingOnFirstDuplicateValue) - } - return (storage, index) - } - - /// Create and return a new copy of this instance. The result has the same - /// scale and seed, and contains the exact same bucket data as the original instance. - internal func copy() -> _HashTableStorage { - self.read { hashTable in - let wordCount = hashTable.wordCount - let new = Self.create( - minimumCapacity: wordCount, - makingHeaderWith: { _ in hashTable._header.pointee }) - new.withUnsafeMutablePointerToElements { elements in - elements.initialize(from: hashTable._buckets, count: wordCount) - } - return unsafeDowncast(new, to: _HashTableStorage.self) - } - } - - /// Call `body` with a hash table handle suitable for read-only use. - /// - /// - Warning: The handle supplied to `body` is only valid for the duration of - /// the closure call. The closure must not escape it outside the call. - @inline(__always) - internal func read(_ body: (_UnsafeHashTable) throws -> R) rethrows -> R { - return try self.withUnsafeMutablePointers { header, elements in - let hashTable = _UnsafeHashTable(header: header, buckets: elements, readonly: true) - defer { withExtendedLifetime(self) {} } - return try body(hashTable) - } - } - - /// Call `body` with a hash table handle suitable for mutating use. - /// - /// - Warning: The handle supplied to `body` is only valid for the duration of - /// the closure call. The closure must not escape it outside the call. - @inline(__always) - internal func update(_ body: (_UnsafeHashTable) throws -> R) rethrows -> R { - return try self.withUnsafeMutablePointers { header, elements in - let hashTable = _UnsafeHashTable(header: header, buckets: elements, readonly: false) - defer { withExtendedLifetime(self) {} } - return try body(hashTable) - } - } -} - -extension _HashTableStorage: CustomStringConvertible { - internal var description: String { - "_HashTableStorage\(header._description)" - } -} diff --git a/Sources/UniquedModule/_HashtableHeader.swift b/Sources/UniquedModule/_HashtableHeader.swift deleted file mode 100644 index ef1af955..00000000 --- a/Sources/UniquedModule/_HashtableHeader.swift +++ /dev/null @@ -1,98 +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 -// -//===----------------------------------------------------------------------===// - -/// The storage header for hash table buffers. -/// -/// Note that we don't store the number of items currently in the table; -/// that information can be easily retrieved from the element storage. -internal struct _HashTableHeader { - /// We are packing the scale data into the lower bits of the seed & bias - /// to saves a bit of space that would be otherwise taken up by padding. - /// - /// Layout: - /// - /// 63 6 5 0 - /// ├──────────────────────────────────────────────┼────────┤ - /// │ seed │ scale │ - /// └──────────────────────────────────────────────┴────────┘ - /// 63 6 5 0 - /// ├──────────────────────────────────────────────┼────────┤ - /// │ bias │ rsvd │ - /// └──────────────────────────────────────────────┴────────┘ - var _scaleAndSeed: UInt64 - var _reservedScaleAndBias: UInt64 - - init(scale: Int, reservedScale: Int, seed: Int) { - assert(scale >= _UnsafeHashTable.minimumScale && scale <= _UnsafeHashTable.maximumScale) - assert(reservedScale >= 0 && reservedScale <= _UnsafeHashTable.maximumScale) - _scaleAndSeed = UInt64(truncatingIfNeeded: seed) << (Swift.max(UInt64.bitWidth - Int.bitWidth, 6)) - _scaleAndSeed &= ~0x3F - _scaleAndSeed |= UInt64(truncatingIfNeeded: scale) - _reservedScaleAndBias = UInt64(truncatingIfNeeded: reservedScale) - assert(self.scale == scale) - assert(self.reservedScale == reservedScale) - assert(self.bias == 0) - } - - /// The scale of the hash table. A table of scale *n* holds 2^*n* buckets, - /// each of which contain an *n*-bit value. - @inline(__always) - var scale: Int { Int(_scaleAndSeed & 0x3F) } - - /// The scale corresponding to the last call to `reserveCapacity`. - /// We remember this here to make sure we don't shrink the table below its reserved size. - var reservedScale: Int { - @inline(__always) - get { Int(_reservedScaleAndBias & 0x3F) } - set { - assert(newValue >= 0 && newValue < 64) - _reservedScaleAndBias &= ~0x3F - _reservedScaleAndBias |= UInt64(truncatingIfNeeded: newValue) & 0x3F - } - } - - /// The hasher seed to use within this hash table. - @inline(__always) - var seed: Int { - Int(truncatingIfNeeded: _scaleAndSeed) - } - - /// A bias value that needs to be added to buckets to convert them into offsets - /// into element storage. (This allows O(1) insertions at the front when the - /// underlying storage supports it.) - var bias: Int { - @inline(__always) - get { Int(truncatingIfNeeded: _reservedScaleAndBias) &>> 6 } - set { - let limit = (1 &<< scale) - 1 - var bias = newValue - if bias < 0 { bias += limit } - if bias >= limit { bias -= limit } - assert(bias >= 0 && bias < limit) - _reservedScaleAndBias &= 0x3F - _reservedScaleAndBias |= UInt64(truncatingIfNeeded: bias) &<< 6 - assert(self.bias >= 0 && self.bias < limit) - } - } - - /// The maximum number of items that can fit into this table. - var capacity: Int { _UnsafeHashTable.maximumCapacity(forScale: scale) } -} - -extension _HashTableHeader: CustomStringConvertible { - internal var _description: String { - "(scale: \(scale), reservedScale: \(reservedScale), bias: \(bias), seed: \(String(seed, radix: 16)))" - } - - internal var description: String { - "_HashTableHeader\(_description)" - } -} diff --git a/Sources/UniquedModule/_UnsafeBitset.swift b/Sources/UniquedModule/_UnsafeBitset.swift deleted file mode 100644 index 079a2b90..00000000 --- a/Sources/UniquedModule/_UnsafeBitset.swift +++ /dev/null @@ -1,321 +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 -// -//===----------------------------------------------------------------------===// - -/// A simple bitmap of a fixed number of bits, implementing a sorted set of -/// small nonnegative `Int` values. -/// -/// Because `_UnsafeBitset` implements a flat bit vector, it isn't suitable for -/// holding arbitrarily large integers. The maximal element a bitset can store -/// is fixed at its initialization. -internal struct _UnsafeBitset { - internal let _words: UnsafeMutableBufferPointer - internal var _count: Int - - @inline(__always) - internal init(words: UnsafeMutableBufferPointer, count: Int) { - self._words = words - self._count = count - } - - @inline(__always) - internal init(words: UnsafeMutablePointer, wordCount: Int, count: Int) { - self._words = UnsafeMutableBufferPointer(start: words, count: wordCount) - self._count = count - } - - @inline(__always) - internal var count: Int { - _count - } -} - -extension _UnsafeBitset { - internal var _actualCount: Int { - return _words.reduce(0) { $0 + $1.count } - } -} - -extension _UnsafeBitset { - static func withTemporaryBitset( - capacity: Int, - run body: (inout _UnsafeBitset) throws -> R - ) rethrows -> R { - let wordCount = _UnsafeBitset.wordCount(forCapacity: capacity) - if wordCount <= 2 { - var buffer: (Word, Word) = (.empty, .empty) - return try withUnsafeMutablePointer(to: &buffer) { p in - // Homogeneous tuples are layout-compatible with their component type. - let words = UnsafeMutableRawPointer(p).assumingMemoryBound(to: Word.self) - var bitset = _UnsafeBitset(words: words, wordCount: wordCount, count: 0) - return try body(&bitset) - } - } - let words = UnsafeMutableBufferPointer.allocate(capacity: wordCount) - words.initialize(repeating: .empty) - defer { words.deallocate() } - var bitset = _UnsafeBitset(words: words, count: 0) - return try body(&bitset) - } -} - -extension _UnsafeBitset { - @inline(__always) - internal static func word(for element: Int) -> Int { - assert(element >= 0) - // Note: We perform on UInts to get faster unsigned math (shifts). - let element = UInt(bitPattern: element) - let capacity = UInt(bitPattern: Word.capacity) - return Int(bitPattern: element / capacity) - } - - @inline(__always) - internal static func bit(for element: Int) -> Int { - assert(element >= 0) - // Note: We perform on UInts to get faster unsigned math (masking). - let element = UInt(bitPattern: element) - let capacity = UInt(bitPattern: Word.capacity) - return Int(bitPattern: element % capacity) - } - - @inline(__always) - internal static func split(_ element: Int) -> (word: Int, bit: Int) { - return (word(for: element), bit(for: element)) - } - - @inline(__always) - internal static func join(word: Int, bit: Int) -> Int { - assert(bit >= 0 && bit < Word.capacity) - return word &* Word.capacity &+ bit - } -} - -extension _UnsafeBitset { - @inline(__always) - internal static func wordCount(forCapacity capacity: Int) -> Int { - return word(for: capacity &+ Word.capacity &- 1) - } - - internal var capacity: Int { - @inline(__always) - get { - return _words.count &* Word.capacity - } - } - - @inline(__always) - internal func isValid(_ element: Int) -> Bool { - return element >= 0 && element < capacity - } - - @inline(__always) - internal func contains(_ element: Int) -> Bool { - assert(isValid(element)) - let (word, bit) = _UnsafeBitset.split(element) - return _words[word].contains(bit) - } - - @discardableResult - internal mutating func insert(_ element: Int) -> Bool { - assert(isValid(element)) - let (word, bit) = _UnsafeBitset.split(element) - let inserted = _words[word].insert(bit) - if inserted { _count += 1 } - return inserted - } - - @discardableResult - internal mutating func remove(_ element: Int) -> Bool { - assert(isValid(element)) - let (word, bit) = _UnsafeBitset.split(element) - let removed = _words[word].remove(bit) - if removed { _count -= 1 } - return removed - } - - internal mutating func clear() { - guard _words.count > 0 else { return } - _words.baseAddress!.assign(repeating: .empty, count: _words.count) - _count = 0 - } - - internal mutating func insertAll(upTo max: Int) { - assert(max <= capacity) - guard max > 0 else { return } - let (w, b) = _UnsafeBitset.split(max) - for i in 0 ..< w { - _count += Word.capacity - _words[i].count - _words[i] = .allBits - } - if b > 0 { - _count += _words[w].insert(bitsBelow: b) - } - } - - internal mutating func removeAll(upTo max: Int) { - assert(max <= capacity) - guard max > 0 else { return } - let (w, b) = _UnsafeBitset.split(max) - for i in 0 ..< w { - _count -= _words[i].count - _words[i] = .empty - } - if b > 0 { - _count -= _words[w].remove(bitsBelow: b) - } - } -} - -extension _UnsafeBitset: Sequence { - internal typealias Element = Int - - internal var underestimatedCount: Int { - return count - } - - func makeIterator() -> Iterator { - return Iterator(self) - } - - internal struct Iterator: IteratorProtocol { - @usableFromInline - internal let bitset: _UnsafeBitset - @usableFromInline - internal var index: Int - @usableFromInline - internal var word: Word - - @inlinable - internal init(_ bitset: _UnsafeBitset) { - self.bitset = bitset - self.index = 0 - self.word = bitset._words.count > 0 ? bitset._words[0] : .empty - } - - internal mutating func next() -> Int? { - if let bit = word.next() { - return _UnsafeBitset.join(word: index, bit: bit) - } - while (index + 1) < bitset._words.count { - index += 1 - word = bitset._words[index] - if let bit = word.next() { - return _UnsafeBitset.join(word: index, bit: bit) - } - } - return nil - } - } -} - -//////////////////////////////////////////////////////////////////////////////// -extension _UnsafeBitset { - internal struct Word { - internal var value: UInt - - internal init(_ value: UInt) { - self.value = value - } - } -} - -extension _UnsafeBitset.Word { - @inline(__always) - internal static var capacity: Int { - return UInt.bitWidth - } - - @inline(__always) - internal var count: Int { - value.nonzeroBitCount - } - - @inline(__always) - internal var isEmpty: Bool { - value == 0 - } - - @inline(__always) - internal func contains(_ bit: Int) -> Bool { - assert(bit >= 0 && bit < UInt.bitWidth) - return value & (1 &<< bit) != 0 - } - - @inline(__always) - @discardableResult - internal mutating func insert(_ bit: Int) -> Bool { - assert(bit >= 0 && bit < UInt.bitWidth) - let mask: UInt = 1 &<< bit - let inserted = value & mask == 0 - value |= mask - return inserted - } - - @inline(__always) - @discardableResult - internal mutating func remove(_ bit: Int) -> Bool { - assert(bit >= 0 && bit < UInt.bitWidth) - let mask: UInt = 1 &<< bit - let removed = value & mask != 0 - value &= ~mask - return removed - } -} - -extension _UnsafeBitset.Word { - @inline(__always) - internal mutating func insert(bitsBelow bit: Int) -> Int { - assert(bit >= 0 && bit < Self.capacity) - let mask: UInt = (1 as UInt &<< bit) &- 1 - let inserted = bit - (value & mask).nonzeroBitCount - value |= mask - return inserted - } - - @inline(__always) - internal mutating func remove(bitsBelow bit: Int) -> Int { - assert(bit >= 0 && bit < Self.capacity) - let mask = UInt.max &<< bit - let removed = (value & ~mask).nonzeroBitCount - value &= mask - return removed - } -} - -extension _UnsafeBitset.Word { - @inline(__always) - internal static var empty: Self { - Self(0) - } - - @inline(__always) - internal static var allBits: Self { - Self(UInt.max) - } -} - -// Word implements Sequence by using a copy of itself as its Iterator. -// Iteration with `next()` destroys the word's value; however, this won't cause -// problems in normal use, because `next()` is usually called on a separate -// iterator, not the original word. -extension _UnsafeBitset.Word: Sequence, IteratorProtocol { - internal var underestimatedCount: Int { - count - } - - /// Return the index of the lowest set bit in this word, - /// and also destructively clear it. - internal mutating func next() -> Int? { - guard value != 0 else { return nil } - let bit = value.trailingZeroBitCount - value &= value &- 1 // Clear lowest nonzero bit. - return bit - } -} diff --git a/Sources/UniquedModule/_UnsafeHashTable.swift b/Sources/UniquedModule/_UnsafeHashTable.swift deleted file mode 100644 index e465ed41..00000000 --- a/Sources/UniquedModule/_UnsafeHashTable.swift +++ /dev/null @@ -1,707 +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 -// -//===----------------------------------------------------------------------===// - -/// A non-owning handle to hash table storage, implementing higher-level table operations. -/// -/// - Warning: `_UnsafeHashTable` values do not have ownership of their underlying storage buffer. -/// You must not escape these handles outside the closure call that produced them. -@_spi(Testing) public struct _UnsafeHashTable { - /// A pointer to the table header. - internal var _header: UnsafeMutablePointer<_HashTableHeader> - - /// A pointer to bucket storage. - internal var _buckets: UnsafeMutablePointer - - #if DEBUG - /// True when this handle does not support table mutations. - /// (This is only checked in debug builds.) - internal let _readonly: Bool - #endif - - /// Initialize a new hash table handle for storage at the supplied locations. - @inline(__always) - internal init( - header: UnsafeMutablePointer<_HashTableHeader>, - buckets: UnsafeMutablePointer, - readonly: Bool - ) { - self._header = header - self._buckets = buckets - #if DEBUG - self._readonly = readonly - #endif - } - - /// Check that this handle supports mutating operations. - /// Every member that mutates table data must start by calling this function. - /// This helps preventing COW violations. - /// - /// Note that this is a noop in release builds. - @inline(__always) - func assertMutable() { - #if DEBUG - assert(!_readonly, "Attempt to mutate a hash table through a read-only handle") - #endif - } -} - -extension _UnsafeHashTable { - /// The minimum hash table scale. - @inline(__always) - @_spi(Testing) - public static var minimumScale: Int { 5 } - - /// The maximum hash table scale. - @inline(__always) - @_spi(Testing) - public static var maximumScale: Int { - Swift.min(Int.bitWidth, 56) - } - - /// The maximum number of items for which we do not create a hash table. - @inline(__always) - @_spi(Testing) - public static var maximumUnhashedCount: Int { - (1 &<< (minimumScale - 1)) - 1 - } - - /// The maximum hash table load factor. - @inline(__always) - static var maximumLoadFactor: Double { 3 / 4 } - - /// The minimum hash table load factor. - @inline(__always) - static var minimumLoadFactor: Double { 1 / 4 } - - /// The maximum number of items that can be held in a hash table of the given scale. - @_spi(Testing) - public static func maximumCapacity(forScale scale: Int) -> Int { - guard scale >= minimumScale else { return maximumUnhashedCount } - let bucketCount = 1 &<< scale - return Int(Double(bucketCount) * maximumLoadFactor) - } - - /// The maximum number of items that can be held in a hash table of the given scale. - @_spi(Testing) - public static func minimumCapacity(forScale scale: Int) -> Int { - guard scale >= minimumScale else { return 0 } - let bucketCount = 1 &<< scale - return Int(Double(bucketCount) * minimumLoadFactor) - } - - /// The minimum hash table scale that can hold the specified number of elements. - @_spi(Testing) - public static func scale(forCapacity capacity: Int) -> Int { - guard capacity > maximumUnhashedCount else { return 0 } - let capacity = Swift.max(capacity, 1) - // Calculate the minimum number of entries we need to allocate to satisfy - // the maximum load factor. `capacity + 1` below ensures that we always - // leave at least one hole. - let minimumEntries = Swift.max( - Int((Double(capacity) / maximumLoadFactor).rounded(.up)), - capacity + 1) - // The actual number of entries we need to allocate is the lowest power of - // two greater than or equal to the minimum entry count. Calculate its - // exponent. - let scale = (Swift.max(minimumEntries, 2) - 1)._binaryLogarithm() + 1 - assert(scale >= minimumScale && scale < Int.bitWidth) - // The scale is the exponent corresponding to the bucket count. - assert(self.maximumCapacity(forScale: scale) >= capacity) - return scale - } - - @_spi(Testing) - public static func biasRange(scale: Int) -> Range { - guard scale != 0 else { return 0 ..< 1 } - return 0 ..< (1 &<< scale) - 1 - } - - /// The count of 64-bit words that a hash table of the specified scale - /// will need to have in its storage. - internal static func wordCount(forScale scale: Int) -> Int { - ((scale &<< scale) + UInt64.bitWidth - 1) / UInt64.bitWidth - } -} - -extension _UnsafeHashTable { - /// The scale of the hash table. A table of scale *n* holds 2^*n* buckets, - /// each of which contain an *n*-bit value. - @inline(__always) - internal var scale: Int { _header.pointee.scale } - - /// The scale corresponding to the last call to `reserveCapacity`. - /// We store this to make sure we don't shrink the table below its reserved size. - @inline(__always) - internal var reservedScale: Int { - get { _header.pointee.reservedScale } - nonmutating set { _header.pointee.reservedScale = newValue } - } - - /// The hasher seed to use within this hash table. - @inline(__always) - internal var seed: Int { _header.pointee.seed } - - /// A bias value that needs to be added to buckets to convert them into offsets - /// into element storage. (This allows O(1) insertions at the front when the - /// underlying storage supports it.) - @inline(__always) - internal var bias: Int { - get { _header.pointee.bias } - nonmutating set { _header.pointee.bias = newValue } - } - - /// The number of buckets within this hash table. This is always a power of two. - @inline(__always) - internal var bucketCount: Int { 1 &<< scale } - - @inline(__always) - internal var bucketMask: UInt64 { UInt64(truncatingIfNeeded: bucketCount) - 1 } - - /// The number of bits used to store all the buckets in this hash table. - /// Each bucket holds a value that is `scale` bits wide. - @inline(__always) - internal var bitCount: Int { scale &<< scale } - - /// The number of 64-bit words that are available in the storage buffer, - /// rounded up to the nearest whole number if necessary. - @inline(__always) - internal var wordCount: Int { (bitCount + UInt64.bitWidth - 1) / UInt64.bitWidth } - - /// The maximum number of items that can fit into this table. - @inline(__always) - internal var capacity: Int { _UnsafeHashTable.maximumCapacity(forScale: scale) } - - /// Return the bucket logically following `bucket` in this hash table. - /// The buckets form a cycle, so the last bucket is logically followed by the first. - @inline(__always) - func bucket(after bucket: _Bucket) -> _Bucket { - var offset = bucket.offset + 1 - if offset == bucketCount { - offset = 0 - } - return _Bucket(offset: offset) - } - - /// Return the bucket logically preceding `bucket` in this hash table. - /// The buckets form a cycle, so the first bucket is logically preceded by the last. - @inline(__always) - func bucket(before bucket: _Bucket) -> _Bucket { - let offset = (bucket.offset == 0 ? bucketCount : bucket.offset) - 1 - return _Bucket(offset: offset) - } - - /// Return the index of the word logically following `word` in this hash table. - /// The buckets form a cycle, so the last word is logically followed by the first. - /// - /// Note that the last word may be only partially filled if `scale` is less than 6. - @inline(__always) - func word(after word: Int) -> Int { - var result = word + 1 - if result == wordCount { - result = 0 - } - return result - } - - /// Return the index of the word logically preceding `word` in this hash table. - /// The buckets form a cycle, so the first word is logically preceded by the first. - /// - /// Note that the last word may be only partially filled if `scale` is less than 6. - @inline(__always) - func word(before word: Int) -> Int { - if word == 0 { - return wordCount - 1 - } - return word - 1 - } - - /// Return the index of the 64-bit storage word that holds the first bit - /// corresponding to `bucket`, along with its bit position within the word. - internal func position(of bucket: _Bucket) -> (word: Int, bit: Int) { - let start = bucket.offset &* scale - return (start &>> 6, start & 0x3F) - } -} - -extension _UnsafeHashTable { - /// Decode and return the logical value corresponding to the specified bucket value. - /// - /// The nil value is represented by an all-zero bit pattern. - /// Other values are stored as the complement of the lowest `scale` bits - /// after taking `bias` into account. - /// The range of representable values is `0 ..< bucketCount - 1`. - /// (Note that the value `bucketCount - 1` is missing from this range, as its - /// encoding is used for `nil`. This isn't an issue, because the maximum load - /// factor guarantees that the hash table will never be completely full.) - func _value(forBucketContents bucketContents: UInt64) -> Int? { - let mask = bucketMask - assert(bucketContents <= mask) - guard bucketContents != 0 else { return nil } - let v = (bucketContents ^ mask) &+ UInt64(truncatingIfNeeded: bias) - return Int(truncatingIfNeeded: v >= mask ? v - mask : v) - } - - /// Encodes the specified logical value into a `scale`-bit bit pattern suitable - /// for storing into a bucket. - /// - /// The nil value is represented by an all-zero bit pattern. - /// Other values are stored as the complement of their lowest `scale` bits. - /// The range of representable values is `0 ..< bucketCount - 1`. - /// (Note that the value `bucketCount - 1` is missing from this range, as it - /// its encoding is used for `nil`. This isn't an issue, because the maximum - /// load factor guarantees that the hash table will never be completely full.) - func _bucketContents(for value: Int?) -> UInt64 { - guard var value = value else { return 0 } - let mask = Int(truncatingIfNeeded: bucketMask) - assert(value >= 0 && value < mask) - value &-= bias - if value < 0 { value += mask } - assert(value >= 0 && value < mask) - return UInt64(truncatingIfNeeded: value ^ mask) - } - - subscript(word word: Int) -> UInt64 { - @inline(__always) get { - assert(word >= 0 && word < bucketCount) - return _buckets[word] - } - @inline(__always) nonmutating set { - assert(word >= 0 && word < bucketCount) - assertMutable() - _buckets[word] = newValue - } - } - - subscript(raw bucket: _Bucket) -> UInt64 { - get { - assert(bucket.offset < bucketCount) - let (word, bit) = position(of: bucket) - var value = self[word: word] &>> bit - let extractedBits = 64 - bit - if extractedBits < scale { - let word2 = self.word(after: word) - value &= (1 &<< extractedBits) - 1 - value |= self[word: word2] &<< extractedBits - } - return value & bucketMask - } - nonmutating set { - assertMutable() - assert(bucket.offset < bucketCount) - let mask = bucketMask - assert(newValue <= mask) - let (word, bit) = position(of: bucket) - self[word: word] &= ~(mask &<< bit) - self[word: word] |= newValue &<< bit - let extractedBits = 64 - bit - if extractedBits < scale { - let word2 = self.word(after: word) - self[word: word2] &= ~((1 &<< (scale - extractedBits)) - 1) - self[word: word2] |= newValue &>> extractedBits - } - } - } - - func isOccupied(_ bucket: _Bucket) -> Bool { - self[raw: bucket] != 0 - } - - /// Return or update the current value stored in the specified bucket. - /// A nil value indicates that the bucket is empty. - subscript(bucket: _Bucket) -> Int? { - get { - let contents = self[raw: bucket] - return _value(forBucketContents: contents) - } - nonmutating set { - assertMutable() - let v = _bucketContents(for: newValue) - self[raw: bucket] = v - } - } -} - -extension _UnsafeHashTable { - /// An infinite iterator construct for visiting a chain of buckets within the hash table. - /// This is a convenient tool for linear probing. - /// - /// Beyond merely providing bucket values, bucket iterators can also tell - /// you their current oposition within the hash table, and (for mutable hash tables) - /// they allow you update the value of the currently visited bucket. - /// (This is useful when implementing simple insertions, for example.) - /// - /// The bucket iterator caches some bucket contents, so if you are looping over an iterator - /// you must be careful to only modify hash table contents through the iterator itself. - /// - /// - Warning: Like `_UnsafeHashTable` itself, `BucketIterator` does not have - /// ownership of its underlying storage buffer. You must not escape iterator - /// values outside the closure call that produced the original hash table. - struct BucketIterator { - /// The hash table we are iterating over. - let _hashTable: _UnsafeHashTable - - /// The current position within the hash table. - var _currentBucket: _Bucket - - /// The raw bucket value corresponding to `_currentBucket`. - var _currentRawValue: UInt64 - - /// Remaining bits not yet processed from the last word read. - var _nextBits: UInt64 - - /// Count of usable bits in `_nextBits`. (They start at bit 0.) - var _remainingBitCount: Int - - /// Create a new iterator starting at the specified bucket. - init(hashTable: _UnsafeHashTable, startingAt bucket: _Bucket) { - assert(hashTable.scale >= _UnsafeHashTable.minimumScale) - assert(bucket.offset >= 0 && bucket.offset < hashTable.bucketCount) - self._hashTable = hashTable - self._currentBucket = bucket - var (word, bit) = hashTable.position(of: bucket) - - // The `scale == 5` case is special because the last word is only half filled there, - // which is why the code below needs to special case it. - // (For all scales > 5, the last bucket ends exactly on a word boundary.) - - if bit + hashTable.scale <= 64 { - // We're in luck, the current bucket is stored entirely within one word. - let w = _hashTable[word: word] - _currentRawValue = (w &>> bit) & _hashTable.bucketMask - let c = (hashTable.scale == 5 && word == hashTable.wordCount - 1 ? 32 : 64) - self._remainingBitCount = c - (bit + hashTable.scale) - self._nextBits = (_remainingBitCount == 0 ? 0 : w &>> (bit + hashTable.scale)) - assert(_remainingBitCount >= 0) - assert(bit < c) - } else { - // We need to read two words. - assert(hashTable.scale != 5 || word < hashTable.wordCount - 1) - assert(bit > 0) - let w1 = _hashTable[word: word] - word = hashTable.word(after: word) - let w2 = _hashTable[word: word] - self._currentRawValue = ((w1 &>> bit) | (w2 &<< (64 - bit))) & _hashTable.bucketMask - let overhang = hashTable.scale - (64 - bit) - self._nextBits = w2 &>> overhang - let c = (hashTable.scale == 5 && word == hashTable.wordCount - 1 ? 32 : 64) - self._remainingBitCount = c - overhang - } - assert(_currentRawValue <= _hashTable.bucketMask) - } - - /// The scale of the hash table. A table of scale *n* holds 2^*n* buckets, - /// each of which contain an *n*-bit value. - @inline(__always) - var _scale: Int { _hashTable.scale } - - /// The current position within the hash table. - @inline(__always) - var currentBucket: _Bucket { _currentBucket } - - var isOccupied: Bool { - _currentRawValue != 0 - } - - /// The value of the bucket at the current position in the hash table. - /// Setting this property overwrites the bucket value. - /// - /// A nil value indicates an empty bucket. - var currentValue: Int? { - @inline(__always) - get { _hashTable._value(forBucketContents: _currentRawValue) } - set { - _hashTable.assertMutable() - let v = _hashTable._bucketContents(for: newValue) - let pattern = v ^ _currentRawValue - - assert(_currentBucket.offset < _hashTable.bucketCount) - let (word, bit) = _hashTable.position(of: _currentBucket) - _hashTable[word: word] ^= pattern &<< bit - let extractedBits = 64 - bit - if extractedBits < _scale { - let word2 = _hashTable.word(after: word) - _hashTable[word: word2] ^= pattern &>> extractedBits - } - _currentRawValue = v - } - } - - /// Advance this iterator to the next bucket within the hash table. - /// The buckets form a cycle, so the last bucket is logically followed - /// by the first. Therefore, the iterator never runs out of buckets -- - /// you must devise some way to guarantee to stop iterating. - /// - /// In the typical case, you stop iterating buckets when you find the - /// element you're looking for, or when you run across an empty bucket - /// (terminating the chain with a negative lookup result). - mutating func advance() { - _currentBucket = _hashTable.bucket(after: _currentBucket) - if _remainingBitCount >= _scale { - _currentRawValue = _nextBits & _hashTable.bucketMask - _nextBits &>>= _scale - _remainingBitCount -= _scale - return - } - var word = _hashTable.position(of: _currentBucket).word - if _remainingBitCount != 0 { - word = _hashTable.word(after: word) - } - let c = (_hashTable.scale == 5 && word == _hashTable.wordCount - 1 ? 32 : 64) - let w = _hashTable[word: word] - _currentRawValue = (_nextBits | (w &<< _remainingBitCount)) & _hashTable.bucketMask - _nextBits = w &>> (_scale - _remainingBitCount) - _remainingBitCount = c - (_scale - _remainingBitCount) - } - - /// Advance this iterator until it points to an occupied bucket with the - /// specified value, or an unoccupied bucket -- whichever comes first. - mutating func advance(until expected: Int) { - while isOccupied && currentValue != expected { - advance() - } - } - - /// Advance this iterator until it points to an unoccupied bucket. - /// Useful when inserting an element that we know isn't already in the table. - mutating func advanceToNextUnoccupiedBucket() { - while isOccupied { - advance() - } - } - } - - @inline(__always) - func idealBucket(forHashValue hashValue: Int) -> _Bucket { - return _Bucket(offset: hashValue & (bucketCount - 1)) - } - - @inline(__always) - func idealBucket(for element: Element) -> _Bucket { - let hashValue = element._rawHashValue(seed: seed) - return idealBucket(forHashValue: hashValue) - } - - /// Return a bucket iterator for the chain starting at the bucket corresponding - /// to the specified value. - @inline(__always) - func bucketIterator(for element: Element) -> BucketIterator { - let bucket = idealBucket(for: element) - return bucketIterator(startingAt: bucket) - } - - /// Return a bucket iterator for the chain starting at the specified bucket. - @inline(__always) - func bucketIterator(startingAt bucket: _Bucket) -> BucketIterator { - BucketIterator(hashTable: self, startingAt: bucket) - } -} - -extension _UnsafeHashTable { - internal func _find( - _ item: Base.Element, - in elements: Base - ) -> (offset: Int?, bucket: _Bucket) - where Base.Element: Hashable { - var iterator = self.bucketIterator(for: item) - let start = iterator.currentBucket - repeat { - guard let offset = iterator.currentValue else { - return (nil, iterator.currentBucket) - } - if elements[_offset: offset] == item { - return (offset, iterator.currentBucket) - } - iterator.advance() - } while iterator.currentBucket.offset != start.offset - fatalError("Hash table has no unoccupied buckets") - } -} - -extension _UnsafeHashTable { - internal func firstUnoccupiedBucket(before bucket: _Bucket) -> _Bucket { - var bucket = bucket - repeat { - bucket = self.bucket(before: bucket) - } while isOccupied(bucket) - return bucket - } - - internal func delete( - bucket: _Bucket, - hashValueGenerator: (Int, Int) -> Int // (offset, seed) -> hashValue - ) { - assertMutable() - var it = bucketIterator(startingAt: bucket) - assert(it.isOccupied) - it.advance() - guard it.isOccupied else { - // Fast path: Don't get the start bucket when there's nothing to do. - self[bucket] = nil - return - } - // If we've put a hole in the middle of a collision chain, some element after - // the hole may belong where the new hole is. - - // Find the first bucket in the collision chain that contains the entry we've just deleted. - let start = self.bucket(after: firstUnoccupiedBucket(before: bucket)) - var hole = bucket - - while it.isOccupied { - let hash = hashValueGenerator(it.currentValue!, seed) - let candidate = idealBucket(forHashValue: hash) - - // Does this element belong between start and hole? We need two - // separate tests depending on whether [start, hole] wraps around the - // end of the storage. - let c0 = candidate.offset >= start.offset - let c1 = candidate.offset <= hole.offset - if start.offset <= hole.offset ? (c0 && c1) : (c0 || c1) { - // Fill the hole. Here we are mutating table contents behind the back of - // the iterator; this is okay since we know we are never going to revisit - // `hole` with it. - self[hole] = it.currentValue - hole = it.currentBucket - } - it.advance() - } - self[hole] = nil - } -} - -extension _UnsafeHashTable { - internal func adjustContents( - preparingForInsertionOfElementAtOffset offset: Int, - in elements: Base - ) where Base.Element: Hashable { - assertMutable() - let index = elements._index(at: offset) - if offset < elements.count / 2 { - self.bias += 1 - if offset <= capacity / 8 { - var i = 1 - for item in elements[..= offset else { continue } - it.currentValue = value + 1 - } while it.currentBucket.offset != 0 - } - } - } -} - -extension _UnsafeHashTable { - @inline(__always) - internal func adjustContents( - preparingForRemovalOf index: Base.Index, - in elements: Base - ) where Base.Element: Hashable { - let next = elements.index(after: index) - adjustContents(preparingForRemovalOf: index ..< next, in: elements) - } - - internal func adjustContents( - preparingForRemovalOf bounds: Range, - in elements: Base - ) where Base.Element: Hashable { - assertMutable() - let startOffset = elements._offset(of: bounds.lowerBound) - let endOffset = elements._offset(of: bounds.upperBound) - let c = endOffset - startOffset - guard c > 0 else { return } - let remainingCount = elements.count - c - - if startOffset >= remainingCount / 2 { - var i = endOffset - for item in elements[bounds.upperBound...] { - var it = self.bucketIterator(for: item) - it.advance(until: i) - it.currentValue = i - c - i += 1 - } - } else { - var i = 0 - for item in elements[..( - from elements: C, - stoppingOnFirstDuplicateValue: Bool = true - ) -> (success: Bool, end: C.Index) - where C.Element: Hashable { - assertMutable() - assert(elements.count <= capacity) - // Iterate over elements and insert their offset into the hash table. - var offset = 0 - loop: for index in elements.indices { - // Find the insertion position. We know that we're inserting a new item, - // so there is no need to compare it with any of the existing ones. - var it = bucketIterator(for: elements[index]) - if stoppingOnFirstDuplicateValue { - while let offset = it.currentValue { - guard elements[_offset: offset] != elements[index] else { - return (false, index) - } - it.advance() - } - } else { - it.advanceToNextUnoccupiedBucket() - } - it.currentValue = offset - offset += 1 - } - return (true, elements.endIndex) - } -} diff --git a/Tests/UniquedTests/BItsetTests.swift b/Tests/UniquedTests/BItsetTests.swift deleted file mode 100644 index a9be8382..00000000 --- a/Tests/UniquedTests/BItsetTests.swift +++ /dev/null @@ -1,187 +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 -// -//===----------------------------------------------------------------------===// - -#if DEBUG // These unit tests need access to Uniqued internals -import XCTest -import CollectionsTestSupport -@_spi(Testing) @testable import UniquedModule - -class BitsetTests: CollectionTestCase { - typealias Word = _UnsafeBitset.Word - - func test_empty() { - withEvery("capacity", in: 0 ..< 500) { capacity in - _UnsafeBitset.withTemporaryBitset(capacity: capacity) { bitset in - expectGreaterThanOrEqual(bitset.capacity, capacity) - expectEqual(bitset.count, 0) - expectEqual(bitset._actualCount, 0) - withEvery("i", in: 0 ..< capacity) { i in - expectFalse(bitset.contains(i)) - } - } - } - } - - func test_insert() { - withEvery("capacity", in: [16, 64, 100, 128, 1000, 1024]) { capacity in - withEvery("seed", in: 0 ..< 3) { seed in - var rng = RepeatableRandomNumberGenerator(seed: seed) - let items = (0 ..< capacity).shuffled(using: &rng) - _UnsafeBitset.withTemporaryBitset(capacity: capacity) { bitset in - var c = 0 - withEvery("item", in: items) { item in - expectFalse(bitset.contains(item)) - expectTrue(bitset.insert(item)) - - expectTrue(bitset.contains(item)) - expectFalse(bitset.insert(item)) - - c += 1 - expectEqual(bitset.count, c) - } - } - } - } - } - - func withRandomBitsets( - capacity: Int, - loadFactor: Double, - body: (inout _UnsafeBitset, inout Set) throws -> Void - ) rethrows { - precondition(loadFactor >= 0 && loadFactor <= 1) - try withEvery("seed", in: 0 ..< 10) { seed in - var rng = RepeatableRandomNumberGenerator(seed: seed) - var items = (0 ..< capacity).shuffled(using: &rng) - items.removeLast(Int((1 - loadFactor) * Double(capacity))) - try _UnsafeBitset.withTemporaryBitset(capacity: capacity) { bitset in - for item in items { - bitset.insert(item) - } - var set = Set(items) - try body(&bitset, &set) - } - } - } - - func test_remove() { - withEvery("capacity", in: [16, 64, 100, 128, 1000, 1024]) { capacity in - withRandomBitsets(capacity: capacity, loadFactor: 0.5) { bitset, contents in - var c = contents.count - withEvery("item", in: 0 ..< capacity) { item in - if contents.contains(item) { - expectTrue(bitset.remove(item)) - expectFalse(bitset.contains(item)) - c -= 1 - expectEqual(bitset.count, c) - } else { - expectFalse(bitset.remove(item)) - expectEqual(bitset.count, c) - } - } - expectEqual(bitset.count, 0) - withEvery("item", in: 0 ..< capacity) { item in - expectFalse(bitset.contains(item)) - } - } - } - } - - func test_clear() { - withEvery("capacity", in: [16, 64, 100, 128, 1000, 1024]) { capacity in - withRandomBitsets(capacity: capacity, loadFactor: 0.5) { bitset, contents in - bitset.clear() - expectEqual(bitset.count, 0) - withEvery("item", in: 0 ..< capacity) { item in - expectFalse(bitset.contains(item)) - } - } - } - } - - func test_insertAll_upTo() { - withEvery("capacity", in: [16, 64, 100, 128, 1000, 1024]) { capacity in - withRandomBitsets(capacity: capacity, loadFactor: 0.5) { bitset, contents in - - let cutoff = capacity / 2 - bitset.insertAll(upTo: cutoff) - expectEqual( - bitset.count, - capacity / 2 + contents.lazy.filter { $0 >= cutoff }.count) - withEvery("item", in: 0 ..< capacity) { item in - if item < cutoff { - expectTrue(bitset.contains(item)) - } else { - expectEqual(bitset.contains(item), contents.contains(item)) - } - } - - bitset.insertAll(upTo: capacity) - expectEqual(bitset.count, capacity) - withEvery("item", in: 0 ..< capacity) { item in - expectTrue(bitset.contains(item)) - } - } - } - } - - func test_removeAll_upTo() { - withEvery("capacity", in: [16, 64, 100, 128, 1000, 1024]) { capacity in - withRandomBitsets(capacity: capacity, loadFactor: 0.5) { bitset, contents in - - let cutoff = capacity / 2 - bitset.removeAll(upTo: cutoff) - expectEqual( - bitset.count, - contents.lazy.filter { $0 >= cutoff }.count) - withEvery("item", in: 0 ..< capacity) { item in - if item < cutoff { - expectFalse(bitset.contains(item)) - } else { - expectEqual(bitset.contains(item), contents.contains(item)) - } - } - - bitset.removeAll(upTo: capacity) - expectEqual(bitset.count, 0) - withEvery("item", in: 0 ..< capacity) { item in - expectFalse(bitset.contains(item)) - } - } - } - } - - func test_Sequence() { - withEvery("capacity", in: [16, 64, 100, 128, 1000, 1024]) { capacity in - withRandomBitsets(capacity: capacity, loadFactor: 0.5) { bitset, contents in - expectEqual(bitset.underestimatedCount, contents.count) - let expected = contents.sorted() - var actual: [Int] = [] - actual.reserveCapacity(bitset.count) - for item in bitset { - actual.append(item) - } - expectEqual(actual, expected) - } - } - } - - func test_max() { - withEvery("capacity", in: [16, 64, 100, 128, 1000, 1024]) { capacity in - withRandomBitsets(capacity: capacity, loadFactor: 0.5) { bitset, contents in - let max = bitset.max() - expectEqual(max, contents.max()) - } - } - } - -} -#endif // DEBUG diff --git a/Tests/UniquedTests/HashTableTests.swift b/Tests/UniquedTests/HashTableTests.swift deleted file mode 100644 index f168a479..00000000 --- a/Tests/UniquedTests/HashTableTests.swift +++ /dev/null @@ -1,607 +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 -// -//===----------------------------------------------------------------------===// - -#if DEBUG // These unit tests need access to Uniqued internals -import XCTest -import CollectionsTestSupport -@_spi(Testing) @testable import UniquedModule - -class HashTableTests: CollectionTestCase { - func test_capacity() { - withEvery("capacity", in: 0 ..< 1000) { capacity in - let scale = _UnsafeHashTable.scale(forCapacity: capacity) - let maximumCapacity = _UnsafeHashTable.maximumCapacity(forScale: scale) - let minimumCapacity = _UnsafeHashTable.minimumCapacity(forScale: scale) - - if scale == 0 { - expectEqual(minimumCapacity, 0) - expectEqual(maximumCapacity, _UnsafeHashTable.maximumUnhashedCount) - expectGreaterThanOrEqual(maximumCapacity, capacity) - } else { - let bucketCount = 1 &<< scale - expectGreaterThanOrEqual(scale, _UnsafeHashTable.minimumScale) - expectLessThan(scale, _UnsafeHashTable.maximumScale) - expectGreaterThanOrEqual(maximumCapacity, capacity) - expectGreaterThan(bucketCount, maximumCapacity) - expectLessThan(minimumCapacity, maximumCapacity) - expectLessThanOrEqual(minimumCapacity, capacity) - expectGreaterThan(minimumCapacity, 0) - } - } - } - - func test_Storage_create() { - let s5 = _HashTableStorage.create(scale: 5) - expectEqual(s5.header.scale, 5) - expectEqual(s5.header.reservedScale, 0) - expectTrue(s5.description.starts(with: "_HashTableStorage(scale: 5, reservedScale: 0, bias: 0, seed: ")) - expectTrue(s5.header.description.starts(with: "_HashTableHeader(scale: 5, reservedScale: 0, bias: 0, seed: ")) - s5.read { hashTable in - for i in 0 ..< 32 { - let bucket = _Bucket(offset: i) - expectNil(hashTable[bucket], "\(bucket.offset)") - } - } - - let s6 = _HashTableStorage.create(scale: 6) - expectEqual(s6.header.scale, 6) - expectEqual(s6.header.reservedScale, 0) - expectTrue(s6.description.starts(with: "_HashTableStorage(scale: 6, reservedScale: 0, bias: 0, seed: ")) - expectTrue(s6.header.description.starts(with: "_HashTableHeader(scale: 6, reservedScale: 0, bias: 0, seed: ")) - s6.read { hashTable in - for i in 0 ..< 64 { - let bucket = _Bucket(offset: i) - expectNil(hashTable[bucket], "\(bucket.offset)") - } - } - - expectNotEqual(s6.header.seed, s5.header.seed) // This is somewhat shaky b/c we're losing address bits - - expectEqual(s5.header.capacity, 24) // 0.75 * 2^5 - expectEqual(s6.header.capacity, 48) // 0.75 * 2^6 - } - - func test_Storage_read() { - let s5 = _HashTableStorage.create(scale: 5) - s5.read { hashTable in - expectEqual(hashTable.scale, 5) - expectEqual(hashTable.reservedScale, 0) - expectEqual(hashTable.seed, s5.header.seed) - expectTrue(hashTable.description.starts(with: "_UnsafeHashTable(scale: 5, reservedScale: 0, bias: 0, seed: ")) - } - let s6 = _HashTableStorage.create(scale: 6) - s6.read { hashTable in - expectEqual(hashTable.scale, 6) - expectEqual(hashTable.reservedScale, 0) - expectEqual(hashTable.seed, s6.header.seed) - expectTrue(hashTable.description.starts(with: "_UnsafeHashTable(scale: 6, reservedScale: 0, bias: 0, seed: ")) - } - } - - func test_counts() { - let s5 = _HashTableStorage.create(scale: 5) - s5.read { hashTable in - expectEqual(hashTable.bucketCount, 32) - expectEqual(hashTable.bitCount, 5 * 32) - expectEqual(hashTable.wordCount, 3) // 2.5 rounded up - expectEqual(hashTable.capacity, 24) // 0.75 * 32 - } - let s6 = _HashTableStorage.create(scale: 6) - s6.read { hashTable in - expectEqual(hashTable.bucketCount, 64) - expectEqual(hashTable.bitCount, 6 * 64) - expectEqual(hashTable.wordCount, 6) - expectEqual(hashTable.capacity, 48) // 0.75 * 64 - } - let s12 = _HashTableStorage.create(scale: 12) - s12.read { hashTable in - expectEqual(hashTable.bucketCount, 4096) - expectEqual(hashTable.bitCount, 12 * 4096) - expectEqual(hashTable.wordCount, 768) - expectEqual(hashTable.capacity, 3072) // 0.75 * 4096 - } - } - - func test_bucket_after() { - withEvery("scale", in: [5, 6, 12]) { scale in - let storage = _HashTableStorage.create(scale: scale) - storage.read { hashTable in - withEvery("offset", in: 0 ..< hashTable.bucketCount) { offset in - let input = _Bucket(offset: offset) - let expected = _Bucket(offset: offset == hashTable.bucketCount - 1 ? 0 : offset + 1) - let actual = hashTable.bucket(after: input) - expectEqual(actual, expected) - } - } - } - } - func test_bucket_before() { - withEvery("scale", in: [5, 6, 12]) { scale in - let storage = _HashTableStorage.create(scale: scale) - storage.read { hashTable in - withEvery("offset", in: 0 ..< hashTable.bucketCount) { offset in - let input = _Bucket(offset: offset) - let expected = _Bucket(offset: offset == 0 ? hashTable.bucketCount - 1 : offset - 1) - let actual = hashTable.bucket(before: input) - expectEqual(actual, expected) - } - } - } - } - func test_word_after() { - withEvery("scale", in: [5, 6, 12]) { scale in - let storage = _HashTableStorage.create(scale: scale) - storage.read { hashTable in - withEvery("input", in: 0 ..< hashTable.wordCount) { input in - let expected = (input == hashTable.wordCount - 1 ? 0 : input + 1) - let actual = hashTable.word(after: input) - expectEqual(actual, expected) - } - } - } - } - func test_word_before() { - withEvery("scale", in: [5, 6, 12]) { scale in - let storage = _HashTableStorage.create(scale: scale) - storage.read { hashTable in - withEvery("input", in: 0 ..< hashTable.wordCount) { input in - let expected = (input == 0 ? hashTable.wordCount - 1 : input - 1) - let actual = hashTable.word(before: input) - expectEqual(actual, expected) - } - } - } - } - func test_coordinates_for_bucket() { - withEvery("scale", in: [5, 6, 12]) { scale in - let storage = _HashTableStorage.create(scale: scale) - storage.read { hashTable in - withEvery("offset", in: 0 ..< hashTable.bucketCount) { offset in - let (word, bit) = hashTable.position(of: _Bucket(offset: offset)) - expectGreaterThanOrEqual(bit, 0) - expectGreaterThanOrEqual(word, 0) - expectLessThan(bit, 64) - expectLessThan(word, hashTable.wordCount) - let pos = 64 * word + bit - expectEqual(pos % scale, 0) - expectEqual(pos / scale, offset) - } - } - } - } - - func test_bucketContents_forValue() { - withEvery("scale", in: [5, 6, 12]) { scale in - let storage = _HashTableStorage.create(scale: scale) - storage.read { hashTable in - expectEqual(hashTable._bucketContents(for: nil), 0) - expectEqual(hashTable._value(forBucketContents: 0), nil) - withEvery("value", in: 0 ..< hashTable.bucketCount - 1) { value in - let contents = hashTable._bucketContents(for: value) - expectEqual(hashTable._value(forBucketContents: contents), value) - } - } - } - } - - func test_subscript_by_bucket() { - withEvery("scale", in: [5, 6, 12]) { scale in - let storage = _HashTableStorage.create(scale: scale) - let bucketCount = 1 << scale - let contents: [Int?] = Array(0 ..< bucketCount - 1) + [nil] - storage.update { hashTable in - for offset in 0 ..< bucketCount { - let bucket = _Bucket(offset: offset) - hashTable[bucket] = contents[offset] - } - } - storage.read { hashTable in - withEvery("offset", in: 0 ..< bucketCount) { offset in - let bucket = _Bucket(offset: offset) - expectEqual(hashTable[bucket], contents[offset]) - } - } - } - } - - /// Create hash table storage of scale `scale`, filled with equal-sized lookup chains - /// of length `chainLength`, separated by holes of length `holeLength`, with the - /// first chain starting at `startOffset`. The chains contain bucket values that - /// sequentially count up from 0. - func sampleStorage( - scale: Int, - chainLength: Int, - holeLength: Int, - startingAt startOffset: Int - ) -> (storage: _HashTableStorage, contents: [Int?]) { - let bucketCount = 1 << scale - - var contents: [Int?] = [] - contents.reserveCapacity(bucketCount + chainLength + holeLength) - contents.append(contentsOf: repeatElement(nil, count: startOffset)) - var i = 0 - while contents.count < bucketCount { - contents.append(contentsOf: (i ..< i + chainLength).map { $0 }) - i += chainLength - contents.append(contentsOf: repeatElement(nil, count: holeLength)) - } - contents.removeLast(contents.count - bucketCount) - - let storage = _HashTableStorage.create(scale: scale) - storage.update { hashTable in - for offset in 0 ..< bucketCount { - let bucket = _Bucket(offset: offset) - hashTable[bucket] = contents[offset] - } - } - return (storage, contents) - } - - /// Call `body` with a hash table of scale `scale`, filled with equal-sized lookup chains - /// of length `chainLength`, separated by holes of length `holeLength`, with the - /// first chain starting at `startOffset`. The chains contain bucket values that - /// sequentially count up from 0. - func withSampleHashTable( - scale: Int, - chainLength: Int, - holeLength: Int, - startingAt startOffset: Int, - body: (_UnsafeHashTable, [Int?]) throws -> R - ) rethrows -> R { - let (storage, contents) = sampleStorage( - scale: scale, - chainLength: chainLength, - holeLength: holeLength, - startingAt: startOffset) - return try storage.update { hashTable in - try body(hashTable, contents) - } - } - - /// Create hash table storage of scale `scale`, filled with a single huge lookup chain - /// of buckets counting sequentially up starting at 0, terminating with the penultimate - /// bucket. The last bucket remains unoccupied. - /// - /// This is useful for testing all possible bucket values. - func sampleStorage(scale: Int) -> (storage: _HashTableStorage, contents: [Int?]) { - sampleStorage(scale: scale, chainLength: (1 << scale) - 1, holeLength: 1, startingAt: 0) - } - - /// Call `body` with a hash table of scale `scale`, filled with a single huge lookup chain - /// of buckets counting sequentially up starting at 0, terminating with the penultimate - /// bucket. The last bucket remains unoccupied. - /// - /// This is useful for testing all possible bucket values. - func withSampleHashTable( - scale: Int, - body: (_UnsafeHashTable, [Int?]) throws -> R - ) rethrows -> R { - let (storage, contents) = sampleStorage(scale: scale) - return try storage.update { hashTable in - try body(hashTable, contents) - } - } - - func test_bucketIterator_read() { - withEvery("scale", in: [5, 6, 7, 8, 12]) { scale in - withSampleHashTable(scale: scale) { hashTable, contents in - // Start an iterator at the first bucket and cycle through - // all buckets twice, checking the values we see at every step. - let bucket = _Bucket(offset: 0) - var it = hashTable.bucketIterator(startingAt: bucket) - expectEqual(it.currentBucket, bucket) - expectEqual(it.isOccupied, contents[bucket.offset] != nil) - expectEqual(it.currentValue, contents[bucket.offset]) - withEvery("iteration", in: 0 ..< 2) { _ in - withEvery("offset", in: 0 ..< hashTable.bucketCount) { offset in - let expected = contents[offset] - expectEqual(it.currentBucket, _Bucket(offset: offset)) - expectEqual(it.isOccupied, expected != nil) - expectEqual(it.currentValue, expected) - it.advance() - } - } - } - } - } - - func test_bucketIterator_read_with_holes() { - withEvery("scale", in: [5, 6, 7, 8, 12]) { scale in - withEvery("chainLength", in: [1, 2, 3, 4]) { chainLength in - withEvery("holeLength", in: [1, 2, 3]) { holeLength in - withEvery("startOffset", in: 0 ... chainLength) { startOffset in - withSampleHashTable( - scale: scale, - chainLength: chainLength, - holeLength: holeLength, - startingAt: startOffset - ) { hashTable, contents in - // Start an iterator at the first bucket and cycle through - // all buckets twice, checking the values we see at every step. - let bucket = _Bucket(offset: 0) - var it = hashTable.bucketIterator(startingAt: bucket) - expectEqual(it.currentBucket, bucket) - expectEqual(it.isOccupied, contents[bucket.offset] != nil) - expectEqual(it.currentValue, contents[bucket.offset]) - withEvery("iteration", in: 0 ..< 2) { _ in - withEvery("offset", in: 0 ..< hashTable.bucketCount) { offset in - let expected = contents[offset] - expectEqual(it.currentBucket, _Bucket(offset: offset)) - expectEqual(it.isOccupied, expected != nil) - expectEqual(it.currentValue, expected) - it.advance() - } - } - } - } - } - } - } - } - - func test_bucketIterator_start_in_middle() { - withEvery("scale", in: [5, 6, 7, 8, 12]) { scale in - withSampleHashTable(scale: scale) { hashTable, contents in - var expected = hashTable.bucketIterator(startingAt: _Bucket(offset: 0)) - // Start a new iterator at every bucket and check that its initial - // state is match exactly what we'd get by starting at the first - // bucket and advancing step by step to the same position. - withEvery("start", in: 0 ..< hashTable.bucketCount) { start in - let bucket = _Bucket(offset: start) - let actual = hashTable.bucketIterator(startingAt: bucket) - - expectEqual(expected.currentBucket, bucket) - expectEqual(expected.currentValue, contents[start]) - - expectEqual(actual.currentBucket, bucket) - expectEqual(actual.currentValue, contents[start]) - - expectEqual(actual._currentBucket, expected._currentBucket) - expectEqual(actual._currentRawValue, expected._currentRawValue) - expectEqual(actual._nextBits, expected._nextBits) - expectEqual(actual._remainingBitCount, expected._remainingBitCount) - - expected.advance() - } - } - } - } - - func test_bucketIterator_start_in_middle_with_holes() { - withEvery("scale", in: [5, 6, 7, 8, 12]) { scale in - withEvery("chainLength", in: [1, 2, 3, 4]) { chainLength in - withEvery("holeLength", in: [1, 2, 3]) { holeLength in - withEvery("startOffset", in: 0 ... chainLength) { startOffset in - withSampleHashTable( - scale: scale, - chainLength: chainLength, - holeLength: holeLength, - startingAt: startOffset - ) { hashTable, contents in - var expected = hashTable.bucketIterator(startingAt: _Bucket(offset: 0)) - // Start a new iterator at every bucket and check that its initial - // state is match exactly what we'd get by starting at the first - // bucket and advancing step by step to the same position. - withEvery("start", in: 0 ..< hashTable.bucketCount) { start in - let bucket = _Bucket(offset: start) - let actual = hashTable.bucketIterator(startingAt: bucket) - - expectEqual(expected.currentBucket, bucket) - expectEqual(expected.currentValue, contents[start]) - - expectEqual(actual.currentBucket, bucket) - expectEqual(actual.currentValue, contents[start]) - - expectEqual(actual._currentBucket, expected._currentBucket) - expectEqual(actual._currentRawValue, expected._currentRawValue) - expectEqual(actual._nextBits, expected._nextBits) - expectEqual(actual._remainingBitCount, expected._remainingBitCount) - - expected.advance() - } - } - } - } - } - } - } - - func test_bucketIterator_advance_until() { - withEvery("scale", in: [5, 6, 7, 8, 12]) { scale in - withEvery("chainLength", in: [1, 2, 3, 4]) { chainLength in - withEvery("holeLength", in: [1, 2, 3]) { holeLength in - withEvery("startOffset", in: 0 ... chainLength) { startOffset in - withSampleHashTable( - scale: scale, - chainLength: chainLength, - holeLength: holeLength, - startingAt: startOffset - ) { hashTable, contents in - var offset = 0 - var it = hashTable.bucketIterator(startingAt: _Bucket(offset: offset)) - let step = 2 - - for _ in 0 ..< hashTable.bucketCount { - if let value = contents[offset] { - // `advance(until:)` should not move if we're already on the right value. - it.advance(until: value) - expectEqual(it.currentBucket.offset, offset) - - // `advance(until:)` should stop when it find the value we're looking for, - // or at the next hole, whichever comes first. - it.advance(until: value + step) - expectTrue(it.currentValue == nil || it.currentValue == value + step) - var o = offset - while true { - o += 1 - if o == contents.count { o = 0 } - if o == it.currentBucket.offset { break } - expectNotNil(contents[o]) - } - offset = o - } else { - // `advance(until:)` should not move if we're on a hole. - it.advance(until: 0) - expectEqual(it.currentBucket.offset, offset) - - // Move to the next bucket. - offset += 1 - if offset == contents.count { offset = 0 } - it.advance() - } - } - } - } - } - } - } - } - - func test_bucketIterator_advance_toNextUnoccupiedBucket() { - withEvery("scale", in: [5, 6, 7, 8, 12]) { scale in - withEvery("chainLength", in: [1, 2, 3, 4]) { chainLength in - withEvery("holeLength", in: [1, 2, 3]) { holeLength in - withEvery("startOffset", in: 0 ... chainLength) { startOffset in - withSampleHashTable( - scale: scale, - chainLength: chainLength, - holeLength: holeLength, - startingAt: startOffset - ) { hashTable, contents in - var offset = 0 - var it = hashTable.bucketIterator(startingAt: _Bucket(offset: offset)) - - for _ in 0 ..< hashTable.bucketCount { - if contents[offset] != nil { - it.advanceToNextUnoccupiedBucket() - - expectNil(it.currentValue) - - while contents[offset] != nil { - offset += 1 - if offset == contents.count { offset = 0 } - } - expectEqual(it.currentBucket.offset, offset) - } else { - // `advanceToNextUnoccupiedBucket()` should not move if we're already on a hole. - it.advanceToNextUnoccupiedBucket() - expectEqual(it.currentBucket.offset, offset) - - // Move to the next bucket. - offset += 1 - if offset == contents.count { offset = 0 } - it.advance() - } - } - } - } - } - } - } - } - - func test_bucketIterator_write() { - withEvery("scale", in: [5, 6, 7, 8, 12]) { scale in - withSampleHashTable(scale: scale) { hashTable, contents in - let storage = _HashTableStorage.create(scale: scale) - let bucketCount = 1 << scale - let contents: [Int?] = Array(0 ..< bucketCount - 1) + [nil] - storage.update { hashTable in - // Start an iterator at the first bucket and cycle through - // all buckets, updating values at every step. - let bucket = _Bucket(offset: 0) - var it = hashTable.bucketIterator(startingAt: bucket) - withEvery("writeOffset", in: 0 ..< contents.count) { writeOffset in - it.currentValue = contents[writeOffset] - it.advance() - } - // Cycle through one more time, verifying that contents match. - withEvery("readOffset", in: 0 ..< contents.count) { readOffset in - expectEqual(it.currentValue, contents[readOffset]) - it.advance() - } - } - } - } - } - - func test_Storage_copy() { - withEvery("scale", in: [5, 6, 7, 8, 12]) { scale in - let (s1, contents) = sampleStorage(scale: scale) - let s2 = s1.copy() - s1.read { original in - s2.read { copy in - expectEqual(copy.scale, original.scale) - expectEqual(copy.reservedScale, original.reservedScale) - expectEqual(copy.seed, original.seed) - var it = copy.bucketIterator(startingAt: _Bucket(offset: 0)) - withEvery("offset", in: 0 ..< contents.count) { offset in - expectEqual(it.currentValue, contents[offset]) - it.advance() - } - } - } - } - } - - func test_bias() { - withEvery("scale", in: [5, 6, 7, 8, 12]) { scale in - let (storage, contents) = sampleStorage(scale: scale) - withEvery("bias", in: [0, 1, -1, 2, -2, 30, -30]) { bias in - storage.update { hashTable in hashTable.bias = bias } - storage.read { hashTable in - var it = hashTable.bucketIterator(startingAt: _Bucket(offset: 0)) - repeat { - if let v = contents[it.currentBucket.offset] { - let m = hashTable.bucketCount - 1 - var expected = (v + bias) % m - if expected < 0 { expected += m } - expectEqual(it.currentValue, expected) - } else { - expectNil(it.currentValue) - } - it.advance() - } while it.currentBucket.offset != 0 - } - } - } - } - - func test_rawSubscript() { - withEvery("scale", in: [5, 6, 7, 8, 12]) { scale in - let (storage, contents) = sampleStorage(scale: scale) - storage.read { hashTable in - var bucket = _Bucket(offset: 0) - repeat { - let expected = hashTable._bucketContents(for: contents[bucket.offset]) - expectEqual(hashTable[raw: bucket], expected) - bucket = hashTable.bucket(after: bucket) - } while bucket.offset != 0 - } - } - } - - func test_isOccupied() { - withEvery("scale", in: [5, 6, 7, 8, 12]) { scale in - let (storage, contents) = sampleStorage(scale: scale) - storage.read { hashTable in - var bucket = _Bucket(offset: 0) - repeat { - expectEqual(hashTable.isOccupied(bucket), contents[bucket.offset] != nil) - bucket = hashTable.bucket(after: bucket) - } while bucket.offset != 0 - } - } - } - -} - -#endif diff --git a/Tests/UniquedTests/RandomAccessCollection+Offsets.swift b/Tests/UniquedTests/RandomAccessCollection+Offsets.swift deleted file mode 100644 index 79db7ede..00000000 --- a/Tests/UniquedTests/RandomAccessCollection+Offsets.swift +++ /dev/null @@ -1,61 +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 -// -//===----------------------------------------------------------------------===// - -extension RandomAccessCollection { - @inline(__always) - internal func _index(at offset: Int) -> Index { - index(startIndex, offsetBy: offset) - } - - @inline(__always) - internal func _offset(of index: Index) -> Int { - distance(from: startIndex, to: index) - } - - @inline(__always) - internal func _indexRange(at offsets: Range) -> Range { - _index(at: offsets.lowerBound) ..< _index(at: offsets.upperBound) - } - - @inline(__always) - internal func _indexRange(at offsets: R) -> Range - where R.Bound == Int { - return _indexRange(at: offsets.relative(to: 0 ..< self.count)) - } - - @inline(__always) - internal func _offsetRange(of range: Range) -> Range { - _offset(of: range.lowerBound) ..< _offset(of: range.upperBound) - } - - @inline(__always) - internal func _offsetRange(of range: R) -> Range - where R.Bound == Index { - return _offsetRange(of: range.relative(to: self)) - } - - @inline(__always) - internal subscript(_offset offset: Int) -> Element { - self[_index(at: offset)] - } - - @inline(__always) - internal subscript(_offsets range: Range) -> SubSequence { - self[_indexRange(at: range)] - } - - @inline(__always) - internal subscript(_offsets range: R) -> SubSequence - where R.Bound == Int { - self[_offsets: range.relative(to: 0 ..< count)] - } -} - diff --git a/Tests/UniquedTests/Uniqued.UnorderedView Tests.swift b/Tests/UniquedTests/Uniqued.UnorderedView Tests.swift deleted file mode 100644 index 69a13c25..00000000 --- a/Tests/UniquedTests/Uniqued.UnorderedView Tests.swift +++ /dev/null @@ -1,82 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift Collections open source project -// -// Copyright (c) 2021 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// -//===----------------------------------------------------------------------===// - -import XCTest -@_spi(Testing) import UniquedModule -import CollectionsTestSupport - -class UniquedUnorderedViewTests: CollectionTestCase { - typealias MinimalImmutableBase = MinimalRandomAccessCollection - typealias MinimalBase = MinimalRangeReplaceableRandomAccessCollection - typealias MinimalMutableBase = MinimalMutableRangeReplaceableRandomAccessCollection - - func test_unordered_insert() { - withEvery("count", in: 0 ..< 20) { count in - withEvery("dupes", in: 1 ... 3) { dupes in - withLifetimeTracking { tracker in - let input = (0 ..< dupes * count) - .map { tracker.instance(for: $0 / dupes) } - .shuffled() - let reference: [Int: LifetimeTracked] = - .init(input.lazy.map { ($0.payload, $0) }, - uniquingKeysWith: { a, b in a }) - var set = Uniqued>>() - withEvery("offset", in: input.indices) { offset in - let item = input[offset] - let ref = reference[item.payload] - let (inserted, member) = set.unordered.insert(item) - expectEqual(inserted, ref === item) - expectEqual(member, item) - expectIdentical(member, ref) - expectTrue(set.contains(item)) - } - } - } - } - // Check CoW copying behavior - do { - var set = Uniqued>(0 ..< 30) - let copy = set - expectTrue(set.unordered.insert(30).inserted) - expectTrue(set.contains(30)) - expectFalse(copy.contains(30)) - } - } - - func test_unordered_update() { - withEvery("count", in: 0 ..< 20) { count in - withEvery("dupes", in: 1 ... 3) { dupes in - withLifetimeTracking { tracker in - let input = (0 ..< dupes * count) - .map { tracker.instance(for: $0 / dupes) } - .shuffled() - var reference: [Int: LifetimeTracked] = [:] - var set = Uniqued>>() - withEvery("offset", in: input.indices) { offset in - let item = input[offset] - let old = set.unordered.update(with: item) - expectIdentical(old, reference[item.payload]) - reference[item.payload] = item - expectTrue(set.contains(item)) - } - } - } - } - // Check CoW copying behavior - do { - var set = Uniqued>(0 ..< 30) - let copy = set - expectNil(set.unordered.update(with: 30)) - expectTrue(set.contains(30)) - expectFalse(copy.contains(30)) - } - } -} diff --git a/Tests/UniquedTests/UniquedInternals.swift b/Tests/UniquedTests/UniquedInternals.swift deleted file mode 100644 index 531c17d6..00000000 --- a/Tests/UniquedTests/UniquedInternals.swift +++ /dev/null @@ -1,81 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift Collections open source project -// -// Copyright (c) 2021 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// -//===----------------------------------------------------------------------===// - -import CollectionsTestSupport -@_spi(Testing) import UniquedModule - -struct UniquedLayout: Hashable, CustomStringConvertible { - let scale: Int - let bias: Int - let count: Int - - var description: String { - "UniquedLayout(scale: \(scale), bias: \(bias), count: \(count))" - } -} - -func withUniquedLayouts( - scales: [Int], - file: StaticString = #file, - line: UInt = #line, - run body: (UniquedLayout) throws -> Void -) rethrows { - for scale in scales { - for count in _interestingCounts(forScale: scale) { - for bias in _interestingBiases(forScale: scale) { - let layout = UniquedLayout(scale: scale, bias: bias, count: count) - let entry = TestContext.current.push("layout: \(layout)") - defer { TestContext.current.pop(entry) } - try body(layout) - } - } - } -} - -func _interestingCounts(forScale scale: Int) -> [Int] { - precondition(scale == 0 || scale >= _UnsafeHashTable.minimumScale) - let min = _UnsafeHashTable.minimumCapacity(forScale: scale) - let max = _UnsafeHashTable.maximumCapacity(forScale: scale) - return [min, min + (max - min) / 2, max] -} - -func _interestingBiases(forScale scale: Int) -> [Int] { - // If we have no hash table, we can only use a bias of 0. - if scale < _UnsafeHashTable.minimumScale { return [0] } - let range = _UnsafeHashTable.biasRange(scale: scale) - // For the minimum scale, try all biases. - if scale == _UnsafeHashTable.minimumScale { return Array(range) } - // Otherwise try 3 biases each from the start, middle, and end of range. - var result: [Int] = [] - result += range.prefix(3) - result += range.prefix(range.count / 2 + 1).suffix(3) - result += range.suffix(3) - return result -} - -extension Uniqued { - init(layout: UniquedLayout, contents: Base) { - self.init(_scale: layout.scale, bias: layout.bias, contents: contents) - } -} - -extension Uniqued where Base: RangeReplaceableCollection { - init(layout: UniquedLayout, contents: C) - where C.Element == Element { - self.init(_scale: layout.scale, bias: layout.bias, contents: contents) - } -} - -extension Uniqued where Element == Int, Base: RangeReplaceableCollection { - init(layout: UniquedLayout) { - self.init(layout: layout, contents: 0 ..< layout.count) - } -} diff --git a/Tests/UniquedTests/UniquedTests.swift b/Tests/UniquedTests/UniquedTests.swift deleted file mode 100644 index 918ca741..00000000 --- a/Tests/UniquedTests/UniquedTests.swift +++ /dev/null @@ -1,1487 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift Collections open source project -// -// Copyright (c) 2021 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// -//===----------------------------------------------------------------------===// - -import XCTest -@_spi(Testing) import UniquedModule -import DequeModule -import CollectionsTestSupport - -class UniquedTests: CollectionTestCase { - typealias MinimalImmutableBase = MinimalRandomAccessCollection - typealias MinimalBase = MinimalRangeReplaceableRandomAccessCollection - typealias MinimalMutableBase = MinimalMutableRangeReplaceableRandomAccessCollection - - func test_init_uncheckedUniqueElements_concrete() { - withEvery("count", in: 0 ..< 20) { count in - let contents = MinimalImmutableBase(0 ..< count) - let set = Uniqued(uncheckedUniqueElements: contents) - expectEqual(set.count, count) - expectEqual(set.isEmpty, count == 0) - expectEqualElements(set, 0 ..< count) - for i in 0 ..< count { - expectTrue(set.contains(i)) - } - } - } - - func test_init_uncheckedUniqueElements_generic() { - withEvery("count", in: 0 ..< 20) { count in - let set = Uniqued>(uncheckedUniqueElements: 0 ..< count) - expectEqual(set.count, count) - expectEqual(set.isEmpty, count == 0) - expectEqualElements(set, 0 ..< count) - for i in 0 ..< count { - expectTrue(set.contains(i)) - } - } - } - - func test_init_uniqueElements_concrete() { - withEvery("count", in: 0 ..< 20) { count in - let contents = MinimalImmutableBase(0 ..< count) - let set = Uniqued(uniqueElements: contents) - expectEqual(set.count, count) - expectEqual(set.isEmpty, count == 0) - expectEqualElements(set, 0 ..< count) - for i in 0 ..< count { - expectTrue(set.contains(i)) - } - } - } - - func test_init_uniqueElements_generic() { - withEvery("count", in: 0 ..< 20) { count in - let set = Uniqued>(uniqueElements: 0 ..< count) - expectEqual(set.count, count) - expectEqual(set.isEmpty, count == 0) - expectEqualElements(set, 0 ..< count) - for i in 0 ..< count { - expectTrue(set.contains(i)) - } - } - } - - func test_init_empty() { - let set = Uniqued>() - expectEqual(set.count, 0) - expectTrue(set.isEmpty) - expectEqualElements(set, []) - } - - func test_init_self() { - withEvery("count", in: 0 ..< 20) { count in - let set = Uniqued>(0 ..< count) - let copy = Uniqued(set) - expectEqualElements(copy, set) - expectEqual(set._hashTableIdentity, copy._hashTableIdentity) - } - } - - func test_init_set() { - withEvery("count", in: 0 ..< 20) { count in - let set = Set(0 ..< count) - let ordered = Uniqued>(set) - expectEqual(ordered.count, count) - expectEqualElements(ordered, set) - } - } - - func test_init_dictionary_keys() { - withEvery("count", in: 0 ..< 20) { count in - let dict: [Int: Int] - = .init(uniqueKeysWithValues: (0 ..< count).lazy.map { (key: $0, value: 2 * $0) }) - let ordered = Uniqued>(dict.keys) - expectEqual(ordered.count, count) - expectEqualElements(ordered, dict.keys) - } - } - - /// Create a new `Uniqued` instance using the generic initializer. - static func _genericInitializer( - _ type: T.Type = T.self, - from elements: S - ) -> Uniqued - where T: RandomAccessCollection & RangeReplaceableCollection, - T.Element == S.Element - { - return Uniqued.init(elements) - } - - - func test_generic_init_self() { - withEvery("count", in: 0 ..< 20) { count in - let set = Uniqued>(0 ..< count) - let copy: Uniqued> = Self._genericInitializer(from: set) - expectEqualElements(copy, set) - expectEqual(set._hashTableIdentity, copy._hashTableIdentity) - } - } - - func test_generic_init_set() { - withEvery("count", in: 0 ..< 20) { count in - let expected = Set(0 ..< count) - let actual = Self._genericInitializer(MinimalBase.self, from: expected) - expectEqualElements(actual, expected) - } - } - - func test_generic_init_array() { - withEvery("count", in: 0 ..< 20) { count in - let expected = Array(0 ..< count) - withEvery("dupes", in: 1 ... 3) { dupes in - let input = (0 ..< count).flatMap { repeatElement($0, count: dupes) } - let actual = Self._genericInitializer(MinimalBase.self, from: input) - expectEqualElements(actual, expected) - } - } - } - - func test_firstIndexOf_lastIndexOf() { - withEvery("count", in: 0 ..< 20) { count in - let contents = Array(0 ..< count) - withEvery("dupes", in: 1 ... 3) { dupes in - let input = (0 ..< count).flatMap { repeatElement($0, count: dupes) } - let set = Uniqued<[Int]>(input) - withEvery("item", in: contents) { item in - expectNotNil(set.firstIndex(of: item)) { index in - expectEqual(set[index], item) - expectEqual(contents[index], item) - expectEqual(set.lastIndex(of: item), index) - } - } - expectNil(set.firstIndex(of: count)) - expectNil(set.lastIndex(of: count)) - } - } - } - - func test_Collection() { - withEvery("count", in: [0, 1, 15, 16, 20]) { count in - let scale = _UnsafeHashTable.scale(forCapacity: count) - withEvery("bias", in: _UnsafeHashTable.biasRange(scale: scale)) { bias in - let contents = Array(0 ..< count) - let set = Uniqued<[Int]>(_scale: scale, bias: bias, contents: contents) - checkBidirectionalCollection(set, expectedContents: contents) - } - } - } - - func test_CustomStringConvertible() { - let a: Uniqued> = [] - expectEqual(a.description, "[]") - - let b: Uniqued> = [0] - expectEqual(b.description, "[0]") - - let c: Uniqued> = [0, 1, 2, 3, 4] - expectEqual(c.description, "[0, 1, 2, 3, 4]") - } - - func test_CustomDebugStringConvertible() { - let a: Uniqued> = [] - expectEqual(a.debugDescription, "OrderedSet([])") - - let b: Uniqued> = [0] - expectEqual(b.debugDescription, "OrderedSet([0])") - - let c: Uniqued> = [0, 1, 2, 3, 4] - expectEqual(c.debugDescription, "OrderedSet([0, 1, 2, 3, 4])") - - let d: Uniqued> = [] - expectEqual(d.debugDescription, "Uniqued>([])") - - let e: Uniqued> = [0] - expectEqual(e.debugDescription, "Uniqued>([0])") - - let f: Uniqued> = [0, 1, 2, 3, 4] - expectEqual(f.debugDescription, "Uniqued>([0, 1, 2, 3, 4])") - } - - func test_customReflectable() { - do { - let set: Uniqued<[Int]> = [1, 2, 3] - let mirror = Mirror(reflecting: set) - expectEqual(mirror.displayStyle, .collection) - expectNil(mirror.superclassMirror) - expectTrue(mirror.children.compactMap { $0.label }.isEmpty) // No label - expectEqualElements(mirror.children.map { $0.value as? Int }, set.map { $0 }) - } - - do { - let set: Uniqued> = [1, 2, 3] - let mirror = Mirror(reflecting: set) - expectEqual(mirror.displayStyle, .collection) - expectNil(mirror.superclassMirror) - expectTrue(mirror.children.compactMap { $0.label }.isEmpty) // No label - expectEqualElements(mirror.children.map { $0.value as? Int }, set.map { $0 }) - } - } - - func test_Equatable_Hashable() { - let samples: [[Uniqued<[Int]>]] = [ - [[1, 2, 3], - [1, 2, 3]], - [[3, 2, 1], - [3, 2, 1]], - [[1, 1, 1], - [1, 1, 1], - [1, 1], - [1]], - [[1, 2], - [1, 2, 2], - [1, 1, 2], - [1, 1, 2, 2]], - ] - checkHashable(equivalenceClasses: samples) - - // Check that hash encoding matches that of the underlying arrays. - for equivalenceClass in samples { - for item in equivalenceClass { - expectEqual(item.hashValue, item.contents.hashValue) - } - } - } - - func test_ExpressibleByArrayLiteral() { - do { - let set: Uniqued<[Int]> = [] - expectEqualElements(set, [] as [Int]) - } - - do { - let set: Uniqued<[Int]> = [1, 2, 3] - expectEqualElements(set, 1 ... 3) - } - - do { - let set: Uniqued<[Int]> = [ - 1, 2, 3, 4, 5, 6, 7, 8, - 1, 2, 3, 4, 5, 6, 7, 8, - 1, 2, 3, 4, 5, 6, 7, 8, - 1, 2, 3, 4, 5, 6, 7, 8, - ] - expectEqualElements(set, 1 ... 8) - } - - do { - let set: Uniqued<[Int]> = [ - 1, 1, 1, 1, - 2, 2, 2, 2, - 3, 3, 3, 3, - 4, 4, 4, 4, - 5, 5, 5, 5, - 6, 6, 6, 6, - 7, 7, 7, 7, - 8, 8, 8, 8, - ] - expectEqualElements(set, 1 ... 8) - } - - do { - let set: Uniqued<[Int]> = [ - 1, 2, 3, 4, 5, 6, 7, 8, - 9, 10, 11, 12, 13, 14, 15, 16, - 17, 18, 19, 20, 21, 22, 23, 24, - 25, 26, 27, 28, 29, 30, 31, 32] - expectEqualElements(set, 1 ... 32) - } - } - - func test_Encodable() throws { - let s1: Uniqued<[Int]> = [] - let v1: MinimalEncoder.Value = .array([]) - expectEqual(try MinimalEncoder.encode(s1), v1) - - let s2: Uniqued<[Int]> = [0, 1, 2, 3] - let v2: MinimalEncoder.Value = .array([.int(0), .int(1), .int(2), .int(3)]) - expectEqual(try MinimalEncoder.encode(s2), v2) - - let s3: Uniqued<[Int]> = [3, 2, 1, 0] - let v3: MinimalEncoder.Value = .array([.int(3), .int(2), .int(1), .int(0)]) - expectEqual(try MinimalEncoder.encode(s3), v3) - - let s4 = Uniqued<[Int]>(0 ..< 100) - let v4: MinimalEncoder.Value = .array((0 ..< 100).map { .int($0) }) - expectEqual(try MinimalEncoder.encode(s4), v4) - } - - func test_Decodable() throws { - let s1: Uniqued<[Int]> = [] - let v1: MinimalEncoder.Value = .array([]) - expectEqual(try MinimalDecoder.decode(v1, as: Uniqued<[Int]>.self), s1) - - let s2: Uniqued<[Int]> = [0, 1, 2, 3] - let v2: MinimalEncoder.Value = .array([.int(0), .int(1), .int(2), .int(3)]) - expectEqual(try MinimalDecoder.decode(v2, as: Uniqued<[Int]>.self), s2) - - let s3 = Uniqued<[Int]>(0 ..< 100) - let v3: MinimalEncoder.Value = .array((0 ..< 100).map { .int($0) }) - expectEqual(try MinimalDecoder.decode(v3, as: Uniqued<[Int]>.self), s3) - - expectThrows(try MinimalDecoder.decode(.int(0), as: Uniqued<[Int]>.self)) - - let v4: MinimalEncoder.Value = .array([.int(0), .int(1), .int(0)]) - expectThrows(try MinimalDecoder.decode(v4, as: Uniqued<[Int]>.self)) { error in - expectNotNil(error as? DecodingError) { error in - guard case .dataCorrupted(let context) = error else { - expectFailure("Unexpected error \(error)") - return - } - expectEqual(context.debugDescription, - "Decoded elements aren't unique (first duplicate at offset 2)") - } - } - } - - func test_append_many() { - #if COLLECTIONS_INTERNAL_CHECKS - // This test just takes too long with O(n) appends. - let count = 1_000 - #else - let count = 10_000 - #endif - - var set = Uniqued>() - withEvery("item", in: 0 ..< count) { item in - let res1 = set.append(item) - expectTrue(res1.inserted) - expectEqual(set[res1.index], item) - - let res2 = set.append(item) - expectFalse(res2.inserted) - expectEqual(res2.index, res1.index) - - expectEqual(set[res1.index], item) // Original index must remain valid. - expectEqual(set[res2.index], item) - } - } - - func test_append() { - withEvery("count", in: 0 ..< 20) { count in - withEvery("dupes", in: 1 ... 3) { dupes in - let input = (0 ..< count).flatMap { repeatElement($0, count: dupes) }.shuffled() - var reference: [Int: Int] = [:] // Value to expected offset - var actual = Uniqued>() - withEvery("offset", in: input.indices) { offset in - let item = input[offset] - let (inserted, index) = actual.append(item) - expectEqual(actual[index], item) - if let expectedOffset = reference[item] { - // Existing item - expectFalse(inserted) - expectEqual(index.offset, expectedOffset) - } else { - expectTrue(inserted) - expectEqual(index.offset, reference.count) - reference[item] = reference.count - } - } - } - } - // Check CoW copying behavior - do { - var set = Uniqued>(0 ..< 30) - let copy = set - expectTrue(set.append(30).inserted) - expectTrue(set.contains(30)) - expectFalse(copy.contains(30)) - } - } - - func test_append_contentsOf() { - withEvery("chunkLength", in: 1 ..< 10) { chunkLength in - withEvery("chunkOverlap", in: 0 ... chunkLength) { chunkOverlap in - var actual = Uniqued>() - var chunkStart = 0 - var expectedCount = 0 - withEvery("iteration", in: 0 ..< 100) { _ in - let chunk = chunkStart ..< chunkStart + chunkLength - actual.append(contentsOf: chunk) - expectedCount = chunk.upperBound - expectEqual(actual.count, expectedCount) - chunkStart += chunkLength - chunkOverlap - } - expectEqualElements(actual, 0 ..< expectedCount) - } - } - } - - func test_prepend_many() { - #if COLLECTIONS_INTERNAL_CHECKS - // This test just takes too long with O(n) appends. - let count = 1_000 - #else - let count = 10_000 - #endif - - var set = Uniqued>() - withEvery("item", in: 0 ..< count) { item in - let res1 = set.prepend(item) - expectTrue(res1.inserted) - expectEqual(set[res1.index], item) - - let res2 = set.prepend(item) - expectFalse(res2.inserted) - expectEqual(res2.index, res1.index) - - expectEqual(set[res1.index], item) // Original index must remain valid. - expectEqual(set[res2.index], item) - } - } - - func test_prepend() { - withEvery("count", in: 0 ..< 20) { count in - withEvery("dupes", in: 1 ... 3) { dupes in - let input = (0 ..< count).flatMap { repeatElement($0, count: dupes) }.shuffled() - var reference: [Int: Int] = [:] // Value to expected offset from end - var actual = Uniqued>() - withEvery("offset", in: input.indices) { offset in - let item = input[offset] - let (inserted, index) = actual.prepend(item) - expectEqual(actual[index], item) - if let expectedOffset = reference[item] { - // Existing item - expectFalse(inserted) - expectEqual(index, actual.count - expectedOffset) - } else { - expectTrue(inserted) - expectEqual(index, 0) - reference[item] = actual.count - } - } - } - } - // Check CoW copying behavior - do { - var set = Uniqued>(0 ..< 30) - let copy = set - expectTrue(set.append(30).inserted) - expectTrue(set.contains(30)) - expectFalse(copy.contains(30)) - } - } - - func test_prepend_contentsOf() { - withEvery("chunkLength", in: 1 ..< 10) { chunkLength in - withEvery("chunkOverlap", in: 0 ... chunkLength) { chunkOverlap in - var actual = Uniqued>() - var chunkStart = 0 - var expectedCount = 0 - withEvery("iteration", in: 0 ..< 100) { _ in - let chunk = chunkStart ..< chunkStart + chunkLength - actual.prepend(contentsOf: chunk.reversed()) - expectedCount = chunk.upperBound - expectEqual(actual.count, expectedCount) - chunkStart += chunkLength - chunkOverlap - } - expectEqualElements(actual, (0 ..< expectedCount).reversed()) - } - } - } - - func test_insert_at() { - func check(_ base: Base.Type) - where Base: RandomAccessCollection & RangeReplaceableCollection, - Base.Element == Int - { - let entry = context.push("base: \(base)") - defer { context.pop(entry) } - withUniquedLayouts(scales: [0, 5, 6]) { layout in - withEvery("isShared", in: [false, true]) { isShared in - let count = layout.count - withEvery("offset", in: 0 ... count) { offset in - var set = Uniqued(layout: layout) - withHiddenCopies(if: isShared, of: &set) { set in - let i = set.index(set.startIndex, offsetBy: offset) - let (inserted, index) = set.insert(count, at: i) - expectTrue(inserted) - expectEqual(set.count, count + 1) - expectEqual(set[index], count) - expectEqualElements(set[...self) - check(ContiguousArray.self) - check(Deque.self) - } - - func test_update_at_with() { - func check(_ base: Base.Type) - where Base: RandomAccessCollection & RangeReplaceableCollection & MutableCollection, - Base.Element == HashableBox - { - let entry = context.push("base: \(base)") - defer { context.pop(entry) } - withUniquedLayouts(scales: [0, 5, 6]) { layout in - let count = layout.count - let contents = Base((0 ..< count).lazy.map { HashableBox($0) }) - withEvery("offset", in: 0 ..< count) { offset in - var set = Uniqued(layout: layout, contents: contents) - let index = set._index(at: offset) // This must remain valid throughout this test - let new = HashableBox(offset) - let old = set.update(at: index, with: new) - expectIdentical(old, contents[index]) - expectIdentical(set[index], new) - - let copy = set - - let old2 = set.update(at: index, with: old) - expectIdentical(old2, new) - expectIdentical(set[index], old) - expectIdentical(copy[index], new) - } - } - } - check(MinimalMutableBase>.self) - check(ContiguousArray>.self) - check(Deque>.self) - } - - func test_updateOrAppend() { - func check(_ base: Base.Type) - where Base: RandomAccessCollection & RangeReplaceableCollection & MutableCollection, - Base.Element == HashableBox - { - let entry = context.push("base: \(base)") - defer { context.pop(entry) } - withUniquedLayouts(scales: [0, 5, 6]) { layout in - let count = layout.count - let contents = Base((0 ..< count).lazy.map { HashableBox($0) }) - withEvery("offset", in: 0 ..< count) { offset in - var set = Uniqued(layout: layout, contents: contents) - let index = set._index(at: offset) // This must remain valid throughout this test - let new = HashableBox(offset) - let old = set.updateOrAppend(new) - expectNotNil(old) { old in - expectIdentical(old, contents[index]) - expectIdentical(set[index], new) - - let copy = set - - let old2 = set.updateOrAppend(old) - expectNotNil(old2) { old2 in - expectIdentical(old2, new) - expectIdentical(set[index], old) - expectIdentical(copy[index], new) - } - } - } - - // Try appending something. - var set = Uniqued(layout: layout, contents: contents) - - let new = HashableBox(count) - do { - expectNil(set.updateOrAppend(new)) - expectTrue(set.contains(new)) - expectIdentical(set.last, new) - } - - let copy = set - let new2 = HashableBox(count + 1) - do { - expectNil(set.updateOrAppend(new2)) - expectTrue(set.contains(new2)) - expectIdentical(set.last, new2) - } - - expectEqual(copy.count, count + 1) - expectIdentical(copy.last, new) - } - } - check(MinimalMutableBase>.self) - check(ContiguousArray>.self) - check(Deque>.self) - } - - - func test_swapAt() { - func check(_ base: Base.Type) - where Base: RandomAccessCollection & RangeReplaceableCollection & MutableCollection, - Base.Element == Int - { - let entry = context.push("base: \(base)") - defer { context.pop(entry) } - withUniquedLayouts(scales: [0, 5, 6]) { layout in - withEvery("isShared", in: [false, true]) { isShared in - let count = layout.count - withEvery("a", in: 0 ..< count) { a in - var set = Uniqued(layout: layout) - withHiddenCopies(if: isShared, of: &set) { set in - let b = count - a - 1 - let ai = set._index(at: a) - let bi = set._index(at: b) - expectEqual(set[ai], a) - expectEqual(set[bi], b) - set.swapAt(ai, bi) - expectEqual(set[ai], b) - expectEqual(set[bi], a) - // Make sure we can still find these elements - expectEqual(set.firstIndex(of: a), bi) - expectEqual(set.firstIndex(of: b), ai) - } - } - } - } - } - check(MinimalMutableBase.self) - check(ContiguousArray.self) - check(Deque.self) - } - - func test_partition() { - func check(_ base: Base.Type) - where Base: RandomAccessCollection & MutableCollection & RangeReplaceableCollection, - Base.Element == Int - { - let entry = context.push("base: \(base)") - defer { context.pop(entry) } - withUniquedLayouts(scales: [0, 5, 6]) { layout in - withEvery("offset", in: 0 ... layout.count) { offset in - withEvery("isShared", in: [false, true]) { isShared in - let count = layout.count - var set = Uniqued(layout: layout) - withHiddenCopies(if: isShared, of: &set) { set in - let pivot = set.partition(by: { $0.isMultiple(of: 2) }) - withEvery("item", in: 0 ..< count) { item in - expectNotNil(set.firstIndex(of: item)) { index in - expectEqual(set[index], item) - if item.isMultiple(of: 2) { - expectGreaterThanOrEqual(index, pivot) - } else { - expectLessThan(index, pivot) - } - } - } - } - } - } - } - } - check(MinimalMutableBase.self) - check(ContiguousArray.self) - check(Deque.self) - } - - func test_partition_extremes() { - func check(_ base: Base.Type) - where Base: RandomAccessCollection & MutableCollection & RangeReplaceableCollection, - Base.Element == Int - { - let entry = context.push("base: \(base)") - defer { context.pop(entry) } - withUniquedLayouts(scales: [0, 5, 6]) { layout in - withEvery("offset", in: 0 ... layout.count) { offset in - withEvery("isShared", in: [false, true]) { isShared in - let count = layout.count - var set = Uniqued(layout: layout) - withHiddenCopies(if: isShared, of: &set) { set in - do { - let pivot = set.partition(by: { _ in false }) - expectEqual(pivot, set.endIndex) - expectEqualElements(set, 0 ..< count) - } - - do { - let pivot = set.partition(by: { _ in true }) - expectEqual(pivot, set.startIndex) - expectEqualElements(set, 0 ..< count) - } - } - } - } - } - } - check(MinimalMutableBase.self) - check(ContiguousArray.self) - check(Deque.self) - } - - func test_sort() { - func check(_ base: Base.Type) - where Base: RandomAccessCollection & MutableCollection & RangeReplaceableCollection, - Base.Element == Int - { - let entry = context.push("base: \(base)") - defer { context.pop(entry) } - withUniquedLayouts(scales: [0, 5, 6]) { layout in - withEvery("seed", in: 0 ..< 10) { seed in - withEvery("isShared", in: [false, true]) { isShared in - let count = layout.count - var rng = RepeatableRandomNumberGenerator(seed: seed) - let contents = (0 ..< count).shuffled(using: &rng) - var set = Uniqued(layout: layout, contents: contents) - withHiddenCopies(if: isShared, of: &set) { set in - set.sort() - expectEqualElements(set, 0 ..< count) - - set.sort(by: >) - expectEqualElements(set, (0 ..< count).reversed()) - } - } - } - } - } - check(MinimalMutableBase.self) - check(ContiguousArray.self) - check(Deque.self) - } - - func test_shuffle() { - func check(_ base: Base.Type) - where Base: RandomAccessCollection & MutableCollection & RangeReplaceableCollection, - Base.Element == Int - { - let entry = context.push("base: \(base)") - defer { context.pop(entry) } - withUniquedLayouts(scales: [0, 5, 6]) { layout in - guard layout.count > 1 else { return } - withEvery("seed", in: 0 ..< 10) { seed in - withEvery("isShared", in: [false, true]) { isShared in - let count = layout.count - var contents = Base(0 ..< count) - var set = Uniqued(layout: layout, contents: 0 ..< count) - withHiddenCopies(if: isShared, of: &set) { set in - var rng1 = RepeatableRandomNumberGenerator(seed: seed) - contents.shuffle(using: &rng1) - - var rng2 = RepeatableRandomNumberGenerator(seed: seed) - set.shuffle(using: &rng2) - - expectEqualElements(set, contents) - - // Check that shuffling with system RNG does permute the elements. - var success = false - for _ in 0 ..< 1000 { - set.shuffle() - if !set.elementsEqual(contents) { - success = true - break - } - } - expectTrue(success) - - } - } - } - } - } - check(MinimalMutableBase.self) - check(ContiguousArray.self) - check(Deque.self) - } - - func test_remove_at() { - func check(_ base: Base.Type) - where Base: RandomAccessCollection & RangeReplaceableCollection, - Base.Element == Int - { - let entry = context.push("base: \(base)") - defer { context.pop(entry) } - withUniquedLayouts(scales: [0, 5, 6]) { layout in - withEvery("offset", in: 0 ..< layout.count) { offset in - withEvery("isShared", in: [false, true]) { isShared in - var set = Uniqued(layout: layout) - withHiddenCopies(if: isShared, of: &set) { set in - let count = layout.count - let index = set._index(at: offset) - let old = set.remove(at: index) - expectEqual(old, offset) - expectEqualElements(set[...self) - check(ContiguousArray.self) - check(Deque.self) - } - - func test_remove_at_capacity_behavior() { - var set = Uniqued>(0 ..< 1000) - while !set.isEmpty { - let originalCount = set.count - context.withTrace("originalCount: \(originalCount)") { - let scale = set._scale - let old = set.remove(at: set.index(before: set.endIndex)) - expectEqual(old, set.count) - if originalCount == _UnsafeHashTable.minimumCapacity(forScale: scale) { - expectLessThan(set._scale, scale) - } else { - expectEqual(set._scale, scale) - } - } - } - } - - - - func test_remove_existing_element() { - func check(_ base: Base.Type) - where Base: RandomAccessCollection & RangeReplaceableCollection, - Base.Element == Int - { - let entry = context.push("base: \(base)") - defer { context.pop(entry) } - withUniquedLayouts(scales: [0, 5, 6]) { layout in - withEvery("item", in: 0 ..< layout.count) { item in - withEvery("isShared", in: [false, true]) { isShared in - var set = Uniqued(layout: layout) - withHiddenCopies(if: isShared, of: &set) { set in - let count = layout.count - let old = set.remove(item) - expectEqual(old, item) - expectEqualElements(set[...self) - check(ContiguousArray.self) - } - - func test_remove_nonexistent_element() { - func check(_ base: Base.Type) - where Base: RandomAccessCollection & RangeReplaceableCollection, - Base.Element == Int - { - let entry = context.push("base: \(base)") - defer { context.pop(entry) } - withUniquedLayouts(scales: [0, 5, 6]) { layout in - withEvery("item", in: layout.count ..< 2 * layout.count) { item in - var set = Uniqued(layout: layout) - let old = set.remove(item) - expectNil(old) - expectEqualElements(set, 0 ..< layout.count) - } - } - } - check(MinimalBase.self) - check(ContiguousArray.self) - } - - func test_remove_subrange() { - func check(_ base: Base.Type) - where Base: RandomAccessCollection & RangeReplaceableCollection, - Base.Element == Int - { - let entry = context.push("base: \(base)") - defer { context.pop(entry) } - withUniquedLayouts(scales: [0, 5, 6]) { layout in - withSomeRanges("offsetRange", in: 0 ..< layout.count) { offsetRange in - withEvery("isShared", in: [false, true]) { isShared in - var set = Uniqued(layout: layout) - let low = offsetRange.lowerBound - let high = offsetRange.upperBound - withHiddenCopies(if: isShared, of: &set) { set in - let count = layout.count - let removedRange = set._indexRange(at: low ..< high) - set.removeSubrange(removedRange) - - expectEqual(set.count, layout.count - offsetRange.count) - - if set.count < _UnsafeHashTable.minimumCapacity(forScale: layout.scale) { - expectLessThan(set._scale, layout.scale) - } - - expectEqualElements(set[_offsets: ..= offsetRange.upperBound { - expectEqual(set.firstIndex(of: i), - set._index(at: i - offsetRange.count)) - } else { - expectNil(set.firstIndex(of: i)) - } - } - } - } - } - } - } - check(MinimalBase.self) - check(ContiguousArray.self) - } - - func test_init_minimumCapacity() { - withEvery("capacity", in: 0 ..< 1000) { capacity in - let expectedScale = _UnsafeHashTable.scale(forCapacity: capacity) - let set = Uniqued>(minimumCapacity: capacity) - expectEqual(set._scale, expectedScale) - expectEqual(set._reservedScale, expectedScale) - expectEqual(set._minimumCapacity, 0) - } - } - - func test_reserveCapacity_empty() { - withEvery("capacity", in: 0 ..< 1000) { capacity in - let expectedScale = _UnsafeHashTable.scale(forCapacity: capacity) - var set = Uniqued>() - expectEqual(set._scale, 0) - expectEqual(set._reservedScale, 0) - expectEqual(set._minimumCapacity, 0) - - set.reserveCapacity(capacity) - expectEqual(set._scale, expectedScale) - expectEqual(set._reservedScale, expectedScale) - expectEqual(set._minimumCapacity, 0) - - set.reserveCapacity(0) - expectEqual(set._scale, 0) - expectEqual(set._reservedScale, 0) - expectEqual(set._minimumCapacity, 0) - } - } - - func test_reserveCapacity_behavior() { - let scale1 = 6 - let range1 = 16 ... 48 - let count1 = 32 - - let scale2 = 8 - let range2 = 64 ... 192 - let count2 = 128 - - var set = Uniqued>(0 ..< count1) - expectEqual(set._scale, scale1) - expectEqual(set._reservedScale, 0) - expectEqual(set._minimumCapacity, range1.lowerBound) - expectEqual(set._capacity, range1.upperBound) - - set.reserveCapacity(count2) - expectEqual(set._scale, scale2) - expectEqual(set._reservedScale, scale2) - expectEqual(set._minimumCapacity, 0) - expectEqual(set._capacity, range2.upperBound) - - set.append(contentsOf: count1 ..< count2) - expectEqual(set._scale, scale2) - expectEqual(set._reservedScale, scale2) - expectEqual(set._minimumCapacity, 0) - expectEqual(set._capacity, range2.upperBound) - - set.reserveCapacity(0) - expectEqual(set._scale, scale2) - expectEqual(set._reservedScale, 0) - expectEqual(set._minimumCapacity, range2.lowerBound) - expectEqual(set._capacity, range2.upperBound) - - set.removeSubrange(set._indexRange(at: count1...)) - expectEqual(set._scale, scale1) - expectEqual(set._reservedScale, 0) - expectEqual(set._minimumCapacity, range1.lowerBound) - expectEqual(set._capacity, range1.upperBound) - } - - func withSampleRanges( - file: StaticString = #file, - line: UInt = #line, - _ body: (Range, Range) throws -> Void - ) rethrows { - for c1 in [0, 10, 32, 64, 128, 256] { - for c2 in [0, 10, 32, 64, 128, 256] { - for overlap in Set([0, 1, c1 / 2, c1, -5]) { - let r1 = 0 ..< c1 - let r2 = c1 - overlap ..< c1 - overlap + c2 - if r1.lowerBound <= r2.lowerBound { - let e1 = context.push("range1: \(r1)", file: file, line: line) - let e2 = context.push("range2: \(r2)", file: file, line: line) - defer { - context.pop(e2) - context.pop(e1) - } - try body(r1, r2) - } else { - let e1 = context.push("range1: \(r2)", file: file, line: line) - let e2 = context.push("range2: \(r1)", file: file, line: line) - defer { - context.pop(e2) - context.pop(e1) - } - try body(r2, r1) - } - } - } - } - } - - func test_union_Self() { - withSampleRanges { r1, r2 in - let expected = Set(r1).union(r2).sorted() - - let u1 = Uniqued>(r1) - let u2 = Uniqued>(r2) - let actual1 = u1.union(u2) - expectEqualElements(actual1, expected) - - let actual2 = actual1.union(u2).union(u1) - expectEqualElements(actual2, expected) - } - } - - func test_formUnion_Self() { - withSampleRanges { r1, r2 in - let expected = Set(r1).union(r2).sorted() - - var res = Uniqued>() - - let u1 = Uniqued>(r1) - res.formUnion(u1) - expectEqualElements(res, r1) - - let u2 = Uniqued>(r2) - res.formUnion(u2) - expectEqualElements(res, expected) - - res.formUnion(u1) - res.formUnion(u2) - expectEqualElements(res, expected) - } - } - - func test_union_generic() { - withSampleRanges { r1, r2 in - let expected = Set(r1).union(r2).sorted() - let u1 = Uniqued>(r1) - let u2 = u1.union(r2) - expectEqualElements(u2, expected) - - let u3 = u2.union(r1) - expectEqualElements(u3, expected) - } - } - - func test_formUnion_generic() { - withSampleRanges { r1, r2 in - let expected = Set(r1).union(r2).sorted() - - var res = Uniqued>() - - res.formUnion(r1) - expectEqualElements(res, r1) - - res.formUnion(r2) - expectEqualElements(res, expected) - - res.formUnion(r1) - res.formUnion(r2) - expectEqualElements(res, expected) - } - } - - func test_intersection_Self() { - withSampleRanges { r1, r2 in - let expected = Set(r1).intersection(r2).sorted() - - let u1 = Uniqued>(r1) - let u2 = Uniqued>(r2) - let actual1 = u1.intersection(u2) - expectEqualElements(actual1, expected) - - let actual2 = actual1.intersection(r1) - expectEqualElements(actual2, expected) - } - } - - func test_formIntersection_Self() { - withSampleRanges { r1, r2 in - let expected = Set(r1).intersection(r2).sorted() - - let u1 = Uniqued>(r1) - let u2 = Uniqued>(r2) - var res = u1 - res.formIntersection(u2) - expectEqualElements(res, expected) - expectEqualElements(u1, r1) - - res.formIntersection(u1) - res.formIntersection(u2) - expectEqualElements(res, expected) - } - } - - func test_intersection_generic() { - withSampleRanges { r1, r2 in - let expected = Set(r1).intersection(r2).sorted() - - let u1 = Uniqued>(r1) - let actual1 = u1.intersection(r2) - expectEqualElements(actual1, expected) - - let actual2 = actual1.intersection(r1).intersection(r2) - expectEqualElements(actual2, expected) - } - } - - func test_formIntersection_generic() { - withSampleRanges { r1, r2 in - let expected = Set(r1).intersection(r2).sorted() - - var res = Uniqued>(r1) - res.formIntersection(r2) - expectEqualElements(res, expected) - - res.formIntersection(r1) - res.formIntersection(r2) - expectEqualElements(res, expected) - } - } - - func test_symmetricDifference_Self() { - withSampleRanges { r1, r2 in - let expected = Set(r1).symmetricDifference(r2).sorted() - - let u1 = Uniqued>(r1) - let u2 = Uniqued>(r2) - let actual1 = u1.symmetricDifference(u2) - expectEqualElements(actual1, expected) - - let actual2 = actual1.symmetricDifference(u1).symmetricDifference(u2) - expectEqual(actual2.count, 0) - } - } - - func test_formSymmetricDifference_Self() { - withSampleRanges { r1, r2 in - let expected = Set(r1).symmetricDifference(r2).sorted() - - let u1 = Uniqued>(r1) - let u2 = Uniqued>(r2) - var res = u1 - res.formSymmetricDifference(u2) - expectEqualElements(res, expected) - expectEqualElements(u1, r1) - - res.formSymmetricDifference(u1) - res.formSymmetricDifference(u2) - expectEqual(res.count, 0) - } - } - - func test_symmetricDifference_generic() { - withSampleRanges { r1, r2 in - let expected = Set(r1).symmetricDifference(r2).sorted() - - let u1 = Uniqued>(r1) - let actual1 = u1.symmetricDifference(r2) - expectEqualElements(actual1, expected) - - let actual2 = actual1.symmetricDifference(r1).symmetricDifference(r2) - expectEqual(actual2.count, 0) - } - } - - func test_formSymmetricDifference_generic() { - withSampleRanges { r1, r2 in - let expected = Set(r1).symmetricDifference(r2).sorted() - - var res = Uniqued>(r1) - res.formSymmetricDifference(r2) - expectEqualElements(res, expected) - - res.formSymmetricDifference(r1) - res.formSymmetricDifference(r2) - expectEqual(res.count, 0) - } - } - - func test_subtracting_Self() { - withSampleRanges { r1, r2 in - let expected = Set(r1).subtracting(r2).sorted() - - let u1 = Uniqued>(r1) - let u2 = Uniqued>(r2) - let actual1 = u1.subtracting(u2) - expectEqualElements(actual1, expected) - - let actual2 = actual1.subtracting(u2) - expectEqualElements(actual2, expected) - } - } - - func test_subtract_Self() { - withSampleRanges { r1, r2 in - let expected = Set(r1).subtracting(r2).sorted() - - let u1 = Uniqued>(r1) - let u2 = Uniqued>(r2) - var res = u1 - res.subtract(u2) - expectEqualElements(res, expected) - expectEqualElements(u1, r1) - - res.subtract(u2) - expectEqualElements(res, expected) - } - } - - func test_subtracting_generic() { - withSampleRanges { r1, r2 in - let expected = Set(r1).subtracting(r2).sorted() - - let u1 = Uniqued>(r1) - let actual1 = u1.subtracting(r2) - expectEqualElements(actual1, expected) - - let actual2 = actual1.subtracting(r2) - expectEqualElements(actual2, expected) - } - } - - func test_subtract_generic() { - withSampleRanges { r1, r2 in - let expected = Set(r1).subtracting(r2).sorted() - - var res = Uniqued>(r1) - res.subtract(r2) - expectEqualElements(res, expected) - - res.subtract(r2) - expectEqualElements(res, expected) - } - } - - struct SampleRanges { - let unit: Int - - init(unit: Int) { - self.unit = unit - } - - var empty: Range { unit ..< unit } - - var a: Range { 0 ..< unit } - var b: Range { unit ..< 2 * unit } - var c: Range { 2 * unit ..< 3 * unit } - - var ab: Range { 0 ..< 2 * unit } - var bc: Range { unit ..< 3 * unit } - - var abc: Range { 0 ..< 3 * unit } - - var ranges: [Range] { [empty, a, b, c, ab, bc, abc] } - - func withEveryPair( - _ body: (Range, Range) throws -> Void - ) rethrows { - try withEvery("range1", in: ranges) { range1 in - try withEvery("range2", in: ranges) { range2 in - try body(range1, range2) - } - } - } - } - - func test_isSubset_Self() { - 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 = Uniqued>(r1) - let b = Uniqued>(r2) - expectEqual(a.isSubset(of: b), 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 = Uniqued>(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 = Uniqued>(r1) - let b = r2 - expectEqual(a.isSubset(of: b), expected) - } - } - } - - func test_isSuperset_Self() { - 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 = Uniqued>(r1) - let b = Uniqued>(r2) - expectEqual(a.isSuperset(of: b), 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 = Uniqued>(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 = Uniqued>(r1) - let b = r2 - expectEqual(a.isSuperset(of: b), expected) - } - } - } - - func test_isStrictSubset_Self() { - 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 = Uniqued>(r1) - let b = Uniqued>(r2) - expectEqual(a.isStrictSubset(of: b), 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 = Uniqued>(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 = Uniqued>(r1) - let b = r2 - expectEqual(a.isStrictSubset(of: b), expected) - } - } - } - - func test_isStrictSuperset_Self() { - 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 = Uniqued>(r1) - let b = Uniqued>(r2) - expectEqual(a.isStrictSuperset(of: b), 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 = Uniqued>(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 = Uniqued>(r1) - let b = r2 - expectEqual(a.isStrictSuperset(of: b), expected) - } - } - } - - func test_isDisjoint_Self() { - 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 = Uniqued>(r1) - let b = Uniqued>(r2) - expectEqual(a.isDisjoint(with: b), expected) - } - } - } - - 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 = Uniqued>(r1) - let b = Set(r2) - expectEqual(a.isDisjoint(with: b), expected) - } - } - } - - 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 = Uniqued>(r1) - let b = r2 - expectEqual(a.isDisjoint(with: b), expected) - } - } - } -}