Remove Uniqued<Base>

This type was one of the prototypes for `OrderedSet` — it allowed us to customize the collection type used for element storage. (E.g., using `Deque` instead of `Array` to get efficient insertions at the front.) The original idea was that `OrderedSet` would simply be a typealias:

```swift
typealias OrderedSet<Element> = Uniqued<Array<Element>>
```

Unfortunately, while this concept is intellectually pleasing, in practice it just made the interface more complicated (and, in some cases, slower). Worse, it cannot be directly translated to an `OrderedDictionary`-style key-value mapping without major usability problems.

# Conflicts:
#	Package.swift
This commit is contained in:
Karoy Lorentey committed 2021-04-05 09:41:00 -07:00
1 parent a2bcac435f
commit 68609682e0
33 files changed
-6186

No files matched your search

@@ -1,78 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1230"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "UniquedModule"
BuildableName = "UniquedModule"
BlueprintName = "UniquedModule"
ReferencedContainer = "container:">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
codeCoverageEnabled = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "UniquedTests"
BuildableName = "UniquedTests"
BlueprintName = "UniquedTests"
ReferencedContainer = "container:">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "UniquedModule"
BuildableName = "UniquedModule"
BlueprintName = "UniquedModule"
ReferencedContainer = "container:">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
-11
View File
@@ -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<Base>
.target(
name: "UniquedModule",
dependencies: ["DequeModule"],
swiftSettings: settings),
.testTarget(
name: "UniquedTests",
dependencies: ["UniquedModule", "CollectionsTestSupport"],
swiftSettings: settings),
],
cxxLanguageStandard: .cxx1z
)
@@ -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)]
}
}
@@ -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)
}
}
@@ -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
}
}
@@ -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)
}
}
@@ -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
}
}
@@ -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)
}
}
@@ -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)
}
}
@@ -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)
}
}
}
@@ -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<S: Sequence>(uncheckedUniqueElements elements: S)
where S.Element == Element {
self.init(uncheckedUniqueElements: Base(elements))
}
public init<S: Sequence>(uniqueElements elements: S)
where S.Element == Element {
self.init(uniqueElements: Base(elements))
}
}
@@ -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<S: Sequence>(
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<S: Sequence>(
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
}
}
@@ -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
}
@@ -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<Element: Hashable>(
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<T: RandomNumberGenerator>(
using generator: inout T
) {
_elements.shuffle(using: &generator)
_regenerateHashTable()
_checkInvariants()
}
}
extension Uniqued {
@_spi(UnsafeInternals)
public mutating func _partition<Key, Value>(
values: UnsafeMutableBufferPointer<Value>,
by belongsInSecondPartition: ((key: Key, value: Value)) throws -> Bool
) rethrows -> Int
where Base == ContiguousArray<Key> {
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
}
}
}
}
@@ -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<Index>) {
_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))
}
}
@@ -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<S: Sequence>(_ elements: S) where S.Element == Element {
if S.self == Self.self {
self = elements as! Self
return
}
if S.self == Set<Element>.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<Element>) {
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<Value>(_ elements: Dictionary<Element, Value>.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<S: Sequence>(
_ other: __owned S
) where S.Element == Element {
for item in other {
append(item)
}
}
public __consuming func union<S: Sequence>(
_ 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<S: Sequence>(
_ 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<S: Sequence>(
_ 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<S: Sequence>(
_ 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<S: Sequence>(
_ 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<S: Sequence>(
_ other: S
) -> Self where S.Element == Element {
_subtracting(other)
}
@inline(__always)
public mutating func subtract<S: Sequence>(
_ other: S
) where S.Element == Element {
self = _subtracting(other)
}
__consuming func _subtracting<S: Sequence>(
_ 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<Element>) -> 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<S: Sequence>(
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<Element>) -> Bool {
guard self.count >= other.count else { return false }
return _isSuperset(of: other)
}
public func isSuperset<S: Sequence>(
of other: S
) -> Bool where S.Element == Element {
_isSuperset(of: other)
}
internal func _isSuperset<S: Sequence>(
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<Element>) -> Bool {
self.count < other.count && self.isSubset(of: other)
}
public func isStrictSubset<S: Sequence>(
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<Element>) -> Bool {
self.count > other.count && other.isSubset(of: self)
}
public func isStrictSuperset<S: Sequence>(
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<Element>) -> 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<S: Sequence>(
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
}
}
@@ -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<Index>) -> 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<Index>) {
_elements._failEarlyRangeCheck(index, bounds: bounds)
}
public func _failEarlyRangeCheck(_ index: Index, bounds: ClosedRange<Index>) {
_elements._failEarlyRangeCheck(index, bounds: bounds)
}
public func _failEarlyRangeCheck(_ range: Range<Index>, bounds: Range<Index>) {
_elements._failEarlyRangeCheck(range, bounds: bounds)
}
}
@@ -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<Element> {
_elements._copyToContiguousArray()
}
public __consuming func _copyContents(
initializing ptr: UnsafeMutableBufferPointer<Element>
) -> (Iterator, UnsafeMutableBufferPointer<Element>.Index) {
_elements._copyContents(initializing: ptr)
}
public func withContiguousStorageIfAvailable<R>(
_ body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R? {
try _elements.withContiguousStorageIfAvailable(body)
}
}
@@ -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<Index>) {
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<Element> {
_slice._copyToContiguousArray()
}
public __consuming func _copyContents(
initializing ptr: UnsafeMutableBufferPointer<Element>
) -> (Iterator, UnsafeMutableBufferPointer<Element>.Index) {
_slice._copyContents(initializing: ptr)
}
public func withContiguousStorageIfAvailable<R>(
_ body: (UnsafeBufferPointer<Element>) 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<Index>) -> 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<Index>) {
_slice._failEarlyRangeCheck(index, bounds: bounds)
}
public func _failEarlyRangeCheck(_ index: Index, bounds: ClosedRange<Index>) {
_slice._failEarlyRangeCheck(index, bounds: bounds)
}
public func _failEarlyRangeCheck(_ range: Range<Index>, bounds: Range<Index>) {
_slice._failEarlyRangeCheck(range, bounds: bounds)
}
}
-141
View File
@@ -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<C: Collection>(
_scale scale: Int,
bias: Int,
contents: C
) where C.Element == Element {
self.init(_scale: scale, bias: bias, contents: Base(contents))
}
}
@@ -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<S: Sequence>(_ elements: S) where S.Element == Element {
_base = Uniqued(elements)
}
// Specializations
public init(_ elements: Self) {
self = elements
}
public init(_ elements: Set<Element>) {
self._base = Uniqued(elements)
}
public init<Value>(_ elements: Dictionary<Element, Value>.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<S: Sequence>(
_ other: __owned S
) where S.Element == Element {
_base.formUnion(other)
}
@inline(__always)
public __consuming func union<S: Sequence>(
_ 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<S: Sequence>(
_ other: S
) -> Self where S.Element == Element {
_base.intersection(other).unordered
}
@inline(__always)
public mutating func formIntersection<S: Sequence>(
_ 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<S: Sequence>(
_ other: __owned S
) -> Self where S.Element == Element {
_base.symmetricDifference(other).unordered
}
@inline(__always)
public mutating func formSymmetricDifference<S: Sequence>(
_ 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<S: Sequence>(
_ other: S
) -> Self where S.Element == Element {
_base.subtracting(other).unordered
}
@inline(__always)
public mutating func subtract<S: Sequence>(
_ 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<Element>) -> Bool {
_base.isSubset(of: other)
}
@inline(__always)
public func isSubset<S: Sequence>(
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<Element>) -> Bool {
_base.isSuperset(of: other)
}
@inline(__always)
public func isSuperset<S: Sequence>(
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<Element>) -> Bool {
_base.isStrictSubset(of: other)
}
@inline(__always)
public func isStrictSubset<S: Sequence>(
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<Element>) -> Bool {
_base.isStrictSuperset(of: other)
}
public func isStrictSuperset<S: Sequence>(
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<Element>) -> Bool {
_base.isDisjoint(with: other)
}
public func isDisjoint<S: Sequence>(
with other: S
) -> Bool where S.Element == Element {
_base.isDisjoint(with: other)
}
}
-203
View File
@@ -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<Base>
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)
}
}
-32
View File
@@ -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
}
}
@@ -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<C: RandomAccessCollection>(
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<R>(_ 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<R>(_ 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)"
}
}
@@ -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)"
}
}
-321
View File
@@ -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<Word>
internal var _count: Int
@inline(__always)
internal init(words: UnsafeMutableBufferPointer<Word>, count: Int) {
self._words = words
self._count = count
}
@inline(__always)
internal init(words: UnsafeMutablePointer<Word>, 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<R>(
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<Word>.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
}
}
@@ -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<UInt64>
#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<UInt64>,
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<Int> {
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<Element: Hashable>(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<Element: Hashable>(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<Base: RandomAccessCollection>(
_ 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<Base: RandomAccessCollection>(
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[..<index] {
var it = bucketIterator(for: item)
it.advance(until: i)
it.currentValue! -= 1
i += 1
}
} else {
var it = bucketIterator(startingAt: _Bucket(offset: 0))
repeat {
guard let value = it.currentValue, value <= offset else { continue }
it.currentValue = value - 1
} while it.currentBucket.offset != 0
}
} else {
if elements.count - offset - 1 <= capacity / 8 {
var i = offset
for item in elements[index...] {
var it = bucketIterator(for: item)
it.advance(until: i)
it.currentValue! += 1
i += 1
}
} else {
var it = bucketIterator(startingAt: _Bucket(offset: 0))
repeat {
guard let value = it.currentValue, value >= offset else { continue }
it.currentValue = value + 1
} while it.currentBucket.offset != 0
}
}
}
}
extension _UnsafeHashTable {
@inline(__always)
internal func adjustContents<Base: RandomAccessCollection>(
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<Base: RandomAccessCollection>(
preparingForRemovalOf bounds: Range<Base.Index>,
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[..<bounds.lowerBound] {
var it = self.bucketIterator(for: item)
it.advance(until: i)
it.currentValue = i + c
i += 1
}
self.bias -= c
}
}
}
extension _UnsafeHashTable {
func clear() {
assertMutable()
_buckets.assign(repeating: 0, count: wordCount)
}
}
extension _UnsafeHashTable {
/// Fill an empty hash table by populating it with data from `elements`.
///
/// - Parameter elements: A random-access collection for which this table is being generated.
/// - Parameter stoppingOnFirstDuplicateValue: If true, check for duplicate values and stop inserting items when one is found.
/// - Returns: `(success, index)` where `success` is a boolean value indicating that every value in `elements` was successfully inserted. A false success indicates that duplicate elements have been found; in this case `index` points to the first duplicate value; otherwise `index` is set to `elements.endIndex`.
@discardableResult
func fill<C: RandomAccessCollection>(
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)
}
}
-187
View File
@@ -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<Int>) 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
-607
View File
@@ -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<R>(
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<R>(
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
@@ -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<Int>) -> Range<Index> {
_index(at: offsets.lowerBound) ..< _index(at: offsets.upperBound)
}
@inline(__always)
internal func _indexRange<R: RangeExpression>(at offsets: R) -> Range<Index>
where R.Bound == Int {
return _indexRange(at: offsets.relative(to: 0 ..< self.count))
}
@inline(__always)
internal func _offsetRange(of range: Range<Index>) -> Range<Int> {
_offset(of: range.lowerBound) ..< _offset(of: range.upperBound)
}
@inline(__always)
internal func _offsetRange<R: RangeExpression>(of range: R) -> Range<Int>
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<Int>) -> SubSequence {
self[_indexRange(at: range)]
}
@inline(__always)
internal subscript<R: RangeExpression>(_offsets range: R) -> SubSequence
where R.Bound == Int {
self[_offsets: range.relative(to: 0 ..< count)]
}
}
@@ -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<T> = MinimalRandomAccessCollection<T>
typealias MinimalBase<T> = MinimalRangeReplaceableRandomAccessCollection<T>
typealias MinimalMutableBase<T> = MinimalMutableRangeReplaceableRandomAccessCollection<T>
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<Int>] =
.init(input.lazy.map { ($0.payload, $0) },
uniquingKeysWith: { a, b in a })
var set = Uniqued<MinimalBase<LifetimeTracked<Int>>>()
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<MinimalBase<Int>>(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<Int>] = [:]
var set = Uniqued<MinimalMutableBase<LifetimeTracked<Int>>>()
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<MinimalMutableBase<Int>>(0 ..< 30)
let copy = set
expectNil(set.unordered.update(with: 30))
expectTrue(set.contains(30))
expectFalse(copy.contains(30))
}
}
}
-81
View File
@@ -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<C: Collection>(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)
}
}
File diff suppressed because it is too large. Load diff