[BasicContainers] Implement removals on RigidSet and UniqueSet

Dictionaries are still to be done.
This commit is contained in:
Karoy Lorentey committed 2026-02-20 18:19:51 -08:00
1 parent d318a65867
commit 3941dab5b0
23 files changed
+513 -104

No files matched your search

@@ -19,7 +19,6 @@ extension _HTable {
// FIXME: Scramble order by swapping things in some way
let r = Bucket(offset: _count)
_count &+= 1
_totalProbeLength += _count
_maxProbeLength = _count
return r
}
@@ -40,7 +39,6 @@ extension _HTable {
let actual = bitmap.firstUnoccupiedBucket(from: ideal)
bitmap.setOccupied(actual)
let probeLength = self.probeLength(from: ideal, to: actual)
_totalProbeLength += probeLength
_maxProbeLength = Swift.max(_maxProbeLength, probeLength)
_count &+= 1
return actual
@@ -49,7 +47,6 @@ extension _HTable {
var probeLength = 0
while bitmap.isOccupied(b) {
probeLength &+= 1
_totalProbeLength &+= 1
let oldHashValue = hashGenerator(b)
let oldProbeLength = self.probeLength(
forHashValue: oldHashValue,
@@ -68,7 +65,6 @@ extension _HTable {
if probeLength > _maxProbeLength {
_maxProbeLength = probeLength
}
_totalProbeLength &+= 1
return b
#endif
}
@@ -0,0 +1,103 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2026 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 compiler(>=6.2)
extension _HTable {
/// Create a hole at the specified occupied bucket without marking it as
/// unoccupied ot restoring the hash table's other invariants. After a hole
/// is created, the table remains in an inconsistent state until one of
/// `resolveHole` or `finalizeHole` is called on the same bucket.
@usableFromInline
package mutating func createHole(
at bucket: Bucket
) {
assert(isOccupied(bucket))
_count &-= 1
}
/// Restore hash table invariants after a hole was created by `createHole`.
/// This works by swapping items as needed to move the hole forward until we
/// reach the end of the affected chain of occupied buckets.
@usableFromInline
@discardableResult
package mutating func resolveHole(
at bucket: Bucket,
hashGenerator: (Bucket) -> Int,
mover: (Bucket, Bucket) -> Void,
) -> Bucket {
if isSmall {
return finalizeHole(at: bucket, mover: mover)
}
assert(isOccupied(bucket))
// Our hash table does not have tombstones, so the holes that are left
// behind when an element is removed need to be immediately filled by the
// next item in the same chain that can now take that position. The process
// then repeats with the new hole thus created, until we reach the end of
// the chain. This is only possible because we're using linear probing;
// otherwise the same bucket would be part of a large number of diverging
// chains, and such compacting would require a full rehashing.
// Note: _maxProbeLength is not updated here, and so it may get out of
// sync with reality. It will get reset at the next rehashing, but if the
// table gets stuck at this size, this parameter may get significantly
// larger than it should be. The hope is that it won't so much larger that
// it would materially affect the performance of negative lookups.
var hole = bucket
var candidate = bucket
wrapBucket(after: &candidate)
while isOccupied(candidate) {
let hashValue = hashGenerator(candidate)
let ideal = self.idealBucket(forHashValue: hashValue)
// Does this element belong in some bucket at or below `hole`?
// If so, move it to the hole. We need two separate tests depending on
// whether `[hole, candidate]` wraps around the end of the storage.
let c0 = ideal <= hole
let c1 = ideal > candidate
if hole < candidate ? (c0 || c1) : (c0 && c1) {
mover(candidate, hole)
hole = candidate
}
wrapBucket(after: &candidate)
}
bitmap.clearOccupied(hole)
return hole
}
/// Finalize the hole at the given bucket, by moving it to some other position
/// (if needed), then marking it as unoccupied.
///
/// This does not fully restore the hash table to a usable state, but it
/// does enough to allow the hash table to get resized.
@discardableResult
@usableFromInline
package mutating func finalizeHole(
at bucket: Bucket,
mover: (Bucket, Bucket) -> Void,
) -> Bucket {
assert(isValid(bucket))
if isSmall {
let last = Bucket(offset: _count) // Note: _count was decreased by createHole
guard bucket < last else { return bucket }
mover(last, bucket)
return last
}
bitmap.clearOccupied(bucket)
return bucket
}
}
#endif
@@ -26,14 +26,16 @@ extension _HTable {
// ordered container.
let c = source.count
self._count = c
self._totalProbeLength = c * (c + 1) / 2
self._maxProbeLength = c
var dst = Bucket(offset: 0)
var src = Bucket(offset: c)
while src._offset > 0 {
src._offset &-= 1
migrator(src, dst)
dst._offset &+= 1
var dst = Bucket(offset: c)
var it = source.makeBucketIterator()
while let next = it.nextOccupiedRegion() {
var src = next.lowerBound
while src != next.upperBound {
dst._offset &-= 1
migrator(src, dst)
src._offset &+= 1
}
}
source.clear()
}
@@ -51,6 +51,25 @@ extension _HTable {
let shift = Swift.max(UInt(scale), Word.wordShift) - Word.wordShift
return 1 &<< shift
}
// These specific parameters result in the following capacity ranges:
//
// Scale Capacity range
// 4 2 ... 14
// 5 4 ... 28
// 6 8 ... 56
// 7 16 ... 112
// 8 32 ... 224
// 9 64 ... 448
// 10 128 ... 896
// 11 256 ... 1792
// 12 512 ... 3584
// etc.
//
// Note how neighboring intervals overlap significantly, as far as two steps
// away. This provides hysteresis for storage capacities, preventing hash
// tables from repeatedly shrinking/growing when only a handful of items are
// added/removed in a loop.
/// The numerator of the maximum hash table load factor.
@_transparent
@@ -29,14 +29,13 @@ package struct _HTable: ~Copyable {
@_alwaysEmitIntoClient
package let _bitmap: UnsafeMutablePointer<Word>?
@_alwaysEmitIntoClient
package var _totalProbeLength: Int
@_alwaysEmitIntoClient
package var _maxProbeLength: Int
@_alwaysEmitIntoClient
package let scale: UInt8
// FIXME: Add a reservedScale for UniqueSet/UniqueDictonary
@inlinable
internal init(
@@ -48,7 +47,6 @@ package struct _HTable: ~Copyable {
&& _capacity <= Self.maximumCapacity(forScale: scale))
self._count = 0
self._capacity = _capacity
self._totalProbeLength = 0
self._maxProbeLength = 0
self.scale = scale
if scale == 0 {
@@ -222,7 +220,6 @@ extension _HTable {
package mutating func clear() {
self._count = 0
self.bitmap.clearAll()
self._totalProbeLength = 0
self._maxProbeLength = 0
}
}
@@ -16,9 +16,7 @@ import InternalCollectionsUtilities
#if compiler(>=6.2)
extension _HTable {
package func maxOccupiedRun() -> Int {
if isSmall {
return self.count
}
if isSmall { return self.count }
var maxOccupiedRun = 0
var it = self.makeBucketIterator()
var first = true
@@ -48,7 +46,7 @@ extension _HTable {
if multiline {
str += "\n "
str += it.currentBucket.word == lastWord ? "└╴" : "├╴"
str += "[" + String(it.currentBucket.offset).lpad(8, with: "0") + "] "
str += "[" + String(it.currentBucket.offset)._lpad(8, with: "0") + "] "
} else {
str += " "
}
@@ -71,7 +69,6 @@ extension _HTable {
s += "\(multiline ? "" : bitmapDesc) "
s += "\(count)/\(capacity)/\(bucketCount), "
s += "maxProbeLength: \(_maxProbeLength), "
s += "totalProbeLength: \(_totalProbeLength), "
s += "maxOccupiedRun: \(maxOccupiedRun())"
if !self.isSmall, multiline {
@@ -58,7 +58,7 @@ extension RigidSet: BorrowingSequence where Element: ~Copyable {
@_alwaysEmitIntoClient
@_lifetime(copy self)
internal func _span(over buckets: Range<_HTable.Bucket>) -> Span<Element> {
internal func _span(over buckets: Range<_Bucket>) -> Span<Element> {
let items = UnsafeBufferPointer(
start: _baseAddress.unsafelyUnwrapped + buckets.lowerBound.offset,
count: buckets.upperBound.offset - buckets.lowerBound.offset)
@@ -9,6 +9,10 @@
//
//===----------------------------------------------------------------------===//
#if !COLLECTIONS_SINGLE_MODULE
import InternalCollectionsUtilities
#endif
#if compiler(>=6.3) && COLLECTIONS_UNSTABLE_NONCOPYABLE_KEYS
@available(SwiftStdlib 5.0, *)
@@ -16,20 +20,41 @@ extension RigidSet where Element: ~Copyable {
public func _describe(
bitmap: Bool = false,
chains: Bool = false,
buckets: Bool = false,
) -> String {
var s = _table.describe(bitmap: bitmap)
if chains {
s += "\n"
s += _chainDescription
}
if buckets, !_table.isSmall, !_table.isEmpty {
s += "\nBuckets:"
var it = _table.makeBucketIterator()
var c = 0
while let next = it.nextOccupiedRegion() {
var b = next.lowerBound
while b != next.upperBound {
if c.isMultiple(of: 8) { s += "\n " }
let hashValue = _hashValue(at: b)
let idealBucket = _table.idealBucket(forHashValue: hashValue)
let s1 = String(b.offset)._lpad(5)
let s2 = String(idealBucket.offset)._rpad(5)
s += "\(s1)→\(s2) "
c += 1
b._offset += 1
}
}
s += "\n"
}
return s
}
public func _dump(
bitmap: Bool = false,
chains: Bool = false,
buckets: Bool = false,
) {
print(self._describe(bitmap: bitmap, chains: chains))
print(self._describe(bitmap: bitmap, chains: chains, buckets: buckets))
}
public func _probeLengthCounts() -> (successful: [Int], unsuccessful: [Int]) {
@@ -63,7 +88,7 @@ extension RigidSet where Element: ~Copyable {
totalChainLength += length * count
totalCount += count
}
assert(totalCount == self.count)
//assert(totalCount == self.count)
var unsuccessful = Array(
repeating: 0,
@@ -71,7 +96,6 @@ extension RigidSet where Element: ~Copyable {
for (length, count) in negativeLengths {
unsuccessful[length] = count
}
//assert(totalChainLength == _table._totalProbeLength)
return (successful, unsuccessful)
}
@@ -85,7 +109,7 @@ extension RigidSet where Element: ~Copyable {
var histogram = ""
for length in data.successful.indices {
let count = data.successful[length]
histogram += "\(String(length + 1).lpad(6)): "
histogram += "\(String(length + 1)._lpad(6)): "
let dotCount = (75 * count + max) / max
histogram += String(repeating: "*", count: dotCount)
histogram += " \(count)\n"
@@ -102,7 +126,7 @@ extension RigidSet where Element: ~Copyable {
var histogram = ""
for length in data.unsuccessful.indices {
let count = data.unsuccessful[length]
histogram += "\(String(length).lpad(6)): "
histogram += "\(String(length)._lpad(6)): "
let dotCount = (75 * count + max) / max
histogram += String(repeating: "*", count: dotCount)
histogram += " \(count)\n"
@@ -18,13 +18,13 @@ extension RigidSet where Element: ~Copyable {
package struct _InsertResult: ~Copyable {
// FIXME: This struct really just wants to be a tuple.
@_alwaysEmitIntoClient
package var bucket: _HTable.Bucket
package var bucket: _Bucket
@_alwaysEmitIntoClient
package var remnant: Element?
@_alwaysEmitIntoClient
package init(
bucket: _HTable.Bucket, remnant: consuming Element?
bucket: _Bucket, remnant: consuming Element?
) {
self.bucket = bucket
self.remnant = remnant
@@ -39,8 +39,8 @@ extension RigidSet where Element: ~Copyable {
package mutating func _insertNew(
_ item: consuming Element,
hashValue: Int,
swapper: (borrowing Element, _HTable.Bucket) -> Void = { _, _ in }
) -> _HTable.Bucket {
swapper: (borrowing Element, _Bucket) -> Void = { _, _ in }
) -> _Bucket {
precondition(!isFull, "RigidSet capacity overflow")
let storage = _memberBuf
if _table.isSmall {
@@ -60,8 +60,8 @@ extension RigidSet where Element: ~Copyable {
@inline(__always)
package mutating func _insertNew_Large(
_ item: consuming Element,
swapper: (borrowing Element, _HTable.Bucket) -> Void = { _, _ in }
) -> _HTable.Bucket {
swapper: (borrowing Element, _Bucket) -> Void = { _, _ in }
) -> _Bucket {
_insertNew_Large(item, hashValue: _hashValue(for: item), swapper: swapper)
}
@@ -69,8 +69,8 @@ extension RigidSet where Element: ~Copyable {
package mutating func _insertNew_Large(
_ item: consuming Element,
hashValue: Int,
swapper: (borrowing Element, _HTable.Bucket) -> Void = { _, _ in }
) -> _HTable.Bucket {
swapper: (borrowing Element, _Bucket) -> Void = { _, _ in }
) -> _Bucket {
let storage = _memberBuf
let seed = self._seed
let bucket = _table.insertNew_Large(
@@ -90,7 +90,7 @@ extension RigidSet where Element: ~Copyable {
@discardableResult
package mutating func _insert(
_ item: consuming Element,
swapper: (borrowing Element, _HTable.Bucket) -> Void = { _, _ in }
swapper: (borrowing Element, _Bucket) -> Void = { _, _ in }
) -> _InsertResult {
let r = _find(item)
if let bucket = r.bucket {
@@ -16,7 +16,7 @@ extension RigidSet where Element: ~Copyable {
@inlinable
package borrowing func _find(
_ item: borrowing Element
) -> (bucket: _HTable.Bucket?, hashValue: Int) {
) -> (bucket: _Bucket?, hashValue: Int) {
let storage = _memberBuf
if _table.isSmall {
let bucket = _table.find_Small(tester: { storage[$0] == item })
@@ -0,0 +1,61 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2026 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 compiler(>=6.3) && COLLECTIONS_UNSTABLE_NONCOPYABLE_KEYS
@available(SwiftStdlib 5.0, *)
extension RigidSet where Element: ~Copyable {
/// Remove the member currently at the specified occupied bucket,
/// and mark it as unoccupied, without restoring the hash table's
/// invariants. Lookup operations may fail after this.
///
/// This operation is intended to be used just before resizing the table.
@inlinable
package mutating func _punchHole(at bucket: _Bucket) -> Element {
assert(_table.isOccupied(bucket))
_table.createHole(at: bucket)
let result = _memberPtr(at: bucket).move()
let members = _members.unsafelyUnwrapped
_table.finalizeHole(
at: bucket,
mover: {
(members + $1.offset).initialize(to: (members + $0.offset).move())
})
return result
}
@inlinable
package mutating func _remove(at bucket: _Bucket) -> Element {
assert(_table.isOccupied(bucket))
_table.createHole(at: bucket)
let result = _memberPtr(at: bucket).move()
let seed = self._seed
let members = _members.unsafelyUnwrapped
_table.resolveHole(
at: bucket,
hashGenerator: {
members[$0.offset]._rawHashValue(seed: seed)
},
mover: {
(members + $1.offset).initialize(to: (members + $0.offset).move())
})
return result
}
@inlinable
public mutating func remove(_ member: borrowing Element) -> Element? {
let r = _find(member)
guard let bucket = r.bucket else { return nil }
return _remove(at: bucket)
}
}
#endif
@@ -42,39 +42,40 @@ extension RigidSet where Element: ~Copyable {
self._table._capacity = capacity
return
}
let newTable = _HTable(_capacity: capacity, scale: scale)
var old = exchange(&self, with: Self(_table: newTable))
guard old.count > 0 else {
return
}
let source = old._members.unsafelyUnwrapped
let target = self._members.unsafelyUnwrapped
if self._table.isSmall {
self._table.migrateItems_Small(from: &old._table) { src, dst in
(target + dst.offset).initialize(to: (source + src.offset).move())
}
} else {
let seed = self._seed
var src = source
self._table.migrateItems_Large(
from: &old._table,
selector: {
src = source + $0.offset
return src.pointee._rawHashValue(seed: seed)
},
hashGenerator: {
target[$0.offset]._rawHashValue(seed: seed)
},
swapper: {
swap(&src.pointee, &target[$0.offset])
},
finalizer: {
(target + $0.offset).initialize(to: src.move())
}
)
return
}
let seed = self._seed
var src = source
self._table.migrateItems_Large(
from: &old._table,
selector: {
src = source + $0.offset
return src.pointee._rawHashValue(seed: seed)
},
hashGenerator: {
target[$0.offset]._rawHashValue(seed: seed)
},
swapper: {
swap(&src.pointee, &target[$0.offset])
},
finalizer: {
(target + $0.offset).initialize(to: src.move())
}
)
}
}
@@ -18,6 +18,9 @@ import ContainersPreview
@available(SwiftStdlib 5.0, *)
@frozen
public struct RigidSet<Element: GeneralizedHashable & ~Copyable>: ~Copyable {
@usableFromInline
package typealias _Bucket = _HTable.Bucket
@_alwaysEmitIntoClient
package var _members: UnsafeMutablePointer<Element>?
@@ -112,7 +115,7 @@ extension RigidSet where Element: ~Copyable {
@_alwaysEmitIntoClient
@_transparent
internal func _memberPtr(
at bucket: _HTable.Bucket
at bucket: _Bucket
) -> UnsafeMutablePointer<Element> {
assert(_table.isValid(bucket))
return _members.unsafelyUnwrapped.advanced(by: bucket.offset)
@@ -133,7 +136,7 @@ extension RigidSet where Element: ~Copyable {
@_alwaysEmitIntoClient
@_transparent
internal borrowing func _hashValue(
at bucket: _HTable.Bucket
at bucket: _Bucket
) -> Int {
assert(bucket.offset >= 0 && bucket.offset < _table.storageCapacity)
return _hashValue(for: _members.unsafelyUnwrapped[bucket.offset])
@@ -16,15 +16,17 @@ extension UniqueSet where Element: ~Copyable {
public func _describe(
bitmap: Bool = false,
chains: Bool = false,
buckets: Bool = false,
) -> String {
_storage._describe(bitmap: bitmap, chains: chains)
_storage._describe(bitmap: bitmap, chains: chains, buckets: buckets)
}
public func _dump(
bitmap: Bool = false,
chains: Bool = false,
buckets: Bool = false,
) {
_storage._dump(bitmap: bitmap, chains: chains)
_storage._dump(bitmap: bitmap, chains: chains, buckets: buckets)
}
}
@@ -0,0 +1,35 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2026 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 compiler(>=6.3) && COLLECTIONS_UNSTABLE_NONCOPYABLE_KEYS
@available(SwiftStdlib 5.0, *)
extension UniqueSet where Element: ~Copyable {
@inlinable
package mutating func _remove(at bucket: _Bucket) -> Element {
guard self.count == _HTable.minimumCapacity(forScale: self._scale) else {
return _storage._remove(at: bucket)
}
// Shrink storage.
let result = _storage._punchHole(at: bucket)
_resize(minimumCapacity: self.count)
return result
}
@inlinable
public mutating func remove(_ member: borrowing Element) -> Element? {
let r = _storage._find(member)
guard let bucket = r.bucket else { return nil }
return _remove(at: bucket)
}
}
#endif
@@ -19,6 +19,9 @@ import ContainersPreview
@available(SwiftStdlib 5.0, *)
@frozen
public struct UniqueSet<Element: GeneralizedHashable & ~Copyable>: ~Copyable {
@usableFromInline
package typealias _Bucket = _HTable.Bucket
@_alwaysEmitIntoClient
package var _storage: RigidSet<Element>
@@ -11,6 +11,32 @@
#if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
#if false
@available(SwiftStdlib 6.2, *)
extension Container where Self: ~Copyable & ~Escapable {
public func map<E: Error, T: ~Copyable>(
_ transform: (borrowing Element) throws(E) -> T
) throws(E) -> MapProducer<Element, T, E> {
}
}
public struct MapProducer<
Base: BorrowingSequence & ~Copyable & ~Escapable,
Element: ~Copyable,
E: Error
> {
internal var _transform: (borrowing Base.Element) throws(E) -> Element
internal init(
_base: borrowing Base,
_ transform: @escaping (borrowing Base.Element) throws(E) -> Element
) {
self._transform = transform
}
}
#endif
@available(SwiftStdlib 6.2, *)
extension Container where Self: ~Copyable & ~Escapable {
@_alwaysEmitIntoClient
@@ -11,21 +11,21 @@
extension String {
@_alwaysEmitIntoClient
package func lpad(_ width: Int, with character: Character = " ") -> Self {
package func _lpad(_ width: Int, with character: Character = " ") -> Self {
let c = count
guard c < width else { return self }
return String(repeating: character, count: width - c) + self
}
@_alwaysEmitIntoClient
package func rpad(_ width: Int, with character: Character = " ") -> Self {
package func _rpad(_ width: Int, with character: Character = " ") -> Self {
let c = count
guard c < width else { return self }
return self + String(repeating: character, count: width - c)
}
@_alwaysEmitIntoClient
package func cpad(_ width: Int, with character: Character = " ") -> Self {
package func _cpad(_ width: Int, with character: Character = " ") -> Self {
let c = count
guard c < width else { return self }
let l = String(repeating: character, count: (width - c + 1) / 2)
@@ -9,6 +9,10 @@
//
//===----------------------------------------------------------------------===//
#if !COLLECTIONS_SINGLE_MODULE
import InternalCollectionsUtilities
#endif
#if compiler(>=6.2) && !$Embedded
@available(SwiftStdlib 6.2, *)
@@ -16,7 +20,7 @@ extension BigString._Chunk: CustomStringConvertible {
var description: String {
let counts = """
❨\(utf8Count)⋅\(utf16Count)⋅\(unicodeScalarCount)⋅\(characterCount)❩
"""._rpad(to: 17)
"""._rpad(17)
let d = _succinctContents(maxLength: 10)
return "Chunk(\(_identity) \(counts) \(d))"
}
@@ -28,7 +32,7 @@ extension BigString._Chunk: CustomStringConvertible {
func _succinctContents(maxLength c: Int) -> String {
/// 4+"short"-1
/// 0+"longer...string"-1
let pc = String(prefixCount)._lpad(to: 3)
let pc = String(prefixCount)._lpad(3)
let sc = String(suffixCount)
let s = String(copying: wholeCharacters)
@@ -11,61 +11,45 @@
#if compiler(>=6.2) && !$Embedded
@available(SwiftStdlib 6.2, *)
extension StringProtocol {
@inline(__always)
var _indexOfLastCharacter: Index {
internal var _indexOfLastCharacter: Index {
guard !isEmpty else { return endIndex }
return index(before: endIndex)
}
@inline(__always)
func _index(at offset: Int) -> Index {
internal func _index(at offset: Int) -> Index {
self.index(self.startIndex, offsetBy: offset)
}
@inline(__always)
func _utf8Index(at offset: Int) -> Index {
internal func _utf8Index(at offset: Int) -> Index {
self.utf8.index(startIndex, offsetBy: offset)
}
@inline(__always)
func _utf8ClampedIndex(at offset: Int) -> Index {
internal func _utf8ClampedIndex(at offset: Int) -> Index {
self.utf8.index(startIndex, offsetBy: offset, limitedBy: endIndex) ?? endIndex
}
@inline(__always)
func _utf8Offset(of index: Index) -> Int {
internal func _utf8Offset(of index: Index) -> Int {
self.utf8.distance(from: startIndex, to: index)
}
@inline(__always)
var _lastCharacter: (index: Index, utf8Length: Int) {
internal var _lastCharacter: (index: Index, utf8Length: Int) {
let i = _indexOfLastCharacter
let length = utf8.distance(from: i, to: endIndex)
return (i, length)
}
}
@available(SwiftStdlib 6.2, *)
extension String {
internal func _lpad(to width: Int, with pad: Character = " ") -> String {
let c = self.count
if c >= width { return self }
return String(repeating: pad, count: width - c) + self
}
internal func _rpad(to width: Int, with pad: Character = " ") -> String {
let c = self.count
if c >= width { return self }
return self + String(repeating: pad, count: width - c)
}
}
@available(SwiftStdlib 6.2, *)
extension String {
@discardableResult
mutating func _appendQuotedProtectingLeft(
internal mutating func _appendQuotedProtectingLeft(
_ str: String,
with state: inout _CharacterRecognizer,
maxLength: Int = Int.max
@@ -98,7 +82,7 @@ extension String {
return i
}
mutating func _appendProtectingRight(_ str: String, with state: inout _CharacterRecognizer) {
internal mutating func _appendProtectingRight(_ str: String, with state: inout _CharacterRecognizer) {
var suffix = str
while !self.isEmpty {
guard let first = suffix.unicodeScalars.first else { return }
@@ -117,7 +101,7 @@ extension String {
/// A representation of the string that is suitable for debugging.
/// This implementation differs from `String.debugDescription` by properly quoting
/// continuation characters after the opening quotation mark and similar meta-characters.
var _properDebugDescription: String {
internal var _properDebugDescription: String {
var result = "\""
var state = _CharacterRecognizer(consuming: result)
result._appendQuotedProtectingLeft(self, with: &state)
@@ -128,7 +112,7 @@ extension String {
extension String {
@available(SwiftStdlib 6.2, *)
mutating func append(copying utf8Span: UTF8Span) {
internal mutating func append(copying utf8Span: UTF8Span) {
self = String(unsafeUninitializedCapacity: utf8.count + utf8Span.count) {
var buffer = $0
+59 -7
View File
@@ -81,7 +81,7 @@ class RigidSetTests: CollectionTestCase {
expectEqual(s.freeCapacity, 19)
}
}
func test_insert_full() {
withEvery("capacity", in: [0, 1, 2, 10, 100, 1000]) { capacity in
withLifetimeTracking { tracker in
@@ -108,7 +108,7 @@ class RigidSetTests: CollectionTestCase {
}
}
}
func test_update_full() {
withEvery("capacity", in: [0, 1, 2, 10, 100, 200, 1000]) { capacity in
withLifetimeTracking { tracker in
@@ -123,7 +123,7 @@ class RigidSetTests: CollectionTestCase {
expectTrue(s.isFull)
expectEqual(s.capacity, capacity)
expectEqual(s.freeCapacity, 0)
for i in 0 ..< capacity {
let new = tracker.instance(for: i)
let old = s.update(with: new)
@@ -136,7 +136,7 @@ class RigidSetTests: CollectionTestCase {
expectTrue(s.isFull)
expectEqual(s.capacity, capacity)
expectEqual(s.freeCapacity, 0)
for i in 0 ..< capacity {
let dupe = tracker.instance(for: i)
expectTrue(s.contains(dupe), "\(dupe) not found")
@@ -144,7 +144,7 @@ class RigidSetTests: CollectionTestCase {
}
}
}
func test_bucketIterator_consistency() {
withEvery("capacity", in: [0, 1, 2, 3, 4, 10, 100, 200]) { capacity in
withEvery("maximumCount", in: [1, 2, 3, Int.max]) { maximumCount in
@@ -152,7 +152,7 @@ class RigidSetTests: CollectionTestCase {
var s = RigidSet<LifetimeTracked<Int>>(capacity: capacity)
withEvery("i", in: 0 ..< capacity) { i in
s.insert(tracker.instance(for: i))
var it = s._table.makeBucketIterator()
var j = s._table.startBucket
while let next = it.nextOccupiedRegion(maximumCount: maximumCount) {
@@ -196,7 +196,7 @@ class RigidSetTests: CollectionTestCase {
}
set._dump(bitmap: true, chains: true)
}
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
func test_iterate() {
withEvery("capacity", in: [0, 1, 2, 3, 4, 10, 100, 1000]) { capacity in
@@ -224,5 +224,57 @@ class RigidSetTests: CollectionTestCase {
}
}
#endif
func test_remove_one() {
withEvery("count", in: [0, 1, 2, 4, 10, 100, 500]) { count in
withEvery("item", in: 0 ..< count) { item in
withLifetimeTracking { tracker in
var set = RigidSet<LifetimeTracked<Int>>(capacity: count)
for i in 0 ..< count {
let instance = tracker.instance(for: i)
set.insert(instance)
}
expectEqual(set.count, count)
let dupe = tracker.instance(for: item)
let removed = set.remove(dupe)
expectNotNil(removed) {
expectNotIdentical($0, dupe)
expectEqual($0.payload, item)
}
expectEqual(set.count, count - 1)
withEvery("j", in: 0 ..< count) { j in
let found = set.contains(tracker.instance(for: j))
expectEqual(found, j != item)
}
}
}
}
}
func test_remove_all() {
withEvery("count", in: [0, 1, 2, 4, 10, 100, 1000]) { count in
withLifetimeTracking { tracker in
var set = RigidSet<LifetimeTracked<Int>>(capacity: count)
for i in 0 ..< count {
let instance = tracker.instance(for: i)
set.insert(instance)
}
expectEqual(set.count, count)
withEvery("i", in: 0 ..< count) { i in
let dupe = tracker.instance(for: i)
let removed = set.remove(dupe)
expectNotNil(removed) {
expectNotIdentical($0, dupe)
expectEqual($0.payload, i)
}
}
expectEqual(set.count, 0)
}
}
}
}
#endif
@@ -116,18 +116,106 @@ class UniqueSetTests: CollectionTestCase {
func test_insert_growth() {
// These are the storage capacities we expect to see for a UniqueSet
// up to size 1000.
let expected = [0, 1, 2, 4, 7, 14, 28, 56, 112, 224, 448, 896, 1792]
var expectedCapacities = [
0, 1, 2, 4, 7, 14, 28, 56, 112, 224, 448, 896, 1792
]
var j = 0
var set = UniqueSet<Int>()
expectEqual(set.capacity, expected[j])
expectEqual(set.capacity, expectedCapacities[j])
withEvery("i", in: 1 ..< 1000) { i in
set.insert(i)
if i > expected[j] {
if i > expectedCapacities[j] {
j += 1
}
expectEqual(set.capacity, expected[j])
expectEqual(set.capacity, expectedCapacities[j])
}
}
func test_remove_one() {
withEvery("cap", in: [0, 1, 2, 4, 10, 100, 500]) { cap in
let scale = _HTable.minimumScale(forCapacity: cap)
let count = _HTable.minimumCapacity(forScale: scale)
withEvery("item", in: 0 ..< count) { item in
withLifetimeTracking { tracker in
var set = UniqueSet<LifetimeTracked<Int>>(minimumCapacity: cap)
expectEqual(set._scale, scale)
for i in 0 ..< count {
let instance = tracker.instance(for: i)
set.insert(instance)
}
expectEqual(set.count, count)
expectEqual(set._scale, scale)
let dupe = tracker.instance(for: item)
let removed = set.remove(dupe)
expectNotNil(removed) {
expectNotIdentical($0, dupe)
expectEqual($0.payload, item)
}
expectEqual(set.count, count - 1)
let expectedScale = _HTable.minimumScale(forCapacity: count - 1)
if scale > 0 {
expectLessThan(expectedScale, scale)
}
expectEqual(set._scale, expectedScale)
withEvery("j", in: 0 ..< count) { j in
let found = set.contains(tracker.instance(for: j))
expectEqual(found, j != item)
}
}
}
}
}
func test_remove_all() {
withEvery("count", in: [0, 1, 2, 4, 10, 100, 1000]) { count in
withLifetimeTracking { tracker in
var set = UniqueSet<LifetimeTracked<Int>>(minimumCapacity: count)
for i in 0 ..< count {
let instance = tracker.instance(for: i)
set.insert(instance)
}
expectEqual(set.count, count)
withEvery("i", in: 0 ..< count) { i in
let dupe = tracker.instance(for: i)
let removed = set.remove(dupe)
expectNotNil(removed) {
expectNotIdentical($0, dupe)
expectEqual($0.payload, i)
}
expectEqual(set.count, count - 1 - i)
expectGreaterThanOrEqual(
set.count,
_HTable.minimumCapacity(forScale: set._scale))
}
expectEqual(set.count, 0)
}
}
}
func test_remove_shrinkage() {
let c = 1000
let expectedCapacities = [1792, 448, 112, 28, 4]
var set = UniqueSet<Int>(minimumCapacity: c)
for i in 0 ..< c {
set.insert(i)
}
var j = 0
expectEqual(set.capacity, expectedCapacities[j])
withEvery("i", in: 0 ..< c) { i in
let removed = set.remove(i)
expectEqual(removed, i)
expectEqual(set.count, c - i - 1)
if set.capacity != expectedCapacities[j], j < expectedCapacities.count - 1 {
j += 1
}
expectEqual(set.capacity, expectedCapacities[j])
}
}
@@ -95,6 +95,9 @@
7D479CEB2F47F3C100A8CB59 /* UniqueDictionary+Resizing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D479CEA2F47F3BC00A8CB59 /* UniqueDictionary+Resizing.swift */; };
7D479CED2F47F41000A8CB59 /* RigidDictionary+Consumption.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D479CEC2F47F40700A8CB59 /* RigidDictionary+Consumption.swift */; };
7D479CEF2F47F4E900A8CB59 /* UniqueDictionary+Consumption.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D479CEE2F47F4E300A8CB59 /* UniqueDictionary+Consumption.swift */; };
7D479CF12F47FA8600A8CB59 /* RigidSet+Removals.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D479CF02F47FA8200A8CB59 /* RigidSet+Removals.swift */; };
7D479CF32F47FB4100A8CB59 /* _HTable+Removal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D479CF22F47FB3D00A8CB59 /* _HTable+Removal.swift */; };
7D479CF52F49070400A8CB59 /* UniqueSet+Removals.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D479CF42F49070100A8CB59 /* UniqueSet+Removals.swift */; };
7D48BCDC2E51554900D7F6F7 /* ClassBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCDB2E51554900D7F6F7 /* ClassBox.swift */; };
7D48BCDF2E51558700D7F6F7 /* TestPrintable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCDD2E51558700D7F6F7 /* TestPrintable.swift */; };
7D48BCE02E51558700D7F6F7 /* LifetimeTrackedStruct.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCDE2E51558700D7F6F7 /* LifetimeTrackedStruct.swift */; };
@@ -639,6 +642,9 @@
7D479CEA2F47F3BC00A8CB59 /* UniqueDictionary+Resizing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueDictionary+Resizing.swift"; sourceTree = "<group>"; };
7D479CEC2F47F40700A8CB59 /* RigidDictionary+Consumption.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidDictionary+Consumption.swift"; sourceTree = "<group>"; };
7D479CEE2F47F4E300A8CB59 /* UniqueDictionary+Consumption.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueDictionary+Consumption.swift"; sourceTree = "<group>"; };
7D479CF02F47FA8200A8CB59 /* RigidSet+Removals.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidSet+Removals.swift"; sourceTree = "<group>"; };
7D479CF22F47FB3D00A8CB59 /* _HTable+Removal.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "_HTable+Removal.swift"; sourceTree = "<group>"; };
7D479CF42F49070100A8CB59 /* UniqueSet+Removals.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueSet+Removals.swift"; sourceTree = "<group>"; };
7D48BCC92E51524200D7F6F7 /* CMakeLists.txt */ = {isa = PBXFileReference; lastKnownFileType = text; path = CMakeLists.txt; sourceTree = "<group>"; };
7D48BCDB2E51554900D7F6F7 /* ClassBox.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClassBox.swift; sourceTree = "<group>"; };
7D48BCDD2E51558700D7F6F7 /* TestPrintable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TestPrintable.swift; sourceTree = "<group>"; };
@@ -1253,6 +1259,7 @@
7D479CD32F46DD9600A8CB59 /* UniqueSet+Initializers.swift */,
7D479CC82F46D21800A8CB59 /* UniqueSet+Insertions.swift */,
7D479CCA2F46D22B00A8CB59 /* UniqueSet+Lookup.swift */,
7D479CF42F49070100A8CB59 /* UniqueSet+Removals.swift */,
7D479CC62F46D20F00A8CB59 /* UniqueSet+Resizing.swift */,
);
path = UniqueSet;
@@ -1305,6 +1312,7 @@
7D72467E2F3D9DDB00112FD0 /* _HTable+Find.swift */,
7D72467F2F3D9DDB00112FD0 /* _HTable+Insert.swift */,
7D7246802F3D9DDB00112FD0 /* _HTable+Iteration.swift */,
7D479CF22F47FB3D00A8CB59 /* _HTable+Removal.swift */,
7D479CE82F47DE1C00A8CB59 /* _HTable+Resizing.swift */,
7D72467D2F3D9DDB00112FD0 /* _HTable+Sizing.swift */,
);
@@ -1334,6 +1342,7 @@
7D479CD12F46DD8600A8CB59 /* RigidSet+Initializers.swift */,
7D479CBE2F46D09E00A8CB59 /* RigidSet+Insertions.swift */,
7D479CBC2F46D05000A8CB59 /* RigidSet+Lookup.swift */,
7D479CF02F47FA8200A8CB59 /* RigidSet+Removals.swift */,
7D479CC22F46D19200A8CB59 /* RigidSet+Resizing.swift */,
);
path = RigidSet;
@@ -2515,6 +2524,7 @@
7D9B75772F3E65E00048157E /* _Htable+Debugging.swift in Sources */,
7DE9214829CA70F4004483EB /* _HashNode+Primitive Removals.swift in Sources */,
7DE9216029CA70F4004483EB /* _HashNode+Structural isDisjoint.swift in Sources */,
7D479CF32F47FB4100A8CB59 /* _HTable+Removal.swift in Sources */,
7DE9203529CA70F3004483EB /* OrderedSet+CustomReflectable.swift in Sources */,
7DE920C929CA70F4004483EB /* BitSet+BidirectionalCollection.swift in Sources */,
7DE920ED29CA70F4004483EB /* BitArray+Extras.swift in Sources */,
@@ -2726,6 +2736,7 @@
7DE9207129CA70F4004483EB /* BigString+Split.swift in Sources */,
7DE9214F29CA70F4004483EB /* _Bucket.swift in Sources */,
7DE9208029CA70F4004483EB /* BigString+Hashing.swift in Sources */,
7D479CF52F49070400A8CB59 /* UniqueSet+Removals.swift in Sources */,
7DE920F829CA70F4004483EB /* BitArray+Testing.swift in Sources */,
7DE920D629CA70F4004483EB /* BitSet+Equatable.swift in Sources */,
7D57A2D22F353CA5002543BD /* UniqueArray+Deprecated.swift in Sources */,
@@ -2736,6 +2747,7 @@
7DAD89A72E8B09D900DD5786 /* _UnsafeBitSet.swift in Sources */,
7DE9201E29CA70F3004483EB /* OrderedSet+Partial SetAlgebra symmetricDifference.swift in Sources */,
7DE9207A29CA70F4004483EB /* BigString+UTF8View.swift in Sources */,
7D479CF12F47FA8600A8CB59 /* RigidSet+Removals.swift in Sources */,
7DE9201329CA70F3004483EB /* OrderedDictionary+CustomReflectable.swift in Sources */,
7D479CCB2F46D22F00A8CB59 /* UniqueSet+Lookup.swift in Sources */,
7DE9201C29CA70F3004483EB /* OrderedDictionary+Partial MutableCollection.swift in Sources */,