Files
2026-11-05 18:04:11 -08:00

247 lines
6.8 KiB
Swift

//===----------------------------------------------------------------------===//
//
// 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
//
// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception
//
//===----------------------------------------------------------------------===//
#if !COLLECTIONS_SINGLE_MODULE
import InternalCollectionsUtilities
import SpanPreview
#endif
#if compiler(>=6.4) && UnstableHashedContainers
@available(SwiftStdlib 5.0, *)
extension RigidSet where Element: ~Copyable {
@usableFromInline
@frozen
package struct _InsertResult: ~Copyable {
// FIXME: This struct really just wants to be a tuple.
@_alwaysEmitIntoClient
package var bucket: _Bucket
@_alwaysEmitIntoClient
package var remnant: Element?
@_alwaysEmitIntoClient
package init(
bucket: _Bucket, remnant: consuming Element?
) {
self.bucket = bucket
self.remnant = remnant
}
@_alwaysEmitIntoClient
package var found: Bool { remnant != nil }
}
/// Inserts a new item that isn't already in the set, and returns the bucket
/// where the new item ended up.
@inlinable
@inline(__always)
@discardableResult
package mutating func _insertNew(
_ item: consuming Element,
hashValue: Int
) -> _Bucket {
precondition(!isFull, "RigidSet capacity overflow")
let storage = unsafe _memberBuf
if _isSmall {
var newBucket: _Bucket? = nil
let bucket = unsafe _table.insertNew_Small(
swapper: {
if newBucket == nil { newBucket = $0 }
unsafe swap(&item, &storage[$0])
})
unsafe storage._initializeElement(at: bucket, to: item)
return newBucket ?? bucket
}
return _insertNew_Large(item, hashValue: hashValue)
}
@inlinable
@discardableResult
package mutating func _insertNew_Large(
_ item: consuming Element,
hashValue: Int
) -> _Bucket {
let storage = unsafe _memberBuf
let seed = self._seed
var newBucket: _Bucket? = nil
let bucket = unsafe _table.insertNew_Large(
hashValue: hashValue,
hashGenerator: {
unsafe storage[$0]._rawHashValue(seed: seed)
},
swapper: {
// The first swap puts the new item in its final place.
if newBucket == nil { newBucket = $0 }
unsafe swap(&item, &storage[$0])
})
unsafe storage.initializeElement(at: bucket.offset, to: item)
return newBucket ?? bucket
}
/// Inserts the given element into the set unconditionally. If the set already
/// contained a member equal to `item`, then the new item replaces it.
///
/// - Parameter item: An element to insert into the set.
/// - Returns: An element equal to `item` if the set already contained such
/// a member, otherwise `nil`.
@inlinable
@discardableResult
public mutating func update(
with item: consuming Element
) -> Element? {
let r = _find(item)
if let bucket = r.bucket {
return unsafe exchange(&_memberPtr(at: bucket).pointee, with: item)
}
_insertNew(item, hashValue: r.hashValue)
return nil
}
/// Inserts the given element in the set if it is not already present.
///
/// - Parameter item: An element to insert into the set.
/// - Returns: `item` if an equal member already exists in the set;
/// otherwise `nil`.
@inlinable
@discardableResult
public mutating func insert(
_ item: consuming Element
) -> Element? {
let r = _find(item)
if r.bucket != nil {
return item
}
_insertNew(item, hashValue: r.hashValue)
return nil
}
}
@available(SwiftStdlib 5.0, *)
extension RigidSet where Element: ~Copyable {
@_alwaysEmitIntoClient
public mutating func insert<E: Error>(
addingCount newItemCount: Int,
initializingWith initializer: (inout OutputSpan<Element>) throws(E) -> Void
) throws(E) -> Void {
precondition(newItemCount >= 0, "Cannot insert a negative number of items")
guard newItemCount > 0 else { return }
precondition(freeCapacity >= newItemCount, "RigidSet capacity overflow")
var remainder = newItemCount
// FIXME: Instead of getting temporary buffers, we could place the new
// items in unoccupied buckets, then incrementally
// rehash them into their correct location, like the stdlib does for
// the bridging initializers for Set/Dictionary.
while remainder > 0 {
let c = Swift.min(remainder, 16)
try withTemporaryOutputSpan(
of: Element.self,
capacity: c
) { output throws(E) in
defer {
#if UnstableContainersPreview
output._consumeAll { span in
if span.count < c {
remainder = 0
} else {
remainder &-= span.count
}
while let next = span.popFirst() {
insert(next)
}
}
#else
unsafe output.withUnsafeMutableBufferPointer { buffer, count in
if count < c {
remainder = 0
} else {
remainder &-= count
}
for i in 0 ..< count {
unsafe self.insert(buffer.moveElement(from: i))
}
count = 0
}
#endif
}
try initializer(&output)
}
}
}
}
@available(SwiftStdlib 5.0, *)
extension RigidSet /* where Element: Copyable */ {
@_alwaysEmitIntoClient
public mutating func insert(
copying items: borrowing Span<Element>
) {
var i = 0
while i < items.count {
unsafe self.insert(items[unchecked: i])
i &+= 1
}
}
@available(SwiftStdlib 6.4, *)
@_alwaysEmitIntoClient
package mutating func _insert<
S: Iterable & ~Copyable & ~Escapable
>(
copying items: borrowing S
) throws(S.Failure)
where S.Element == Element {
var it = items.makeBorrowingIterator()
while true {
let span = try it.nextSpan()
guard !span.isEmpty else { break }
self.insert(copying: span)
}
}
@available(SwiftStdlib 6.4, *)
@_alwaysEmitIntoClient
@inline(__always)
public mutating func insert<
S: Iterable & ~Copyable & ~Escapable
>(
copying items: borrowing S
) throws(S.Failure)
where S.Element == Element {
try _insert(copying: items)
}
@_alwaysEmitIntoClient
@inline(__always)
public mutating func insert(copying items: some Sequence<Element>) {
var it = items.makeIterator()
while let next = it.next() {
self.insert(next)
}
}
@available(SwiftStdlib 6.4, *)
@_alwaysEmitIntoClient
@inline(__always)
public mutating func insert<
S: Iterable & Sequence<Element>
>(
copying items: borrowing S
) throws(S.Failure)
where S.Element == Element {
try _insert(copying: items)
}
}
#endif