[BitSet, OrderedCollections] Unify UnsafeBitSet implementations

This commit is contained in:
Karoy Lorentey committed 2022-11-28 16:30:55 -08:00
1 parent c80b844e5e
commit a2f4b18ae0
29 files changed
+944 -1382

No files matched your search

@@ -9,7 +9,11 @@
//
//===----------------------------------------------------------------------===//
import _CollectionsUtilities
internal struct _ChunkedBitsForwardIterator {
internal typealias _BitPosition = _UnsafeBitSet.Index
internal let words: UnsafeBufferPointer<_Word>
internal let end: _BitPosition
internal var position: _BitPosition
@@ -43,6 +47,8 @@ internal struct _ChunkedBitsForwardIterator {
}
internal struct _ChunkedBitsBackwardIterator {
internal typealias _BitPosition = _UnsafeBitSet.Index
internal let words: UnsafeBufferPointer<_Word>
internal let start: _BitPosition
internal var position: _BitPosition
@@ -9,12 +9,17 @@
//
//===----------------------------------------------------------------------===//
import _CollectionsUtilities
extension BitArray {
/// An unsafe-unowned bitarray view over `UInt` storage, providing bit array
/// primitives.
@usableFromInline
@frozen
internal struct _UnsafeHandle {
@usableFromInline
internal typealias _BitPosition = _UnsafeBitSet.Index
@usableFromInline
internal let _words: UnsafeBufferPointer<_Word>
@@ -9,6 +9,8 @@
//
//===----------------------------------------------------------------------===//
import _CollectionsUtilities
/// An ordered, random-access collection of `Bool` values, implemented as an
/// uncompressed bitmap of as many bits as the count of the array.
///
@@ -19,6 +21,9 @@
/// structure, treating it as a set of nonnegative integers corresponding to
/// `true` bits.
public struct BitArray {
@usableFromInline
internal typealias _BitPosition = _UnsafeBitSet.Index
@usableFromInline
internal var _storage: [_Word]
@@ -158,7 +158,7 @@ extension BitSet: Collection, BidirectionalCollection {
/// storage.)
public func index(after index: Index) -> Index {
_read { handle in
assert(handle.isReachable(index._position), "Invalid index")
assert(handle._isReachable(index._position), "Invalid index")
let pos = handle.index(after: index._position)
return Index(_position: pos)
}
@@ -178,7 +178,7 @@ extension BitSet: Collection, BidirectionalCollection {
/// storage.)
public func index(before index: Index) -> Index {
_read { handle in
assert(handle.isReachable(index._position), "Invalid index")
assert(handle._isReachable(index._position), "Invalid index")
let pos = handle.index(before: index._position)
return Index(_position: pos)
}
@@ -196,8 +196,8 @@ extension BitSet: Collection, BidirectionalCollection {
/// addressed by the two input indices.
public func distance(from start: Index, to end: Index) -> Int {
_read { handle in
assert(handle.isReachable(start._position), "Invalid start index")
assert(handle.isReachable(end._position), "Invalid end index")
assert(handle._isReachable(start._position), "Invalid start index")
assert(handle._isReachable(end._position), "Invalid end index")
return handle.distance(from: start._position, to: end._position)
}
}
@@ -220,7 +220,7 @@ extension BitSet: Collection, BidirectionalCollection {
/// addressed by `index` and the returned result.
public func index(_ index: Index, offsetBy distance: Int) -> Index {
_read { handle in
assert(handle.isReachable(index._position), "Invalid index")
assert(handle._isReachable(index._position), "Invalid index")
let pos = handle.index(index._position, offsetBy: distance)
return Index(_position: pos)
}
@@ -250,8 +250,8 @@ extension BitSet: Collection, BidirectionalCollection {
_ i: Index, offsetBy distance: Int, limitedBy limit: Index
) -> Index? {
_read { handle in
assert(handle.isReachable(i._position), "Invalid index")
assert(handle.isReachable(limit._position), "Invalid limit index")
assert(handle._isReachable(i._position), "Invalid index")
assert(handle._isReachable(limit._position), "Invalid limit index")
return handle.index(
i._position, offsetBy: distance, limitedBy: limit._position
).map { Index(_position: $0) }
@@ -96,7 +96,7 @@ extension BitSet {
public subscript(members bounds: Range<Int>) -> Slice<BitSet> {
let bounds: Range<Index> = _read { handle in
let bounds = bounds._clampedToUInt()
var lower = _BitPosition(bounds.lowerBound)
var lower = _UnsafeBitSet.Index(bounds.lowerBound)
if lower >= handle.endIndex {
lower = handle.endIndex
} else if !handle.contains(lower.value) {
@@ -104,7 +104,7 @@ extension BitSet {
}
assert(lower == handle.endIndex || handle.contains(lower.value))
var upper = _BitPosition(bounds.upperBound)
var upper = _UnsafeBitSet.Index(bounds.upperBound)
if upper <= lower {
upper = lower
} else if upper >= handle.endIndex {
@@ -21,7 +21,7 @@ extension BitSet {
) -> BitSet {
precondition(limit >= 0, "Invalid limit value")
guard limit > 0 else { return BitSet() }
let (w, b) = _BitPosition(limit).endSplit
let (w, b) = _UnsafeHandle.Index(limit).endSplit
var words = (0 ... w).map { _ in _Word(rng.next() as UInt) }
words[w].formIntersection(_Word(upTo: b))
return BitSet(_words: words)
@@ -129,7 +129,7 @@ extension BitSet {
}
let selfCount = self.count
return _UnsafeHandle.withTemporaryBitset(
return _UnsafeHandle.withTemporaryBitSet(
wordCount: _storage.count
) { seen in
var strict = false
@@ -141,7 +141,7 @@ extension BitSet {
continue
}
if seen.insert(UInt(i)) {
c += 1
c &+= 1
if c == selfCount {
while !strict, let i = it.next() {
strict = !self.contains(i)
@@ -108,13 +108,12 @@ extension BitSet {
if S.self == Range<Int>.self {
return isStrictSuperset(of: other as! Range<Int>)
}
return _UnsafeHandle.withTemporaryBitset(
return _UnsafeHandle.withTemporaryBitSet(
wordCount: _storage.count
) { seen in
var c = 0
for i in other {
guard contains(i) else { return false }
if seen.insert(UInt(i)) { c += 1 }
seen.insert(UInt(i))
}
return !_storage.elementsEqual(seen._words)
}
@@ -12,446 +12,30 @@
import _CollectionsUtilities
extension BitSet {
/// An unsafe-unowned bitset view over `UInt` storage, providing bit set
/// primitives.
@usableFromInline
@frozen
internal struct _UnsafeHandle {
/// An unsafe-unowned storage view.
@usableFromInline
internal let _words: UnsafeBufferPointer<_Word>
#if DEBUG
/// True when this handle does not support table mutations.
/// (This is only checked in debug builds.)
@usableFromInline
internal let _mutable: Bool
#endif
@inline(__always)
internal func ensureMutable() {
#if DEBUG
assert(_mutable)
#endif
}
internal var _mutableWords: UnsafeMutableBufferPointer<_Word> {
ensureMutable()
return UnsafeMutableBufferPointer(mutating: _words)
}
@inlinable
@inline(__always)
internal init(
words: UnsafeBufferPointer<_Word>,
mutable: Bool
) {
assert(words.baseAddress != nil)
self._words = words
#if DEBUG
self._mutable = mutable
#endif
}
@inlinable
@inline(__always)
internal init(
words: UnsafeMutableBufferPointer<_Word>,
mutable: Bool
) {
self.init(words: UnsafeBufferPointer(words), mutable: mutable)
}
}
internal typealias _UnsafeHandle = _UnsafeBitSet
}
extension BitSet._UnsafeHandle {
@inlinable
extension _UnsafeBitSet {
@inline(__always)
internal var wordCount: Int {
_words.count
}
@inlinable
internal var _actualCount: Int {
return _words.reduce(0) { $0 + $1.count }
}
}
extension BitSet._UnsafeHandle {
@inlinable
@inline(__always)
static func withTemporaryBitset<R>(
wordCount: Int,
run body: (inout Self) throws -> R
) rethrows -> R {
var result: R?
try _withTemporaryBitset(wordCount: wordCount) { bitset in
result = try body(&bitset)
}
return result!
}
@usableFromInline
@inline(never)
static func _withTemporaryBitset(
wordCount: Int,
run body: (inout Self) throws -> Void
) rethrows {
try _withTemporaryUninitializedBitset(wordCount: wordCount) { handle in
handle._mutableWords.initialize(repeating: .empty)
try body(&handle)
}
}
internal static func _withTemporaryUninitializedBitset(
wordCount: Int,
run body: (inout Self) throws -> Void
) rethrows {
assert(wordCount >= 0)
#if compiler(>=5.6)
return try withUnsafeTemporaryAllocation(
of: _Word.self, capacity: wordCount
) { words in
var bitset = Self(words: words, mutable: true)
return try body(&bitset)
}
#else
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 start = UnsafeMutableRawPointer(p)
.assumingMemoryBound(to: _Word.self)
let words = UnsafeMutableBufferPointer(start: start, count: wordCount)
var bitset = Self(words: words, mutable: true)
return try body(&bitset)
}
}
let words = UnsafeMutableBufferPointer<_Word>.allocate(capacity: wordCount)
defer { words.deallocate() }
var bitset = Self(words: words, mutable: true)
return try body(&bitset)
#endif
}
}
extension BitSet._UnsafeHandle {
@usableFromInline
@_effects(readnone)
@inline(__always)
internal static func wordCount(forCapacity capacity: UInt) -> Int {
_Word.wordCount(forBitCount: capacity)
}
internal var capacity: UInt {
@inline(__always)
get {
UInt(wordCount &* _Word.capacity)
}
}
@inline(__always)
internal func isWithinBounds(_ element: UInt) -> Bool {
element < capacity
}
@inline(__always)
internal func isReachable(_ index: Index) -> Bool {
internal func _isReachable(_ index: Index) -> Bool {
index == endIndex || contains(index.value)
}
}
@inline(__always)
internal func contains(_ element: UInt) -> Bool {
let (word, bit) = Index(element).split
guard word < wordCount else { return false }
return _words[word].contains(bit)
}
internal func emptySuffix() -> Int {
extension _UnsafeBitSet {
internal func _emptySuffix() -> Int {
var i = wordCount - 1
while i >= 0, _words[i].isEmpty {
i -= 1
}
return wordCount - 1 - i
}
@usableFromInline
@_effects(releasenone)
@discardableResult
internal mutating func insert(_ element: UInt) -> Bool {
ensureMutable()
assert(isWithinBounds(element))
let index = Index(element)
return _mutableWords[index.word].insert(index.bit)
}
@discardableResult
internal mutating func remove(_ element: UInt) -> Bool {
ensureMutable()
let index = Index(element)
if index.word >= _words.count { return false }
return _mutableWords[index.word].remove(index.bit)
}
internal mutating func update(_ member: UInt, to newValue: Bool) -> Bool {
ensureMutable()
let (w, b) = _BitPosition(member).split
_mutableWords[w].update(b, to: newValue)
return w == _words.count &- 1
}
}
extension BitSet._UnsafeHandle: Sequence {
@usableFromInline
internal typealias Element = UInt
extension _UnsafeBitSet {
@inlinable
@inline(__always)
internal var underestimatedCount: Int {
return _actualCount // FIXME: really?
}
@inlinable
@inline(__always)
func makeIterator() -> Iterator {
return Iterator(self)
}
@usableFromInline
@frozen
internal struct Iterator: IteratorProtocol {
@usableFromInline
internal typealias _UnsafeHandle = BitSet._UnsafeHandle
@usableFromInline
internal let bitset: _UnsafeHandle
@usableFromInline
internal var index: Int
@usableFromInline
internal var word: _Word
@inlinable
internal init(_ bitset: _UnsafeHandle) {
self.bitset = bitset
self.index = 0
self.word = bitset.wordCount > 0 ? bitset._words[0] : .empty
}
@usableFromInline
@_effects(releasenone)
internal mutating func next() -> UInt? {
if let bit = word.next() {
return Index(word: index, bit: bit).value
}
while (index + 1) < bitset.wordCount {
index += 1
word = bitset._words[index]
if let bit = word.next() {
return Index(word: index, bit: bit).value
}
}
return nil
}
}
}
extension BitSet._UnsafeHandle: BidirectionalCollection {
@usableFromInline
internal typealias Index = _BitPosition
@inlinable
@inline(__always)
internal var count: Int {
_actualCount
}
@inlinable
@inline(__always)
internal var isEmpty: Bool {
_words.firstIndex(where: { !$0.isEmpty }) == nil
}
@inlinable
internal var startIndex: Index {
let word = _words.firstIndex { !$0.isEmpty }
guard let word = word else { return endIndex }
return Index(word: word, bit: _words[word].firstMember!)
}
@inlinable
internal var endIndex: Index {
Index(word: wordCount, bit: 0)
}
@inlinable
internal subscript(position: Index) -> UInt {
position.value
}
@usableFromInline
internal func index(after index: Index) -> Index {
precondition(index < endIndex, "Index out of bounds")
var word = index.word
var w = _words[word]
w.removeAll(through: index.bit)
while w.isEmpty {
word += 1
guard word < wordCount else {
return Index(word: wordCount, bit: 0)
}
w = _words[word]
}
return Index(word: word, bit: w.firstMember!)
}
@usableFromInline
internal func index(before index: Index) -> Index {
precondition(index <= endIndex, "Index out of bounds")
var word = index.word
var w: _Word
if index.bit > 0 {
w = _words[word]
w.removeAll(from: index.bit)
} else {
w = .empty
}
while w.isEmpty {
word -= 1
precondition(word >= 0, "Can't advance below startIndex")
w = _words[word]
}
return Index(word: word, bit: w.lastMember!)
}
@usableFromInline
internal func distance(from start: Index, to end: Index) -> Int {
precondition(start <= endIndex && end <= endIndex, "Index out of bounds")
let isNegative = end < start
let (start, end) = (Swift.min(start, end), Swift.max(start, end))
let (w1, b1) = start.split
let (w2, b2) = end.split
if w1 == w2 {
guard w1 < wordCount else { return 0 }
let mask = _Word(from: b1, to: b2)
let c = _words[w1].intersection(mask).count
return isNegative ? -c : c
}
var c = 0
var w = w1
guard w < wordCount else { return 0 }
c &+= _words[w].subtracting(_Word(upTo: b1)).count
w &+= 1
while w < w2 {
c &+= _words[w].count
w &+= 1
}
guard w < wordCount else { return isNegative ? -c : c }
c &+= _words[w].intersection(_Word(upTo: b2)).count
return isNegative ? -c : c
}
@usableFromInline
internal func index(_ i: Index, offsetBy distance: Int) -> Index {
precondition(i <= endIndex, "Index out of bounds")
precondition(i == endIndex || contains(i.value), "Invalid index")
guard distance != 0 else { return i }
var remaining = distance.magnitude
if distance > 0 {
var (w, b) = i.split
precondition(w < wordCount, "Index out of bounds")
if let v = _words[w].subtracting(_Word(upTo: b)).nthElement(&remaining) {
return Index(word: w, bit: v)
}
while true {
w &+= 1
guard w < wordCount else { break }
if let v = _words[w].nthElement(&remaining) {
return Index(word: w, bit: v)
}
}
precondition(remaining == 0, "Index out of bounds")
return endIndex
}
// distance < 0
remaining -= 1
var (w, b) = i.endSplit
if w < wordCount {
if let v = _words[w].intersection(_Word(upTo: b)).nthElementFromEnd(&remaining) {
return Index(word: w, bit: v)
}
}
while true {
precondition(w > 0, "Index out of bounds")
w &-= 1
if let v = _words[w].nthElementFromEnd(&remaining) {
return Index(word: w, bit: v)
}
}
}
@usableFromInline
internal func index(
_ i: Index, offsetBy distance: Int, limitedBy limit: Index
) -> Index? {
precondition(i <= endIndex && limit <= endIndex, "Index out of bounds")
precondition(i == endIndex || contains(i.value), "Invalid index")
guard distance != 0 else { return i }
var remaining = distance.magnitude
if distance > 0 {
guard i <= limit else {
return self.index(i, offsetBy: distance)
}
var (w, b) = i.split
if w < wordCount,
let v = _words[w].subtracting(_Word(upTo: b)).nthElement(&remaining)
{
let r = Index(word: w, bit: v)
return r <= limit ? r : nil
}
let maxWord = Swift.min(wordCount - 1, limit.word)
while w < maxWord {
w &+= 1
if let v = _words[w].nthElement(&remaining) {
let r = Index(word: w, bit: v)
return r <= limit ? r : nil
}
}
return remaining == 0 && limit == endIndex ? endIndex : nil
}
// distance < 0
guard i >= limit else {
return self.index(i, offsetBy: distance)
}
remaining &-= 1
var (w, b) = i.endSplit
if w < wordCount {
if let v = _words[w].intersection(_Word(upTo: b)).nthElementFromEnd(&remaining) {
let r = Index(word: w, bit: v)
return r >= limit ? r : nil
}
}
let minWord = limit.word
while w > minWord {
w &-= 1
if let v = _words[w].nthElementFromEnd(&remaining) {
let r = Index(word: w, bit: v)
return r >= limit ? r : nil
}
}
return nil
}
}
extension BitSet._UnsafeHandle {
internal mutating func combineSharedPrefix(
public mutating func combineSharedPrefix(
with other: Self,
using function: (inout _Word, _Word) -> Void
) {
@@ -463,8 +47,9 @@ extension BitSet._UnsafeHandle {
}
}
extension BitSet._UnsafeHandle {
internal mutating func formUnion(_ range: Range<UInt>) {
extension _UnsafeBitSet {
@_effects(releasenone)
public mutating func formUnion(_ range: Range<UInt>) {
ensureMutable()
let l = Index(range.lowerBound)
let u = Index(range.upperBound)
@@ -485,7 +70,8 @@ extension BitSet._UnsafeHandle {
}
}
internal mutating func formIntersection(_ range: Range<UInt>) {
@_effects(releasenone)
public mutating func formIntersection(_ range: Range<UInt>) {
ensureMutable()
let l = Index(Swift.min(range.lowerBound, capacity))
let u = Index(Swift.min(range.upperBound, capacity))
@@ -509,7 +95,8 @@ extension BitSet._UnsafeHandle {
}
}
internal mutating func formSymmetricDifference(_ range: Range<UInt>) {
@_effects(releasenone)
public mutating func formSymmetricDifference(_ range: Range<UInt>) {
ensureMutable()
let l = Index(range.lowerBound)
let u = Index(range.upperBound)
@@ -531,7 +118,8 @@ extension BitSet._UnsafeHandle {
}
}
internal mutating func subtract(_ range: Range<UInt>) {
@_effects(releasenone)
public mutating func subtract(_ range: Range<UInt>) {
ensureMutable()
let l = Index(Swift.min(range.lowerBound, capacity))
let u = Index(Swift.min(range.upperBound, capacity))
@@ -550,7 +138,8 @@ extension BitSet._UnsafeHandle {
}
}
internal func isDisjoint(with range: Range<UInt>) -> Bool {
@_effects(releasenone)
public func isDisjoint(with range: Range<UInt>) -> Bool {
if self.isEmpty { return true }
let lower = Index(Swift.min(range.lowerBound, capacity))
let upper = Index(Swift.min(range.upperBound, capacity))
@@ -575,7 +164,8 @@ extension BitSet._UnsafeHandle {
return true
}
internal func isSubset(of range: Range<UInt>) -> Bool {
@_effects(releasenone)
public func isSubset(of range: Range<UInt>) -> Bool {
guard !range.isEmpty else { return isEmpty }
guard !_words.isEmpty else { return true }
let r = range.clamped(to: 0 ..< UInt(capacity))
@@ -600,7 +190,8 @@ extension BitSet._UnsafeHandle {
return true
}
internal func isSuperset(of range: Range<UInt>) -> Bool {
@_effects(releasenone)
public func isSuperset(of range: Range<UInt>) -> Bool {
guard !range.isEmpty else { return true }
let r = range.clamped(to: 0 ..< UInt(capacity))
guard r == range else { return false }
@@ -624,7 +215,8 @@ extension BitSet._UnsafeHandle {
return _words[upper.word].intersection(uw) == uw
}
internal func isEqualSet(to range: Range<UInt>) -> Bool {
@_effects(releasenone)
public func isEqualSet(to range: Range<UInt>) -> Bool {
if range.isEmpty { return self.isEmpty }
let r = range.clamped(to: 0 ..< UInt(capacity))
guard r == range else { return false }
@@ -653,3 +245,4 @@ extension BitSet._UnsafeHandle {
return _words[upper.word] == uw
}
}
+3 -1
View File
@@ -9,6 +9,8 @@
//
//===----------------------------------------------------------------------===//
import _CollectionsUtilities
/// A sorted collection of small nonnegative integers, implemented as an
/// uncompressed bitmap of as many bits as the value of the largest member.
///
@@ -65,7 +67,7 @@ extension BitSet {
}
internal mutating func _shrink() {
let suffix = _read { $0.emptySuffix() }
let suffix = _read { $0._emptySuffix() }
if suffix > 0 { _storage.removeLast(suffix) }
}
+6 -290
View File
@@ -12,291 +12,7 @@
import _CollectionsUtilities
@usableFromInline
@frozen
internal struct _Word {
@usableFromInline
internal var value: UInt
@inlinable
@inline(__always)
internal init(_ value: UInt) {
self.value = value
}
@inline(__always)
internal init(upTo bit: UInt) {
assert(bit <= _Word.capacity)
self.init((1 << bit) &- 1)
}
@inline(__always)
internal init(from start: UInt, to end: UInt) {
assert(start <= end && end <= _Word.capacity)
self = Self(upTo: end).symmetricDifference(Self(upTo: start))
}
}
extension _Word: CustomStringConvertible {
@usableFromInline
internal var description: String {
String(value, radix: 16)
}
}
extension _Word {
/// Returns the `n`th member in `self`.
///
/// - Parameter n: The offset of the element to retrieve. This value is
/// decremented by the number of items found in this `self` towards the
/// value we're looking for. (If the function returns non-nil, then `n`
/// is set to `0` on return.)
/// - Returns: If this word contains enough members to satisfy the request,
/// then this function returns the member found. Otherwise it returns nil.
@inline(never)
internal func nthElement(_ n: inout UInt) -> UInt? {
value._rank(ofBit: &n)
}
@inline(never)
internal func nthElementFromEnd(_ n: inout UInt) -> UInt? {
guard let i = value._reversed._rank(ofBit: &n) else { return nil }
return UInt(UInt.bitWidth) &- 1 &- i
}
}
extension _Word {
@inline(__always)
internal static func wordCount(forBitCount count: UInt) -> Int {
return _BitPosition(count + UInt(_Word.capacity) - 1).word
}
}
extension _Word {
@inlinable
@inline(__always)
internal static var capacity: Int {
return UInt.bitWidth
}
@inlinable
@inline(__always)
internal var count: Int {
value.nonzeroBitCount
}
@inlinable
@inline(__always)
internal var isEmpty: Bool {
value == 0
}
@inlinable
@inline(__always)
internal var isFull: Bool {
value == UInt.max
}
@inlinable
@inline(__always)
internal func contains(_ bit: UInt) -> Bool {
assert(bit >= 0 && bit < UInt.bitWidth)
return value & (1 &<< bit) != 0
}
@inlinable
@inline(__always)
internal var firstMember: UInt? {
value._lastSetBit
}
@inlinable
@inline(__always)
internal var lastMember: UInt? {
value._firstSetBit
}
@inlinable
@inline(__always)
@discardableResult
internal mutating func insert(_ bit: UInt) -> Bool {
assert(bit < UInt.bitWidth)
let mask: UInt = 1 &<< bit
let inserted = value & mask == 0
value |= mask
return inserted
}
@inlinable
@inline(__always)
@discardableResult
internal mutating func remove(_ bit: UInt) -> Bool {
assert(bit < UInt.bitWidth)
let mask: UInt = 1 &<< bit
let removed = (value & mask) != 0
value &= ~mask
return removed
}
@inlinable
@inline(__always)
internal mutating func update(_ bit: UInt, to value: Bool) {
assert(bit < UInt.bitWidth)
let mask: UInt = 1 &<< bit
if value {
self.value |= mask
} else {
self.value &= ~mask
}
}
}
extension _Word {
@inlinable
@inline(__always)
internal mutating func insertAll(upTo bit: UInt) {
assert(bit >= 0 && bit < Self.capacity)
let mask: UInt = (1 as UInt &<< bit) &- 1
value |= mask
}
@inlinable
@inline(__always)
internal mutating func removeAll(upTo bit: UInt) {
assert(bit >= 0 && bit < Self.capacity)
let mask = UInt.max &<< bit
value &= mask
}
@inlinable
@inline(__always)
internal mutating func removeAll(through bit: UInt) {
assert(bit >= 0 && bit < Self.capacity)
var mask = UInt.max &<< bit
mask &= mask &- 1 // Clear lowest nonzero bit.
value &= mask
}
@inlinable
@inline(__always)
internal mutating func removeAll(from bit: UInt) {
assert(bit >= 0 && bit < Self.capacity)
let mask: UInt = (1 as UInt &<< bit) &- 1
value &= mask
}
}
extension _Word {
@inlinable
@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 _Word: Sequence, IteratorProtocol {
@inlinable
internal var underestimatedCount: Int {
count
}
/// Return the index of the lowest set bit in this word,
/// and also destructively clear it.
@inlinable
internal mutating func next() -> UInt? {
guard value != 0 else { return nil }
let bit = UInt(truncatingIfNeeded: value.trailingZeroBitCount)
value &= value &- 1 // Clear lowest nonzero bit.
return bit
}
}
extension _Word: Equatable {
@inlinable
internal static func ==(left: Self, right: Self) -> Bool {
left.value == right.value
}
}
extension _Word: Hashable {
@inlinable
internal func hash(into hasher: inout Hasher) {
hasher.combine(value)
}
}
extension _Word {
@inline(__always)
internal func complement() -> Self {
_Word(~self.value)
}
@inline(__always)
internal mutating func formComplement() {
self.value = ~self.value
}
@inline(__always)
internal func union(_ other: Self) -> Self {
_Word(self.value | other.value)
}
@inline(__always)
internal mutating func formUnion(_ other: Self) {
self.value |= other.value
}
@inline(__always)
internal func intersection(_ other: Self) -> Self {
_Word(self.value & other.value)
}
@inline(__always)
internal mutating func formIntersection(_ other: Self) {
self.value &= other.value
}
@inline(__always)
internal func symmetricDifference(_ other: Self) -> Self {
_Word(self.value ^ other.value)
}
@inline(__always)
internal mutating func formSymmetricDifference(_ other: Self) {
self.value ^= other.value
}
@inline(__always)
internal func subtracting(_ other: Self) -> Self {
_Word(self.value & ~other.value)
}
@inline(__always)
internal mutating func subtract(_ other: Self) {
self.value &= ~other.value
}
}
extension _Word {
@inline(__always)
internal func shiftedDown(by shift: UInt) -> Self {
assert(shift >= 0 && shift < Self.capacity)
return _Word(self.value &>> shift)
}
@inline(__always)
internal func shiftedUp(by shift: UInt) -> Self {
assert(shift >= 0 && shift < Self.capacity)
return _Word(self.value &<< shift)
}
}
internal typealias _Word = _UnsafeBitSet._Word
extension Array where Element == _Word {
internal func _encodeAsUInt64(
@@ -331,24 +47,24 @@ extension Array where Element == _Word {
reservingCount count: Int? = nil
) throws {
self = []
if _Word.capacity == 64 {
if Element.capacity == 64 {
if let c = count {
self.reserveCapacity(c)
}
while !container.isAtEnd {
let v = try container.decode(UInt64.self)
self.append(_Word(UInt(truncatingIfNeeded: v)))
self.append(Element(UInt(truncatingIfNeeded: v)))
}
return
}
assert(_Word.capacity == 32, "Unsupported platform")
assert(Element.capacity == 32, "Unsupported platform")
if let c = count {
self.reserveCapacity(2 * c)
}
while !container.isAtEnd {
let v = try container.decode(UInt64.self)
self.append(_Word(UInt(truncatingIfNeeded: v)))
self.append(_Word(UInt(truncatingIfNeeded: v &>> 32)))
self.append(Element(UInt(truncatingIfNeeded: v)))
self.append(Element(UInt(truncatingIfNeeded: v &>> 32)))
}
}
}
+1 -1
View File
@@ -68,7 +68,7 @@ add_library(OrderedCollections
"OrderedSet/OrderedSet+UnorderedView.swift"
"OrderedSet/OrderedSet+UnstableInternals.swift"
"OrderedSet/OrderedSet.swift"
"Utilities/_UnsafeBitset.swift"
"Utilities/_UnsafeBitSet.swift"
)
target_link_libraries(OrderedCollections PRIVATE
_CollectionsUtilities)
@@ -93,15 +93,13 @@ extension OrderedSet {
public __consuming func intersection<S: Sequence>(
_ other: S
) -> Self where S.Element == Element {
_UnsafeBitset.withTemporaryBitset(capacity: self.count) { bitset in
_UnsafeBitSet.withTemporaryBitSet(capacity: self.count) { bitset in
for item in other {
if let index = self._find_inlined(item).index {
bitset.insert(index)
}
}
let result = self._extractSubset(using: bitset)
result._checkInvariants()
return result
return self._extractSubset(using: bitset)
}
}
}
@@ -69,12 +69,15 @@ extension OrderedSet {
return seen == self.count
}
return _UnsafeBitset.withTemporaryBitset(capacity: count) { seen in
return _UnsafeBitSet.withTemporaryBitSet(capacity: count) { seen in
var c = 0
for item in other {
guard let index = _find(item).index else { return false }
_ = seen.insert(index) // Ignore dupes
if seen.insert(index) {
c &+= 1
}
}
return seen.count == count
return c == count
}
}
}
@@ -134,17 +134,21 @@ extension OrderedSet {
return !other.allSatisfy { self.contains($0) }
}
return _UnsafeBitset.withTemporaryBitset(capacity: count) { seen in
return _UnsafeBitSet.withTemporaryBitSet(capacity: count) { seen in
// Mark elements in `self` that we've seen in `other`.
var isKnownStrict = false
var c = 0
for item in other {
if let index = _find(item).index {
if seen.insert(index), seen.count == self.count, isKnownStrict {
// We've seen enough.
return true
if seen.insert(index) {
c &+= 1
if c == self.count, isKnownStrict {
// We've seen enough.
return true
}
}
} else {
if !isKnownStrict, seen.count == self.count { return true }
if !isKnownStrict, c == self.count { return true }
isKnownStrict = true
}
}
@@ -134,18 +134,22 @@ extension OrderedSet {
return false
}
return _UnsafeBitset.withTemporaryBitset(capacity: count) { seen in
return _UnsafeBitSet.withTemporaryBitSet(capacity: count) { seen in
// Mark elements in `self` that we've seen in `other`.
var c = 0
for item in other {
guard let index = _find(item).index else {
return false
}
if seen.insert(index), seen.count == self.count {
// We've seen enough.
return false
if seen.insert(index) {
c &+= 1
if c == self.count {
// We've seen enough.
return false
}
}
}
return seen.count < self.count
return c < self.count
}
}
}
@@ -131,13 +131,17 @@ extension OrderedSet {
return true
}
return _UnsafeBitset.withTemporaryBitset(capacity: count) { seen in
return _UnsafeBitSet.withTemporaryBitSet(capacity: count) { seen in
// Mark elements in `self` that we've seen in `other`.
var c = 0
for item in other {
if let index = _find(item).index {
if seen.insert(index), seen.count == self.count {
// We've seen enough.
return true
if seen.insert(index) {
c &+= 1
if c == self.count {
// We've seen enough.
return true
}
}
}
}
@@ -90,19 +90,21 @@ extension OrderedSet {
_ other: S
) -> Self where S.Element == Element {
guard count > 0 else { return Self() }
return _UnsafeBitset.withTemporaryBitset(capacity: count) { difference in
return _UnsafeBitSet.withTemporaryBitSet(capacity: count) { difference in
difference.insertAll(upTo: count)
var c = count
for item in other {
if let index = self._find(item).index {
if difference.remove(index), difference.count == 0 {
return Self()
if difference.remove(index) {
c &-= 1
if c == 0 {
return Self()
}
}
}
}
assert(difference.count > 0)
let result = _extractSubset(using: difference)
result._checkInvariants()
return result
assert(c > 0)
return _extractSubset(using: difference, count: c)
}
}
}
@@ -37,8 +37,8 @@ extension OrderedSet {
/// `Element` implements high-quality hashing.
@inlinable
public __consuming func symmetricDifference(_ other: __owned Self) -> Self {
_UnsafeBitset.withTemporaryBitset(capacity: self.count) { bitset1 in
_UnsafeBitset.withTemporaryBitset(capacity: other.count) { bitset2 in
_UnsafeBitSet.withTemporaryBitSet(capacity: self.count) { bitset1 in
_UnsafeBitSet.withTemporaryBitSet(capacity: other.count) { bitset2 in
bitset1.insertAll(upTo: self.count)
for item in other {
if let index = self._find(item).index {
@@ -54,7 +54,7 @@ extension OrderedSet {
var result = self._extractSubset(using: bitset1,
extraCapacity: bitset2.count)
for offset in bitset2 {
result._appendNew(other._elements[offset])
result._appendNew(other._elements[Int(bitPattern: offset)])
}
result._checkInvariants()
return result
@@ -112,7 +112,7 @@ extension OrderedSet {
public __consuming func symmetricDifference<S: Sequence>(
_ other: __owned S
) -> Self where S.Element == Element {
_UnsafeBitset.withTemporaryBitset(capacity: self.count) { bitset in
_UnsafeBitSet.withTemporaryBitSet(capacity: self.count) { bitset in
var new = Self()
bitset.insertAll(upTo: self.count)
for item in other {
@@ -477,24 +477,27 @@ extension OrderedSet {
@inlinable
@inline(never)
internal __consuming func _extractSubset(
using bitset: _UnsafeBitset,
using bitset: _UnsafeBitSet,
count: Int? = nil,
extraCapacity: Int = 0
) -> Self {
assert(bitset.count == 0 || bitset.max()! <= count)
if bitset.count == 0 { return Self(minimumCapacity: extraCapacity) }
if bitset.count == self.count {
let c = count ?? bitset.count
assert(c == 0 || bitset.max()! <= self.count)
if c == 0 { return Self(minimumCapacity: extraCapacity) }
if c == self.count {
if extraCapacity <= self._capacity - self.count {
return self
}
var copy = self
copy.reserveCapacity(count + extraCapacity)
copy.reserveCapacity(c + extraCapacity)
return copy
}
var result = Self(minimumCapacity: bitset.count + extraCapacity)
var result = Self(minimumCapacity: c + extraCapacity)
for offset in bitset {
result._appendNew(_elements[offset])
result._appendNew(_elements[Int(bitPattern: offset)])
}
assert(result.count == bitset.count)
assert(result.count == c)
result._checkInvariants()
return result
}
}
@@ -545,13 +548,11 @@ extension OrderedSet {
public func filter(
_ isIncluded: (Element) throws -> Bool
) rethrows -> Self {
try _UnsafeBitset.withTemporaryBitset(capacity: self.count) { bitset in
try _UnsafeBitSet.withTemporaryBitSet(capacity: self.count) { bitset in
for i in _elements.indices where try isIncluded(_elements[i]) {
bitset.insert(i)
}
let result = self._extractSubset(using: bitset)
result._checkInvariants()
return result
return self._extractSubset(using: bitset)
}
}
}
@@ -11,387 +11,6 @@
import _CollectionsUtilities
/// 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.
@usableFromInline
@frozen
internal struct _UnsafeBitset {
@usableFromInline
internal let _words: UnsafeMutableBufferPointer<Word>
internal typealias _UnsafeBitSet = _CollectionsUtilities._UnsafeBitSet
@usableFromInline
internal var _count: Int
@inlinable
@inline(__always)
internal init(words: UnsafeMutableBufferPointer<Word>, count: Int) {
self._words = words
self._count = count
}
@inlinable
@inline(__always)
internal init(words: UnsafeMutablePointer<Word>, wordCount: Int, count: Int) {
self._words = UnsafeMutableBufferPointer(start: words, count: wordCount)
self._count = count
}
@inlinable
@inline(__always)
internal var count: Int {
_count
}
}
extension _UnsafeBitset {
@usableFromInline
internal var _actualCount: Int {
return _words.reduce(0) { $0 + $1.count }
}
}
extension _UnsafeBitset {
@inlinable
@inline(__always)
static func withTemporaryBitset<R>(
capacity: Int,
run body: (inout _UnsafeBitset) throws -> R
) rethrows -> R {
var result: R?
try _withTemporaryBitset(capacity: capacity) { bitset in
result = try body(&bitset)
}
return result!
}
@usableFromInline
@inline(never)
static func _withTemporaryBitset(
capacity: Int,
run body: (inout _UnsafeBitset) throws -> Void
) rethrows {
let wordCount = _UnsafeBitset.wordCount(forCapacity: capacity)
#if compiler(>=5.6)
return try withUnsafeTemporaryAllocation(
of: Word.self, capacity: wordCount
) { words in
words.initialize(repeating: .empty)
var bitset = Self(words: words, count: 0)
return try body(&bitset)
}
#else
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)
#endif
}
}
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 {
@usableFromInline
@_effects(readnone)
@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)
}
@usableFromInline
@_effects(releasenone)
@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
}
@usableFromInline
@_effects(releasenone)
@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
}
@usableFromInline
@_effects(releasenone)
internal mutating func clear() {
guard _words.count > 0 else { return }
_words.baseAddress!.update(repeating: .empty, count: _words.count)
_count = 0
}
@usableFromInline
@_effects(releasenone)
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)
}
}
@usableFromInline
@_effects(releasenone)
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 {
@usableFromInline
internal typealias Element = Int
@inlinable
@inline(__always)
internal var underestimatedCount: Int {
return count
}
@inlinable
@inline(__always)
func makeIterator() -> Iterator {
return Iterator(self)
}
@usableFromInline
@frozen
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
}
@usableFromInline
@_effects(releasenone)
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 {
@usableFromInline
@frozen
internal struct Word {
@usableFromInline
internal var value: UInt
@inlinable
@inline(__always)
internal init(_ value: UInt) {
self.value = value
}
}
}
extension _UnsafeBitset.Word {
@inlinable
@inline(__always)
internal static var capacity: Int {
return UInt.bitWidth
}
@inlinable
@inline(__always)
internal var count: Int {
value.nonzeroBitCount
}
@inlinable
@inline(__always)
internal var isEmpty: Bool {
value == 0
}
@inlinable
@inline(__always)
internal func contains(_ bit: Int) -> Bool {
assert(bit >= 0 && bit < UInt.bitWidth)
return value & (1 &<< bit) != 0
}
@inlinable
@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
}
@inlinable
@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 {
@inlinable
@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
}
@inlinable
@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 {
@inlinable
@inline(__always)
internal static var empty: Self {
Self(0)
}
@inlinable
@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 {
@inlinable
internal var underestimatedCount: Int {
count
}
/// Return the index of the lowest set bit in this word,
/// and also destructively clear it.
@inlinable
internal mutating func next() -> Int? {
guard value != 0 else { return nil }
let bit = value.trailingZeroBitCount
value &= value &- 1 // Clear lowest nonzero bit.
return bit
}
}
@@ -9,48 +9,53 @@
//
//===----------------------------------------------------------------------===//
@usableFromInline
@frozen
internal struct _BitPosition: Comparable, Hashable {
@usableFromInline
internal var value: UInt
extension _UnsafeBitSet {
@frozen
public struct Index: Comparable, Hashable {
@usableFromInline
internal typealias _Word = _UnsafeBitSet._Word
@inlinable
internal init(_ value: UInt) {
self.value = value
public var value: UInt
@inlinable
public init(_ value: UInt) {
self.value = value
}
@inlinable
public init(_ value: Int) {
self.value = UInt(value)
}
@inlinable
public init(word: Int, bit: UInt) {
assert(word >= 0 && word <= Int.max / _Word.capacity)
assert(bit < _Word.capacity)
self.value = UInt(word &* _Word.capacity) &+ bit
}
}
}
extension _UnsafeBitSet.Index {
@inlinable
internal init(_ value: Int) {
self.value = UInt(value)
}
@inlinable
internal init(word: Int, bit: UInt) {
assert(word >= 0 && word <= Int.max / _Word.capacity)
assert(bit < _Word.capacity)
self.value = UInt(word &* _Word.capacity) &+ bit
}
@inlinable
internal var word: Int {
public var word: Int {
// Note: We perform on UInts to get faster unsigned math (shifts).
Int(truncatingIfNeeded: value / UInt(bitPattern: _Word.capacity))
}
@inlinable
internal var bit: UInt {
public var bit: UInt {
// Note: We perform on UInts to get faster unsigned math (masking).
value % UInt(bitPattern: _Word.capacity)
}
@inlinable
internal var split: (word: Int, bit: UInt) {
public var split: (word: Int, bit: UInt) {
(word, bit)
}
@inlinable
internal var endSplit: (word: Int, bit: UInt) {
public var endSplit: (word: Int, bit: UInt) {
let w = word
let b = bit
if w > 0, b == 0 { return (w &- 1, UInt(_Word.capacity)) }
@@ -58,27 +63,27 @@ internal struct _BitPosition: Comparable, Hashable {
}
@inlinable
static func ==(left: Self, right: Self) -> Bool {
public static func ==(left: Self, right: Self) -> Bool {
left.value == right.value
}
@inlinable
static func <(left: Self, right: Self) -> Bool {
public static func <(left: Self, right: Self) -> Bool {
left.value < right.value
}
@inlinable
func hash(into hasher: inout Hasher) {
public func hash(into hasher: inout Hasher) {
hasher.combine(value)
}
@inlinable
func successor() -> Self {
internal func _successor() -> Self {
Self(value + 1)
}
@inlinable
func predecessor() -> Self {
internal func _predecessor() -> Self {
Self(value - 1)
}
}
@@ -0,0 +1,317 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension _UnsafeBitSet {
@frozen
public struct _Word {
public var value: UInt
@inlinable
@inline(__always)
public init(_ value: UInt) {
self.value = value
}
@inlinable
@inline(__always)
public init(upTo bit: UInt) {
assert(bit <= _Word.capacity)
self.init((1 << bit) &- 1)
}
@inlinable
@inline(__always)
public init(from start: UInt, to end: UInt) {
assert(start <= end && end <= _Word.capacity)
self = Self(upTo: end).symmetricDifference(Self(upTo: start))
}
}
}
extension _UnsafeBitSet._Word: CustomStringConvertible {
public var description: String {
String(value, radix: 16)
}
}
extension _UnsafeBitSet._Word {
/// Returns the `n`th member in `self`.
///
/// - Parameter n: The offset of the element to retrieve. This value is
/// decremented by the number of items found in this `self` towards the
/// value we're looking for. (If the function returns non-nil, then `n`
/// is set to `0` on return.)
/// - Returns: If this word contains enough members to satisfy the request,
/// then this function returns the member found. Otherwise it returns nil.
@inline(never)
internal func nthElement(_ n: inout UInt) -> UInt? {
let c = UInt(bitPattern: count)
guard n < c else {
n &-= c
return nil
}
let m = Int(bitPattern: n)
n = 0
return value._bit(ranked: m)!
}
@inline(never)
internal func nthElementFromEnd(_ n: inout UInt) -> UInt? {
let c = UInt(bitPattern: count)
guard n < c else {
n &-= c
return nil
}
let m = Int(bitPattern: c &- 1 &- n)
n = 0
return value._bit(ranked: m)!
}
}
extension _UnsafeBitSet._Word {
@inlinable
@inline(__always)
public static func wordCount(forBitCount count: UInt) -> Int {
// Note: We perform on UInts to get faster unsigned math (shifts).
let width = UInt(bitPattern: Self.capacity)
return Int(bitPattern: (count + width - 1) / width)
}
}
extension _UnsafeBitSet._Word {
@inlinable
@inline(__always)
public static var capacity: Int {
return UInt.bitWidth
}
@inlinable
@inline(__always)
public var count: Int {
value.nonzeroBitCount
}
@inlinable
@inline(__always)
public var isEmpty: Bool {
value == 0
}
@inlinable
@inline(__always)
public var isFull: Bool {
value == UInt.max
}
@inlinable
@inline(__always)
public func contains(_ bit: UInt) -> Bool {
assert(bit >= 0 && bit < UInt.bitWidth)
return value & (1 &<< bit) != 0
}
@inlinable
@inline(__always)
public var firstMember: UInt? {
value._lastSetBit
}
@inlinable
@inline(__always)
public var lastMember: UInt? {
value._firstSetBit
}
@inlinable
@inline(__always)
@discardableResult
public mutating func insert(_ bit: UInt) -> Bool {
assert(bit < UInt.bitWidth)
let mask: UInt = 1 &<< bit
let inserted = value & mask == 0
value |= mask
return inserted
}
@inlinable
@inline(__always)
@discardableResult
public mutating func remove(_ bit: UInt) -> Bool {
assert(bit < UInt.bitWidth)
let mask: UInt = 1 &<< bit
let removed = (value & mask) != 0
value &= ~mask
return removed
}
@inlinable
@inline(__always)
public mutating func update(_ bit: UInt, to value: Bool) {
assert(bit < UInt.bitWidth)
let mask: UInt = 1 &<< bit
if value {
self.value |= mask
} else {
self.value &= ~mask
}
}
}
extension _UnsafeBitSet._Word {
@inlinable
@inline(__always)
internal mutating func insertAll(upTo bit: UInt) {
assert(bit >= 0 && bit < Self.capacity)
let mask: UInt = (1 as UInt &<< bit) &- 1
value |= mask
}
@inlinable
@inline(__always)
internal mutating func removeAll(upTo bit: UInt) {
assert(bit >= 0 && bit < Self.capacity)
let mask = UInt.max &<< bit
value &= mask
}
@inlinable
@inline(__always)
internal mutating func removeAll(through bit: UInt) {
assert(bit >= 0 && bit < Self.capacity)
var mask = UInt.max &<< bit
mask &= mask &- 1 // Clear lowest nonzero bit.
value &= mask
}
@inlinable
@inline(__always)
internal mutating func removeAll(from bit: UInt) {
assert(bit >= 0 && bit < Self.capacity)
let mask: UInt = (1 as UInt &<< bit) &- 1
value &= mask
}
}
extension _UnsafeBitSet._Word {
@inlinable
@inline(__always)
public static var empty: Self {
Self(0)
}
@inline(__always)
public 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 {
@inlinable @inline(__always)
public var underestimatedCount: Int {
count
}
/// Return the index of the lowest set bit in this word,
/// and also destructively clear it.
@inlinable
public mutating func next() -> UInt? {
guard value != 0 else { return nil }
let bit = UInt(truncatingIfNeeded: value.trailingZeroBitCount)
value &= value &- 1 // Clear lowest nonzero bit.
return bit
}
}
extension _UnsafeBitSet._Word: Equatable {
@inlinable
public static func ==(left: Self, right: Self) -> Bool {
left.value == right.value
}
}
extension _UnsafeBitSet._Word: Hashable {
@inlinable
public func hash(into hasher: inout Hasher) {
hasher.combine(value)
}
}
extension _UnsafeBitSet._Word {
@inline(__always)
public func complement() -> Self {
Self(~self.value)
}
@inline(__always)
public mutating func formComplement() {
self.value = ~self.value
}
@inline(__always)
public func union(_ other: Self) -> Self {
Self(self.value | other.value)
}
@inline(__always)
public mutating func formUnion(_ other: Self) {
self.value |= other.value
}
@inline(__always)
public func intersection(_ other: Self) -> Self {
Self(self.value & other.value)
}
@inline(__always)
public mutating func formIntersection(_ other: Self) {
self.value &= other.value
}
@inline(__always)
public func symmetricDifference(_ other: Self) -> Self {
Self(self.value ^ other.value)
}
@inline(__always)
public mutating func formSymmetricDifference(_ other: Self) {
self.value ^= other.value
}
@inline(__always)
public func subtracting(_ other: Self) -> Self {
Self(self.value & ~other.value)
}
@inline(__always)
public mutating func subtract(_ other: Self) {
self.value &= ~other.value
}
}
extension _UnsafeBitSet._Word {
@inlinable
@inline(__always)
public func shiftedDown(by shift: UInt) -> Self {
assert(shift >= 0 && shift < Self.capacity)
return Self(self.value &>> shift)
}
@inlinable
@inline(__always)
public func shiftedUp(by shift: UInt) -> Self {
assert(shift >= 0 && shift < Self.capacity)
return Self(self.value &<< shift)
}
}
@@ -0,0 +1,466 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
/// An unsafe-unowned bitset view over `UInt` storage, providing bit set
/// primitives.
@frozen
public struct _UnsafeBitSet {
/// An unsafe-unowned storage view.
public let _words: UnsafeBufferPointer<_Word>
#if DEBUG
/// True when this handle does not support table mutations.
/// (This is only checked in debug builds.)
@usableFromInline
internal let _mutable: Bool
#endif
@inlinable
@inline(__always)
public func ensureMutable() {
#if DEBUG
assert(_mutable)
#endif
}
@inlinable
@inline(__always)
public var _mutableWords: UnsafeMutableBufferPointer<_Word> {
ensureMutable()
return UnsafeMutableBufferPointer(mutating: _words)
}
@inlinable
@inline(__always)
public init(
words: UnsafeBufferPointer<_Word>,
mutable: Bool
) {
assert(words.baseAddress != nil)
self._words = words
#if DEBUG
self._mutable = mutable
#endif
}
@inlinable
@inline(__always)
public init(
words: UnsafeMutableBufferPointer<_Word>,
mutable: Bool
) {
self.init(words: UnsafeBufferPointer(words), mutable: mutable)
}
}
extension _UnsafeBitSet {
@inlinable
@inline(__always)
public var wordCount: Int {
_words.count
}
}
extension _UnsafeBitSet {
@inlinable
@inline(__always)
public static func withTemporaryBitSet<R>(
capacity: Int,
run body: (inout _UnsafeBitSet) throws -> R
) rethrows -> R {
let wordCount = _UnsafeBitSet.wordCount(forCapacity: UInt(capacity))
return try withTemporaryBitSet(wordCount: wordCount, run: body)
}
@inlinable
@inline(__always)
public static func withTemporaryBitSet<R>(
wordCount: Int,
run body: (inout Self) throws -> R
) rethrows -> R {
var result: R?
try _withTemporaryBitSet(wordCount: wordCount) { bitset in
result = try body(&bitset)
}
return result!
}
@inline(never)
public static func _withTemporaryBitSet(
wordCount: Int,
run body: (inout Self) throws -> Void
) rethrows {
try _withTemporaryUninitializedBitSet(wordCount: wordCount) { handle in
handle._mutableWords.initialize(repeating: .empty)
try body(&handle)
}
}
internal static func _withTemporaryUninitializedBitSet(
wordCount: Int,
run body: (inout Self) throws -> Void
) rethrows {
assert(wordCount >= 0)
#if compiler(>=5.6)
return try withUnsafeTemporaryAllocation(
of: _Word.self, capacity: wordCount
) { words in
var bitset = Self(words: words, mutable: true)
return try body(&bitset)
}
#else
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 start = UnsafeMutableRawPointer(p)
.assumingMemoryBound(to: _Word.self)
let words = UnsafeMutableBufferPointer(start: start, count: wordCount)
var bitset = Self(words: words, mutable: true)
return try body(&bitset)
}
}
let words = UnsafeMutableBufferPointer<_Word>.allocate(capacity: wordCount)
defer { words.deallocate() }
var bitset = Self(words: words, mutable: true)
return try body(&bitset)
#endif
}
}
extension _UnsafeBitSet {
@_effects(readnone)
@inline(__always)
public static func wordCount(forCapacity capacity: UInt) -> Int {
_Word.wordCount(forBitCount: capacity)
}
public var capacity: UInt {
@inline(__always)
get {
UInt(wordCount &* _Word.capacity)
}
}
@inline(__always)
internal func isWithinBounds(_ element: UInt) -> Bool {
element < capacity
}
@inline(__always)
public func contains(_ element: UInt) -> Bool {
let (word, bit) = Index(element).split
guard word < wordCount else { return false }
return _words[word].contains(bit)
}
@_effects(releasenone)
@discardableResult
public mutating func insert(_ element: UInt) -> Bool {
ensureMutable()
assert(isWithinBounds(element))
let index = Index(element)
return _mutableWords[index.word].insert(index.bit)
}
@_effects(releasenone)
@discardableResult
public mutating func remove(_ element: UInt) -> Bool {
ensureMutable()
let index = Index(element)
if index.word >= _words.count { return false }
return _mutableWords[index.word].remove(index.bit)
}
@_effects(releasenone)
public mutating func update(_ member: UInt, to newValue: Bool) -> Bool {
ensureMutable()
let (w, b) = Index(member).split
_mutableWords[w].update(b, to: newValue)
return w == _words.count &- 1
}
@_effects(releasenone)
public mutating func insertAll(upTo max: UInt) {
assert(max <= capacity)
guard max > 0 else { return }
let (w, b) = Index(max).split
for i in 0 ..< w {
_mutableWords[i] = .allBits
}
if b > 0 {
_mutableWords[w].insertAll(upTo: b)
}
}
@_alwaysEmitIntoClient
@inline(__always)
@discardableResult
public mutating func insert(_ element: Int) -> Bool {
precondition(element >= 0)
return insert(UInt(bitPattern: element))
}
@_alwaysEmitIntoClient
@inline(__always)
@discardableResult
public mutating func remove(_ element: Int) -> Bool {
guard element >= 0 else { return false }
return remove(UInt(bitPattern: element))
}
@_alwaysEmitIntoClient
@inline(__always)
public mutating func insertAll(upTo max: Int) {
precondition(max >= 0)
return insertAll(upTo: UInt(bitPattern: max))
}
}
extension _UnsafeBitSet: Sequence {
public typealias Element = UInt
@inlinable
@inline(__always)
public var underestimatedCount: Int {
count // FIXME: really?
}
@inlinable
@inline(__always)
public func makeIterator() -> Iterator {
return Iterator(self)
}
@frozen
public 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.wordCount > 0 ? bitset._words[0] : .empty
}
@_effects(releasenone)
public mutating func next() -> UInt? {
if let bit = _word.next() {
return Index(word: _index, bit: bit).value
}
while (_index + 1) < _bitset.wordCount {
_index += 1
_word = _bitset._words[_index]
if let bit = _word.next() {
return Index(word: _index, bit: bit).value
}
}
return nil
}
}
}
extension _UnsafeBitSet: BidirectionalCollection {
@inlinable
@inline(__always)
public var count: Int {
_words.reduce(0) { $0 + $1.count }
}
@inlinable
@inline(__always)
public var isEmpty: Bool {
_words.firstIndex(where: { !$0.isEmpty }) == nil
}
@inlinable
public var startIndex: Index {
let word = _words.firstIndex { !$0.isEmpty }
guard let word = word else { return endIndex }
return Index(word: word, bit: _words[word].firstMember!)
}
@inlinable
public var endIndex: Index {
Index(word: wordCount, bit: 0)
}
@inlinable
public subscript(position: Index) -> UInt {
position.value
}
@_effects(releasenone)
public func index(after index: Index) -> Index {
precondition(index < endIndex, "Index out of bounds")
var word = index.word
var w = _words[word]
w.removeAll(through: index.bit)
while w.isEmpty {
word += 1
guard word < wordCount else {
return Index(word: wordCount, bit: 0)
}
w = _words[word]
}
return Index(word: word, bit: w.firstMember!)
}
@_effects(releasenone)
public func index(before index: Index) -> Index {
precondition(index <= endIndex, "Index out of bounds")
var word = index.word
var w: _Word
if index.bit > 0 {
w = _words[word]
w.removeAll(from: index.bit)
} else {
w = .empty
}
while w.isEmpty {
word -= 1
precondition(word >= 0, "Can't advance below startIndex")
w = _words[word]
}
return Index(word: word, bit: w.lastMember!)
}
@_effects(releasenone)
public func distance(from start: Index, to end: Index) -> Int {
precondition(start <= endIndex && end <= endIndex, "Index out of bounds")
let isNegative = end < start
let (start, end) = (Swift.min(start, end), Swift.max(start, end))
let (w1, b1) = start.split
let (w2, b2) = end.split
if w1 == w2 {
guard w1 < wordCount else { return 0 }
let mask = _Word(from: b1, to: b2)
let c = _words[w1].intersection(mask).count
return isNegative ? -c : c
}
var c = 0
var w = w1
guard w < wordCount else { return 0 }
c &+= _words[w].subtracting(_Word(upTo: b1)).count
w &+= 1
while w < w2 {
c &+= _words[w].count
w &+= 1
}
guard w < wordCount else { return isNegative ? -c : c }
c &+= _words[w].intersection(_Word(upTo: b2)).count
return isNegative ? -c : c
}
@_effects(releasenone)
public func index(_ i: Index, offsetBy distance: Int) -> Index {
precondition(i <= endIndex, "Index out of bounds")
precondition(i == endIndex || contains(i.value), "Invalid index")
guard distance != 0 else { return i }
var remaining = distance.magnitude
if distance > 0 {
var (w, b) = i.split
precondition(w < wordCount, "Index out of bounds")
if let v = _words[w].subtracting(_Word(upTo: b)).nthElement(&remaining) {
return Index(word: w, bit: v)
}
while true {
w &+= 1
guard w < wordCount else { break }
if let v = _words[w].nthElement(&remaining) {
return Index(word: w, bit: v)
}
}
precondition(remaining == 0, "Index out of bounds")
return endIndex
}
// distance < 0
remaining -= 1
var (w, b) = i.endSplit
if w < wordCount {
if let v = _words[w].intersection(_Word(upTo: b)).nthElementFromEnd(&remaining) {
return Index(word: w, bit: v)
}
}
while true {
precondition(w > 0, "Index out of bounds")
w &-= 1
if let v = _words[w].nthElementFromEnd(&remaining) {
return Index(word: w, bit: v)
}
}
}
@_effects(releasenone)
public func index(
_ i: Index, offsetBy distance: Int, limitedBy limit: Index
) -> Index? {
precondition(i <= endIndex && limit <= endIndex, "Index out of bounds")
precondition(i == endIndex || contains(i.value), "Invalid index")
guard distance != 0 else { return i }
var remaining = distance.magnitude
if distance > 0 {
guard i <= limit else {
return self.index(i, offsetBy: distance)
}
var (w, b) = i.split
if w < wordCount,
let v = _words[w].subtracting(_Word(upTo: b)).nthElement(&remaining)
{
let r = Index(word: w, bit: v)
return r <= limit ? r : nil
}
let maxWord = Swift.min(wordCount - 1, limit.word)
while w < maxWord {
w &+= 1
if let v = _words[w].nthElement(&remaining) {
let r = Index(word: w, bit: v)
return r <= limit ? r : nil
}
}
return remaining == 0 && limit == endIndex ? endIndex : nil
}
// distance < 0
guard i >= limit else {
return self.index(i, offsetBy: distance)
}
remaining &-= 1
var (w, b) = i.endSplit
if w < wordCount {
if let v = _words[w].intersection(_Word(upTo: b)).nthElementFromEnd(&remaining) {
let r = Index(word: w, bit: v)
return r >= limit ? r : nil
}
}
let minWord = limit.word
while w > minWord {
w &-= 1
if let v = _words[w].nthElementFromEnd(&remaining) {
let r = Index(word: w, bit: v)
return r >= limit ? r : nil
}
}
return nil
}
}
@@ -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 OrderedSet internals
import XCTest
import _CollectionsTestSupport
@_spi(Testing) @testable import OrderedCollections
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