mirror of
https://github.com/apple/swift-collections
synced 2026-11-27 04:54:21 +00:00
Merge remote-tracking branch 'origin/main' into sortedcollections-hashable
This commit is contained in:
commit
13bda5d66d
405 files changed
+7886
-6566
No files matched your search
@@ -125,5 +125,7 @@ jobs:
|
||||
run: xcrun xcodebuild -version
|
||||
- name: Swift version
|
||||
run: xcrun swift --version
|
||||
- name: Build
|
||||
- name: Build Collections
|
||||
run: xcrun xcodebuild -project Xcode/Collections.xcodeproj -scheme Collections
|
||||
- name: Build ContainersPreview
|
||||
run: xcrun xcodebuild -project Xcode/Collections.xcodeproj -scheme ContainersPreview
|
||||
@@ -1,4 +1,4 @@
|
||||
// swift-tools-version:6.2
|
||||
// swift-tools-version:6.4
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Collections open source project
|
||||
@@ -44,6 +44,8 @@ let availabilityMacros: KeyValuePairs<String, String> = [
|
||||
"SwiftStdlib 6.1": "macOS 15.4, iOS 18.4, watchOS 11.4, tvOS 18.4, visionOS 2.4",
|
||||
"SwiftStdlib 6.2": "macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, visionOS 26.0",
|
||||
"SwiftStdlib 6.3": "macOS 26.4, iOS 26.4, watchOS 26.4, tvOS 26.4, visionOS 26.4",
|
||||
"SwiftStdlib 6.4": "macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0",
|
||||
"SwiftStdlib 6.5": "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, visionOS 9999",
|
||||
]
|
||||
|
||||
let _sharedSettings: [SwiftSetting] = (
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import CollectionsBenchmark
|
||||
@_spi(Testing) import DequeModule
|
||||
import DequeModule
|
||||
|
||||
extension Deque {
|
||||
@inline(__always)
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import CollectionsBenchmark
|
||||
@_spi(Testing) import DequeModule
|
||||
import DequeModule
|
||||
|
||||
/// Do nothing and immediately return.
|
||||
///
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import CollectionsBenchmark
|
||||
@_spi(Testing) import DequeModule
|
||||
import DequeModule
|
||||
|
||||
@inline(never)
|
||||
@_optimize(none)
|
||||
|
||||
+3
-2
@@ -1,4 +1,4 @@
|
||||
// swift-tools-version:6.2
|
||||
// swift-tools-version:6.4
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Collections open source project
|
||||
@@ -108,7 +108,7 @@ let availabilityMacros: KeyValuePairs<String, String> = [
|
||||
]
|
||||
|
||||
let extraSettings: [SwiftSetting] = [
|
||||
// .strictMemorySafety(),
|
||||
.strictMemorySafety(),
|
||||
.enableUpcomingFeature("MemberImportVisibility"),
|
||||
.enableExperimentalFeature("BuiltinModule"),
|
||||
.enableExperimentalFeature("Lifetimes"),
|
||||
@@ -341,6 +341,7 @@ let targets: [CustomTarget] = [
|
||||
.target(
|
||||
kind: .exported,
|
||||
name: "TrailingElementsModule",
|
||||
dependencies: ["InternalCollectionsUtilities"],
|
||||
exclude: ["CMakeLists.txt"]),
|
||||
.target(
|
||||
kind: .test,
|
||||
|
||||
@@ -0,0 +1,390 @@
|
||||
// swift-tools-version:6.2
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Collections open source project
|
||||
//
|
||||
// Copyright (c) 2021 - 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import PackageDescription
|
||||
|
||||
let _traits: Set<Trait> = [
|
||||
.default(
|
||||
enabledTraits: [
|
||||
// "UnstableContainersPreview",
|
||||
// "UnstableHashedContainers",
|
||||
// "UnstableSortedCollections",
|
||||
]),
|
||||
.trait(
|
||||
name: "UnstableContainersPreview",
|
||||
description: """
|
||||
Enables source-unstable components of the ContainersPreview module in
|
||||
swift-collections. This allows experimental use of the Container
|
||||
protocols and associated algorithms.
|
||||
"""),
|
||||
.trait(
|
||||
name: "UnstableSortedCollections",
|
||||
description: """
|
||||
Enables source-unstable prototypes of `SortedSet` and `SortedDictionary`,
|
||||
two potential new collection types implementing in-memory B-trees.
|
||||
These are early developer drafts, and they not ready for use in
|
||||
production. We will make significant, source breaking API changes to these
|
||||
types before they ship.
|
||||
"""),
|
||||
.trait(
|
||||
name: "UnstableHashedContainers",
|
||||
description: """
|
||||
Enables support for noncopyable set members and dictionary keys in
|
||||
`BasicContainers`. This requires a Standard Library with generalized
|
||||
`Equatable` and `Hashable` protocols that allow noncopyable conformers;
|
||||
this feature has not shipped in a stable compiler version yet.
|
||||
"""),
|
||||
]
|
||||
|
||||
// This package recognizes the conditional compilation flags listed below.
|
||||
// To use enable them, uncomment the corresponding lines or define them
|
||||
// from the package manager command line:
|
||||
//
|
||||
// swift build -Xswiftc -DCOLLECTIONS_INTERNAL_CHECKS
|
||||
var defines: [SwiftSetting] = [
|
||||
// Enables internal consistency checks at the end of initializers and
|
||||
// mutating operations. This can have very significant overhead, so enabling
|
||||
// this setting invalidates all documented performance guarantees.
|
||||
//
|
||||
// This is mostly useful while debugging an issue with the implementation of
|
||||
// the hash table itself. This setting should never be enabled in production
|
||||
// code.
|
||||
// .define("COLLECTIONS_INTERNAL_CHECKS"),
|
||||
|
||||
// Hashing collections provided by this package usually seed their hash
|
||||
// function with the address of the memory location of their storage,
|
||||
// to prevent some common hash table merge/copy operations from regressing to
|
||||
// quadratic behavior. This setting turns off this mechanism, seeding
|
||||
// the hash function with the table's size instead.
|
||||
//
|
||||
// When used in conjunction with the SWIFT_DETERMINISTIC_HASHING environment
|
||||
// variable, this enables reproducible hashing behavior.
|
||||
//
|
||||
// This is mostly useful while debugging an issue with the implementation of
|
||||
// the hash table itself. This setting should never be enabled in production
|
||||
// code.
|
||||
// .define("COLLECTIONS_DETERMINISTIC_HASHING"),
|
||||
|
||||
// Enables randomized testing of some data structure implementations.
|
||||
.define("COLLECTIONS_RANDOMIZED_TESTING"),
|
||||
|
||||
// Enable this to build the sources as a single, large module.
|
||||
// This removes the distinct modules for each data structure, instead
|
||||
// putting them all directly into the `Collections` module.
|
||||
// Note: This is a source-incompatible variation of the default configuration.
|
||||
// .define("COLLECTIONS_SINGLE_MODULE"),
|
||||
|
||||
// Enables longer, more exhaustive tests.
|
||||
// .define("COLLECTIONS_LONG_TESTS"),
|
||||
]
|
||||
|
||||
let availabilityMacros: KeyValuePairs<String, String> = [
|
||||
"SwiftStdlib 5.0": "macOS 10.14.4, iOS 12.2, watchOS 5.2, tvOS 12.2",
|
||||
"SwiftStdlib 5.1": "macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0",
|
||||
"SwiftStdlib 5.6": "macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4",
|
||||
"SwiftStdlib 5.7": "macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0",
|
||||
"SwiftStdlib 5.8": "macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4",
|
||||
"SwiftStdlib 5.9": "macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0",
|
||||
"SwiftStdlib 5.10": "macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4, visionOS 1.1",
|
||||
"SwiftStdlib 6.0": "macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0",
|
||||
"SwiftStdlib 6.1": "macOS 15.4, iOS 18.4, watchOS 11.4, tvOS 18.4, visionOS 2.4",
|
||||
"SwiftStdlib 6.2": "macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, visionOS 26.0",
|
||||
"SwiftStdlib 6.3": "macOS 26.4, iOS 26.4, watchOS 26.4, tvOS 26.4, visionOS 26.4",
|
||||
"SwiftStdlib 6.4": "macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0",
|
||||
"SwiftStdlib 6.5": "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, visionOS 9999",
|
||||
// Note: if you touch these, please make sure to also update the similar lists in
|
||||
// CMakeLists.txt and Xcode/Shared.xcconfig.
|
||||
]
|
||||
|
||||
let extraSettings: [SwiftSetting] = [
|
||||
//.strictMemorySafety(),
|
||||
.enableUpcomingFeature("MemberImportVisibility"),
|
||||
.enableExperimentalFeature("BuiltinModule"),
|
||||
.enableExperimentalFeature("Lifetimes"),
|
||||
.enableExperimentalFeature("InoutLifetimeDependence"),
|
||||
.enableExperimentalFeature("AddressableParameters"),
|
||||
.enableExperimentalFeature("AddressableTypes"),
|
||||
.enableExperimentalFeature("SuppressedAssociatedTypesWithDefaults"), // Requires Swift 6.4
|
||||
.enableExperimentalFeature("BorrowingSequence"), // 6.4
|
||||
// Note: if you touch these, please make sure to also update the similar lists in
|
||||
// CMakeLists.txt and Xcode/Shared.xcconfig.
|
||||
]
|
||||
|
||||
let _baseSettings: [SwiftSetting] = (
|
||||
defines
|
||||
+ availabilityMacros.map { name, value in
|
||||
.enableExperimentalFeature("AvailabilityMacro=\(name): \(value)")
|
||||
}
|
||||
)
|
||||
|
||||
let _settings: [SwiftSetting] = _baseSettings + extraSettings
|
||||
let _testSettings: [SwiftSetting] = _settings
|
||||
|
||||
struct CustomTarget {
|
||||
enum Kind {
|
||||
case exported
|
||||
case hidden
|
||||
case test
|
||||
case testSupport
|
||||
}
|
||||
|
||||
var kind: Kind
|
||||
var name: String
|
||||
var dependencies: [Target.Dependency]
|
||||
var directory: String
|
||||
var exclude: [String]
|
||||
var sources: [String]?
|
||||
var settings: [SwiftSetting]
|
||||
}
|
||||
|
||||
extension CustomTarget.Kind {
|
||||
func path(for name: String) -> String {
|
||||
switch self {
|
||||
case .exported, .hidden: return "Sources/\(name)"
|
||||
case .test, .testSupport: return "Tests/\(name)"
|
||||
}
|
||||
}
|
||||
|
||||
var isTest: Bool {
|
||||
switch self {
|
||||
case .exported, .hidden: return false
|
||||
case .test, .testSupport: return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension CustomTarget {
|
||||
static func target(
|
||||
kind: Kind,
|
||||
name: String,
|
||||
dependencies: [Target.Dependency] = [],
|
||||
directory: String? = nil,
|
||||
exclude: [String] = [],
|
||||
sources: [String]? = nil,
|
||||
settings: [SwiftSetting]? = nil
|
||||
) -> CustomTarget {
|
||||
CustomTarget(
|
||||
kind: kind,
|
||||
name: name,
|
||||
dependencies: dependencies,
|
||||
directory: directory ?? name,
|
||||
exclude: exclude,
|
||||
sources: sources,
|
||||
settings: settings ?? (kind.isTest ? _testSettings : _settings))
|
||||
}
|
||||
|
||||
func toTarget() -> Target {
|
||||
var linkerSettings: [LinkerSetting] = []
|
||||
if kind == .testSupport {
|
||||
linkerSettings.append(
|
||||
.linkedFramework("XCTest", .when(platforms: [.macOS, .iOS, .watchOS, .tvOS])))
|
||||
}
|
||||
switch kind {
|
||||
case .exported, .hidden, .testSupport:
|
||||
return Target.target(
|
||||
name: name,
|
||||
dependencies: dependencies,
|
||||
path: kind.path(for: directory),
|
||||
exclude: exclude,
|
||||
sources: sources,
|
||||
swiftSettings: settings,
|
||||
linkerSettings: linkerSettings)
|
||||
case .test:
|
||||
return Target.testTarget(
|
||||
name: name,
|
||||
dependencies: dependencies,
|
||||
path: kind.path(for: directory),
|
||||
exclude: exclude,
|
||||
swiftSettings: settings,
|
||||
linkerSettings: linkerSettings)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let targets: [CustomTarget] = [
|
||||
.target(
|
||||
kind: .testSupport,
|
||||
name: "_CollectionsTestSupport",
|
||||
dependencies: [
|
||||
"InternalCollectionsUtilities",
|
||||
"ContainersPreview",
|
||||
"BasicContainers",
|
||||
"SpanPreview",
|
||||
]),
|
||||
.target(
|
||||
kind: .test,
|
||||
name: "CollectionsTestSupportTests",
|
||||
dependencies: ["_CollectionsTestSupport"]),
|
||||
.target(
|
||||
kind: .hidden,
|
||||
name: "InternalCollectionsUtilities",
|
||||
exclude: [
|
||||
"CMakeLists.txt",
|
||||
]),
|
||||
|
||||
.target(
|
||||
kind: .exported,
|
||||
name: "BasicContainers",
|
||||
dependencies: ["InternalCollectionsUtilities", "SpanPreview"],
|
||||
exclude: ["CMakeLists.txt"]
|
||||
),
|
||||
.target(
|
||||
kind: .test,
|
||||
name: "BasicContainersTests",
|
||||
dependencies: [
|
||||
"BasicContainers", "_CollectionsTestSupport"
|
||||
]),
|
||||
|
||||
.target(
|
||||
kind: .exported,
|
||||
name: "BitCollections",
|
||||
dependencies: ["InternalCollectionsUtilities"],
|
||||
exclude: ["CMakeLists.txt"]),
|
||||
.target(
|
||||
kind: .test,
|
||||
name: "BitCollectionsTests",
|
||||
dependencies: [
|
||||
"BitCollections", "_CollectionsTestSupport", "OrderedCollections"
|
||||
]),
|
||||
|
||||
.target(
|
||||
kind: .exported,
|
||||
name: "ContainersPreview",
|
||||
dependencies: [
|
||||
"InternalCollectionsUtilities",
|
||||
"BasicContainers",
|
||||
"DequeModule",
|
||||
"SpanPreview",
|
||||
],
|
||||
exclude: ["CMakeLists.txt"]),
|
||||
.target(
|
||||
kind: .test,
|
||||
name: "ContainersTests",
|
||||
dependencies: [
|
||||
"ContainersPreview", "_CollectionsTestSupport"
|
||||
]),
|
||||
|
||||
.target(
|
||||
kind: .exported,
|
||||
name: "DequeModule",
|
||||
dependencies: ["InternalCollectionsUtilities", "SpanPreview"],
|
||||
exclude: ["CMakeLists.txt"]),
|
||||
.target(
|
||||
kind: .test,
|
||||
name: "DequeTests",
|
||||
dependencies: ["DequeModule", "_CollectionsTestSupport"]),
|
||||
|
||||
.target(
|
||||
kind: .exported,
|
||||
name: "HashTreeCollections",
|
||||
dependencies: ["InternalCollectionsUtilities"],
|
||||
exclude: ["CMakeLists.txt"]),
|
||||
.target(
|
||||
kind: .test,
|
||||
name: "HashTreeCollectionsTests",
|
||||
dependencies: ["HashTreeCollections", "_CollectionsTestSupport"]),
|
||||
|
||||
.target(
|
||||
kind: .exported,
|
||||
name: "HeapModule",
|
||||
dependencies: ["InternalCollectionsUtilities"],
|
||||
exclude: ["CMakeLists.txt"]),
|
||||
.target(
|
||||
kind: .test,
|
||||
name: "HeapTests",
|
||||
dependencies: ["HeapModule", "_CollectionsTestSupport"]),
|
||||
|
||||
.target(
|
||||
kind: .exported,
|
||||
name: "OrderedCollections",
|
||||
dependencies: ["InternalCollectionsUtilities"],
|
||||
exclude: ["CMakeLists.txt"]),
|
||||
.target(
|
||||
kind: .test,
|
||||
name: "OrderedCollectionsTests",
|
||||
dependencies: ["OrderedCollections", "_CollectionsTestSupport"]),
|
||||
|
||||
.target(
|
||||
kind: .exported,
|
||||
name: "_RopeModule",
|
||||
dependencies: ["InternalCollectionsUtilities"],
|
||||
directory: "RopeModule",
|
||||
exclude: ["CMakeLists.txt"],
|
||||
// FIXME: _modify accessors in RopeModule seem to be broken in Swift 6 mode
|
||||
settings: _settings + [.swiftLanguageMode(.v5)]),
|
||||
.target(
|
||||
kind: .test,
|
||||
name: "RopeModuleTests",
|
||||
dependencies: ["_RopeModule", "_CollectionsTestSupport"]),
|
||||
|
||||
.target(
|
||||
kind: .exported,
|
||||
name: "SpanPreview",
|
||||
dependencies: ["InternalCollectionsUtilities"],
|
||||
exclude: ["CMakeLists.txt"]),
|
||||
.target(
|
||||
kind: .test,
|
||||
name: "SpanPreviewTests",
|
||||
dependencies: ["SpanPreview", "_CollectionsTestSupport"]),
|
||||
|
||||
.target(
|
||||
kind: .exported,
|
||||
name: "TrailingElementsModule",
|
||||
dependencies: ["InternalCollectionsUtilities"],
|
||||
exclude: ["CMakeLists.txt"]),
|
||||
.target(
|
||||
kind: .test,
|
||||
name: "TrailingElementsTests",
|
||||
dependencies: ["TrailingElementsModule"]),
|
||||
|
||||
.target(
|
||||
kind: .exported,
|
||||
name: "SortedCollections",
|
||||
dependencies: ["InternalCollectionsUtilities"],
|
||||
directory: "SortedCollections"),
|
||||
.target(
|
||||
kind: .test,
|
||||
name: "SortedCollectionsTests",
|
||||
dependencies: ["SortedCollections", "_CollectionsTestSupport"]),
|
||||
|
||||
.target(
|
||||
kind: .exported,
|
||||
name: "Collections",
|
||||
dependencies: [
|
||||
"BitCollections",
|
||||
"DequeModule",
|
||||
"HashTreeCollections",
|
||||
"HeapModule",
|
||||
"OrderedCollections",
|
||||
"_RopeModule",
|
||||
],
|
||||
exclude: ["CMakeLists.txt"]),
|
||||
.target(
|
||||
kind: .test,
|
||||
name: "CollectionsModuleTests",
|
||||
dependencies: ["Collections", "_CollectionsTestSupport"],
|
||||
settings: _baseSettings + [.enableUpcomingFeature("MemberImportVisibility")]),
|
||||
]
|
||||
|
||||
let _products: [Product] = targets.compactMap { t in
|
||||
guard t.kind == .exported else { return nil }
|
||||
return .library(name: t.name, targets: [t.name])
|
||||
}
|
||||
let _targets: [Target] = targets.map { $0.toTarget() }
|
||||
|
||||
let package = Package(
|
||||
name: "swift-collections",
|
||||
products: _products,
|
||||
traits: _traits,
|
||||
targets: _targets)
|
||||
@@ -18,6 +18,7 @@ import InternalCollectionsUtilities
|
||||
extension _HTable {
|
||||
@usableFromInline
|
||||
@frozen
|
||||
@safe
|
||||
package struct Bitmap: ~Copyable, ~Escapable {
|
||||
@usableFromInline
|
||||
package typealias Bucket = _HTable.Bucket
|
||||
@@ -28,7 +29,7 @@ extension _HTable {
|
||||
@_alwaysEmitIntoClient
|
||||
@_lifetime(borrow table)
|
||||
package init(table: borrowing _HTable) {
|
||||
self._words = .init(start: table._bitmap, count: table.wordCount)
|
||||
unsafe self._words = .init(start: table._bitmap, count: table.wordCount)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -39,42 +40,43 @@ extension _HTable.Bitmap {
|
||||
|
||||
@_transparent
|
||||
@inlinable
|
||||
@safe
|
||||
package func isValid(_ bucket: Bucket) -> Bool {
|
||||
bucket.word < _words.count
|
||||
unsafe bucket.word < _words.count
|
||||
}
|
||||
|
||||
@_transparent
|
||||
@inlinable
|
||||
package func isOccupied(_ bucket: Bucket) -> Bool {
|
||||
assert(isValid(bucket))
|
||||
return _words[bucket.word].contains(bucket.bit)
|
||||
return unsafe _words[bucket.word].contains(bucket.bit)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
@inlinable
|
||||
package func setOccupied(_ bucket: Bucket) {
|
||||
assert(isValid(bucket))
|
||||
_words[bucket.word].set(bucket.bit)
|
||||
unsafe _words[bucket.word].set(bucket.bit)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
@inlinable
|
||||
package func clearOccupied(_ bucket: Bucket) {
|
||||
assert(isValid(bucket))
|
||||
_words[bucket.word].clear(bucket.bit)
|
||||
unsafe _words[bucket.word].clear(bucket.bit)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
@inlinable
|
||||
package func clearAll() {
|
||||
_words.update(repeating: .empty)
|
||||
unsafe _words.update(repeating: .empty)
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
package func occupiedCount() -> Int {
|
||||
var c = 0
|
||||
for i in 0 ..< _words.count {
|
||||
c += _words[i].count
|
||||
for i in unsafe 0 ..< _words.count {
|
||||
unsafe c += _words[i].count
|
||||
}
|
||||
return c
|
||||
}
|
||||
@@ -84,7 +86,7 @@ extension _HTable.Bitmap {
|
||||
guard isValid(start) else { return nil }
|
||||
|
||||
var word = start.word
|
||||
var bits = _words[word]
|
||||
var bits = unsafe _words[word]
|
||||
bits.removeAll(upTo: start.bit)
|
||||
|
||||
while true {
|
||||
@@ -92,10 +94,10 @@ extension _HTable.Bitmap {
|
||||
return Bucket(word: word, bit: bit)
|
||||
}
|
||||
word &+= 1
|
||||
if word >= _words.count {
|
||||
if unsafe word >= _words.count {
|
||||
return nil
|
||||
}
|
||||
bits = _words[word]
|
||||
unsafe bits = _words[word]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,16 +105,16 @@ extension _HTable.Bitmap {
|
||||
package func firstOccupiedBucket(
|
||||
from start: Bucket, limit: Bucket
|
||||
) -> Bucket {
|
||||
assert(isValid(start) && start <= limit && limit.word <= _words.count)
|
||||
assert(unsafe isValid(start) && start <= limit && limit.word <= _words.count)
|
||||
var word = start.word
|
||||
var bits = _words[word]
|
||||
var bits = unsafe _words[word]
|
||||
bits.removeAll(upTo: start.bit)
|
||||
while word < limit.word {
|
||||
if let bit = bits.firstMember {
|
||||
return Bucket(word: word, bit: bit)
|
||||
}
|
||||
word &+= 1
|
||||
bits = word < _words.count ? _words[word] : .empty
|
||||
unsafe bits = word < _words.count ? _words[word] : .empty
|
||||
}
|
||||
bits.removeAll(from: limit.bit)
|
||||
if let bit = bits.firstMember {
|
||||
@@ -127,7 +129,7 @@ extension _HTable.Bitmap {
|
||||
package func collisionChainEnd(from start: Bucket) -> Bucket {
|
||||
assert(isOccupied(start))
|
||||
var word = start.word
|
||||
var bits = _words[word]
|
||||
var bits = unsafe _words[word]
|
||||
bits.insertAll(upTo: start.bit)
|
||||
var wrapped = false
|
||||
while true {
|
||||
@@ -136,12 +138,12 @@ extension _HTable.Bitmap {
|
||||
return Bucket(word: word, bit: bit)
|
||||
}
|
||||
word &+= 1
|
||||
if word >= _words.count {
|
||||
if unsafe word >= _words.count {
|
||||
precondition(!wrapped, "Corrupt hash table")
|
||||
wrapped = true
|
||||
word = 0
|
||||
}
|
||||
bits = _words[word]
|
||||
unsafe bits = _words[word]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -153,9 +155,9 @@ extension _HTable.Bitmap {
|
||||
) -> Bucket {
|
||||
assert(isValid(start))
|
||||
var word = start.word
|
||||
var bits = _words[word]
|
||||
var bits = unsafe _words[word]
|
||||
bits.insertAll(upTo: start.bit)
|
||||
var remainder = Swift.min(
|
||||
var remainder = unsafe Swift.min(
|
||||
UInt(bitPattern: maxCount) &+ start.bit,
|
||||
UInt(bitPattern: (_words.count &- start.word) &* Word.capacity))
|
||||
while true {
|
||||
@@ -169,8 +171,8 @@ extension _HTable.Bitmap {
|
||||
word &+= 1
|
||||
remainder &-= Word._capacity
|
||||
guard remainder > 0 else { break }
|
||||
assert(word < _words.count)
|
||||
bits = _words[word]
|
||||
assert(unsafe word < _words.count)
|
||||
unsafe bits = _words[word]
|
||||
}
|
||||
return Bucket(word: word, bit: remainder)
|
||||
}
|
||||
@@ -187,7 +189,7 @@ extension _HTable.Bitmap {
|
||||
let end = self._nextOccupiedChunkEnd(
|
||||
from: bucket,
|
||||
maxCount: Swift.min(maxCount, limit.offset &- bucket.offset))
|
||||
let result = Range(uncheckedBounds: (bucket, end))
|
||||
let result = unsafe Range(uncheckedBounds: (bucket, end))
|
||||
if isValid(end), !isOccupied(end) {
|
||||
bucket = firstOccupiedBucket(from: end, limit: limit)
|
||||
} else {
|
||||
|
||||
@@ -21,6 +21,7 @@ extension _HTable {
|
||||
/// to a function that expects a word index, or vice versa.
|
||||
@usableFromInline
|
||||
@frozen
|
||||
@safe
|
||||
package struct Bucket {
|
||||
@usableFromInline
|
||||
internal typealias Word = _HTable.Word
|
||||
@@ -127,11 +128,11 @@ extension UnsafeMutableBufferPointer where Element: ~Copyable {
|
||||
package subscript(bucket: _HTable.Bucket) -> Element {
|
||||
@_transparent
|
||||
unsafeAddress {
|
||||
return .init(_ptr(at: bucket.offset))
|
||||
return unsafe .init(_ptr(at: bucket.offset))
|
||||
}
|
||||
@_transparent
|
||||
nonmutating unsafeMutableAddress {
|
||||
return _ptr(at: bucket.offset)
|
||||
return unsafe _ptr(at: bucket.offset)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -140,7 +141,7 @@ extension UnsafeMutableBufferPointer where Element: ~Copyable {
|
||||
package func _ptr(
|
||||
at bucket: _HTable.Bucket
|
||||
) -> UnsafeMutablePointer<Element> {
|
||||
_ptr(at: bucket.offset)
|
||||
unsafe _ptr(at: bucket.offset)
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@@ -149,13 +150,13 @@ extension UnsafeMutableBufferPointer where Element: ~Copyable {
|
||||
at bucket: _HTable.Bucket,
|
||||
to value: consuming Element
|
||||
) {
|
||||
initializeElement(at: bucket.offset, to: value)
|
||||
unsafe initializeElement(at: bucket.offset, to: value)
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
package func _extracting(_ buckets: Range<_HTable.Bucket>) -> Self {
|
||||
_extracting(
|
||||
unsafe _extracting(
|
||||
uncheckedFrom: buckets.lowerBound.offset,
|
||||
to: buckets.upperBound.offset)
|
||||
}
|
||||
@@ -166,7 +167,7 @@ extension Range where Bound == _HTable.Bucket {
|
||||
package var _offsets: Range<Int> {
|
||||
@_transparent
|
||||
get {
|
||||
.init(uncheckedBounds: (lowerBound.offset, upperBound.offset))
|
||||
unsafe .init(uncheckedBounds: (lowerBound.offset, upperBound.offset))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,13 +17,13 @@ extension _HTable {
|
||||
swapper: (Bucket) -> Void,
|
||||
) -> Bucket {
|
||||
assert(isSmall)
|
||||
if _count > 0 {
|
||||
if self.count > 0 {
|
||||
// Scramble order by swapping the new item in the middle of the table.
|
||||
swapper(Bucket(offset: _count / 2))
|
||||
swapper(Bucket(offset: self.count / 2))
|
||||
}
|
||||
let r = Bucket(offset: _count)
|
||||
_count &+= 1
|
||||
_maxProbeLength = _count
|
||||
let r = Bucket(offset: self.count)
|
||||
unsafe _count &+= 1
|
||||
_maxProbeLength = self.count
|
||||
return r
|
||||
}
|
||||
|
||||
@@ -75,7 +75,7 @@ extension _HTable {
|
||||
probeLength &+= 1
|
||||
}
|
||||
bitmap.setOccupied(b)
|
||||
_count &+= 1
|
||||
unsafe _count &+= 1
|
||||
if probeLength > _maxProbeLength {
|
||||
_maxProbeLength = probeLength
|
||||
}
|
||||
|
||||
@@ -37,6 +37,7 @@ extension _HTable {
|
||||
/// iterator values outside the closure call that produced the original
|
||||
/// hash table.
|
||||
@usableFromInline
|
||||
@safe
|
||||
package struct BucketIterator: ~Escapable {
|
||||
@usableFromInline
|
||||
package typealias Bucket = _HTable.Bucket
|
||||
@@ -72,17 +73,17 @@ extension _HTable {
|
||||
assert(table.isValid(bucket) || bucket == table.endBucket)
|
||||
assert(table.endBucket.bit == 0 || table.endBucket.word == 0) // We rely on this throughout the code below
|
||||
self._bucket = bucket
|
||||
if let bitmap = table._bitmap {
|
||||
self._words = .init(bitmap)
|
||||
if let bitmap = unsafe table._bitmap {
|
||||
unsafe self._words = .init(bitmap)
|
||||
self._endBucket = table.endBucket
|
||||
self._nextBits = bitmap[_bucket.word].shiftedDown(by: _bucket.bit)
|
||||
self._nextBits = unsafe bitmap[_bucket.word].shiftedDown(by: _bucket.bit)
|
||||
if table.endBucket._offset < Word.capacity {
|
||||
self._nextBitCount = UInt8(table.endBucket.bit &- _bucket.bit)
|
||||
} else {
|
||||
self._nextBitCount = UInt8(Word._capacity &- _bucket.bit)
|
||||
}
|
||||
} else {
|
||||
self._words = nil
|
||||
unsafe self._words = nil
|
||||
self._endBucket = Bucket(offset: table.count) // Note: not capacity!
|
||||
self._nextBits = .empty
|
||||
self._nextBitCount = 0
|
||||
@@ -108,7 +109,7 @@ extension _HTable.BucketIterator {
|
||||
@_transparent
|
||||
package var isOccupied: Bool {
|
||||
assert(!isAtEnd)
|
||||
if _words == nil { return true }
|
||||
if unsafe _words == nil { return true }
|
||||
return _nextBits.contains(0)
|
||||
}
|
||||
|
||||
@@ -117,8 +118,8 @@ extension _HTable.BucketIterator {
|
||||
package mutating func restart() {
|
||||
_wrapped = true
|
||||
_bucket._offset = 0
|
||||
if let words = _words {
|
||||
_nextBits = words[_bucket.word]
|
||||
if let words = unsafe _words {
|
||||
_nextBits = unsafe words[_bucket.word]
|
||||
_nextBitCount = UInt8(Swift.min(Word._capacity, _endBucket._offset))
|
||||
}
|
||||
}
|
||||
@@ -148,8 +149,8 @@ extension _HTable.BucketIterator {
|
||||
advanceToEnd()
|
||||
return false
|
||||
}
|
||||
if let words = _words{
|
||||
_nextBits = words[_bucket.word]
|
||||
if let words = unsafe _words {
|
||||
_nextBits = unsafe words[_bucket.word]
|
||||
_nextBitCount = UInt8(Word._capacity)
|
||||
}
|
||||
return true
|
||||
@@ -161,8 +162,8 @@ extension _HTable.BucketIterator {
|
||||
_bucket.advanceToNextWord()
|
||||
if isAtEnd {
|
||||
_wrap()
|
||||
} else if let words = _words {
|
||||
_nextBits = words[_bucket.word]
|
||||
} else if let words = unsafe _words {
|
||||
_nextBits = unsafe words[_bucket.word]
|
||||
_nextBitCount = UInt8(Word._capacity)
|
||||
}
|
||||
}
|
||||
@@ -177,14 +178,14 @@ extension _HTable.BucketIterator {
|
||||
advanceToEnd()
|
||||
return false
|
||||
}
|
||||
guard let words = _words else { return true }
|
||||
guard let words = unsafe _words else { return true }
|
||||
assert(_nextBitCount > 0)
|
||||
_nextBitCount &-= 1
|
||||
if _nextBitCount > 0 {
|
||||
_nextBits = _nextBits.shiftedDown(by: 1)
|
||||
} else {
|
||||
assert(_bucket.bit == 0)
|
||||
_nextBits = words[_bucket.word]
|
||||
_nextBits = unsafe words[_bucket.word]
|
||||
_nextBitCount = UInt8(Word._capacity)
|
||||
}
|
||||
return true
|
||||
@@ -198,13 +199,13 @@ extension _HTable.BucketIterator {
|
||||
_wrap()
|
||||
return
|
||||
}
|
||||
guard let words = _words else { return }
|
||||
guard let words = unsafe _words else { return }
|
||||
assert(_nextBitCount > 0)
|
||||
_nextBitCount &-= 1
|
||||
if _nextBitCount > 0 {
|
||||
_nextBits = _nextBits.shiftedDown(by: 1)
|
||||
} else {
|
||||
_nextBits = words[_bucket.word]
|
||||
_nextBits = unsafe words[_bucket.word]
|
||||
_nextBitCount = UInt8(Word._capacity)
|
||||
}
|
||||
}
|
||||
@@ -215,7 +216,7 @@ extension _HTable.BucketIterator {
|
||||
@_lifetime(self: copy self)
|
||||
package mutating func advanceToOccupied() -> Bool {
|
||||
if isAtEnd { return false }
|
||||
if _words == nil {
|
||||
if unsafe _words == nil {
|
||||
return true
|
||||
}
|
||||
while true {
|
||||
@@ -239,7 +240,7 @@ extension _HTable.BucketIterator {
|
||||
) -> Bool {
|
||||
var remainder = UInt(bitPattern: maxCount)
|
||||
if isAtEnd { return false }
|
||||
if _words == nil {
|
||||
if unsafe _words == nil {
|
||||
let delta = Swift.min(_endBucket._offset &- _bucket._offset, remainder)
|
||||
_bucket._offset &+= delta
|
||||
return true
|
||||
@@ -269,7 +270,7 @@ extension _HTable.BucketIterator {
|
||||
@usableFromInline
|
||||
@_lifetime(self: copy self)
|
||||
package mutating func wrapToOccupied() {
|
||||
if _words == nil {
|
||||
if unsafe _words == nil {
|
||||
wrapToNextBit()
|
||||
return
|
||||
}
|
||||
@@ -290,7 +291,7 @@ extension _HTable.BucketIterator {
|
||||
@_lifetime(self: copy self)
|
||||
package mutating func advanceToUnoccupied() -> Bool {
|
||||
assert(!isAtEnd)
|
||||
if _words == nil {
|
||||
if unsafe _words == nil {
|
||||
_bucket = _endBucket
|
||||
return false
|
||||
}
|
||||
@@ -317,7 +318,7 @@ extension _HTable.BucketIterator {
|
||||
assert(maxCount > 0)
|
||||
assert(!isAtEnd)
|
||||
var remainder = UInt(bitPattern: maxCount)
|
||||
if _words == nil {
|
||||
if unsafe _words == nil {
|
||||
let delta = Swift.min(_endBucket._offset &- _bucket._offset, remainder)
|
||||
_bucket._offset &+= delta
|
||||
return false
|
||||
@@ -348,7 +349,7 @@ extension _HTable.BucketIterator {
|
||||
@usableFromInline
|
||||
@_lifetime(self: copy self)
|
||||
package mutating func wrapToUnoccupied() {
|
||||
if _words == nil {
|
||||
if unsafe _words == nil {
|
||||
_bucket = _endBucket
|
||||
return
|
||||
}
|
||||
@@ -374,7 +375,7 @@ extension _HTable.BucketIterator {
|
||||
let start = self.currentBucket
|
||||
self.advanceToUnoccupied(maxCount: maxCount)
|
||||
let end = self.currentBucket
|
||||
return Range(uncheckedBounds: (start, end))
|
||||
return unsafe Range(uncheckedBounds: (start, end))
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
@@ -388,6 +389,6 @@ extension _HTable.BucketIterator {
|
||||
let start = self.currentBucket
|
||||
self.advanceToOccupied(maxCount: maxCount)
|
||||
let end = self.currentBucket
|
||||
return Range(uncheckedBounds: (start, end))
|
||||
return unsafe Range(uncheckedBounds: (start, end))
|
||||
}
|
||||
}
|
||||
@@ -17,11 +17,12 @@ extension _HTable {
|
||||
/// is created, the table remains in an inconsistent state until one of
|
||||
/// `resolveHole` or `finalizeHole` is called on the same bucket.
|
||||
@usableFromInline
|
||||
@unsafe
|
||||
package mutating func createHole(
|
||||
at bucket: Bucket
|
||||
) {
|
||||
assert(isOccupied(bucket))
|
||||
_count &-= 1
|
||||
unsafe _count &-= 1
|
||||
}
|
||||
|
||||
/// Restore hash table invariants after a hole was created by `createHole`.
|
||||
@@ -29,13 +30,14 @@ extension _HTable {
|
||||
/// reach the end of the affected chain of occupied buckets.
|
||||
@usableFromInline
|
||||
@discardableResult
|
||||
@unsafe
|
||||
package mutating func resolveHole(
|
||||
at bucket: Bucket,
|
||||
hashGenerator: (Bucket) -> Int,
|
||||
mover: (Bucket, Bucket) -> Void,
|
||||
) -> Bucket {
|
||||
if isSmall {
|
||||
return finalizeHole(at: bucket, mover: mover)
|
||||
return unsafe finalizeHole(at: bucket, mover: mover)
|
||||
}
|
||||
assert(isOccupied(bucket))
|
||||
|
||||
@@ -88,8 +90,8 @@ extension _HTable {
|
||||
// incremental updates here (like the original thesis suggests), but it's
|
||||
// unclear if the benefits of that would outweigh the costs.)
|
||||
// (FIXME: Try it and see.)
|
||||
if _maxProbeLength > _count {
|
||||
_maxProbeLength = _count
|
||||
if _maxProbeLength > self.count {
|
||||
_maxProbeLength = self.count
|
||||
}
|
||||
|
||||
return hole
|
||||
@@ -102,14 +104,15 @@ extension _HTable {
|
||||
/// does enough to allow the hash table to get resized.
|
||||
@discardableResult
|
||||
@usableFromInline
|
||||
@unsafe
|
||||
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
|
||||
_maxProbeLength = _count
|
||||
let last = Bucket(offset: self.count) // Note: _count was decreased by createHole
|
||||
_maxProbeLength = self.count
|
||||
guard bucket < last else { return bucket }
|
||||
mover(last, bucket)
|
||||
return last
|
||||
|
||||
@@ -25,7 +25,7 @@ extension _HTable {
|
||||
// Let's reverse the order of members, to emphasize that this is not an
|
||||
// ordered container.
|
||||
let c = source.count
|
||||
self._count = c
|
||||
unsafe self._count = c
|
||||
self._maxProbeLength = c
|
||||
var dst = Bucket(offset: c)
|
||||
var it = source.makeBucketIterator()
|
||||
|
||||
@@ -18,6 +18,7 @@ import InternalCollectionsUtilities
|
||||
extension _HTable {
|
||||
/// The minimum hash table scale.
|
||||
@_alwaysEmitIntoClient
|
||||
@safe
|
||||
package static var minimumScale: UInt8 {
|
||||
@_effects(readnone)
|
||||
@_transparent
|
||||
@@ -28,6 +29,7 @@ extension _HTable {
|
||||
|
||||
/// The maximum hash table scale.
|
||||
@_alwaysEmitIntoClient
|
||||
@safe
|
||||
package static var maximumScale: UInt8 {
|
||||
@_effects(readnone)
|
||||
@_transparent
|
||||
@@ -38,6 +40,7 @@ extension _HTable {
|
||||
|
||||
/// The maximum number of items for which we do not create a hash table.
|
||||
@usableFromInline
|
||||
@safe
|
||||
package static var maximumUnhashedCount: Int {
|
||||
@_effects(readnone)
|
||||
get {
|
||||
@@ -47,6 +50,7 @@ extension _HTable {
|
||||
|
||||
@inlinable
|
||||
@inline(__always)
|
||||
@safe
|
||||
package static func wordCount(forScale scale: UInt8) -> Int {
|
||||
guard scale > 0 else { return 0 }
|
||||
let shift = Swift.max(UInt(scale), Word.wordShift) - Word.wordShift
|
||||
@@ -74,24 +78,29 @@ extension _HTable {
|
||||
|
||||
/// The numerator of the maximum hash table load factor.
|
||||
@_transparent
|
||||
@safe
|
||||
internal static var _maxLFNum: UInt { 7 }
|
||||
|
||||
/// The denominator of the maximum hash table load factor.
|
||||
@_transparent
|
||||
@safe
|
||||
internal static var _maxLFDenom: UInt { 8 }
|
||||
|
||||
/// The numerator of the minimum hash table load factor.
|
||||
@_transparent
|
||||
@safe
|
||||
internal static var _minLFNum: UInt { 1 }
|
||||
|
||||
/// The denominator of minimum hash table load factor.
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
@safe
|
||||
internal static var _minLFDenom: UInt { 8 }
|
||||
|
||||
/// The minimum number of items that can be held in a hash table of the given scale.
|
||||
@usableFromInline
|
||||
@_effects(readnone)
|
||||
@safe
|
||||
package static func minimumCapacity(forScale scale: UInt8) -> Int {
|
||||
guard scale >= minimumScale else { return 0 }
|
||||
precondition(scale <= maximumScale)
|
||||
@@ -102,6 +111,7 @@ extension _HTable {
|
||||
/// The maximum number of items that can be held in a hash table of the given scale.
|
||||
@usableFromInline
|
||||
@_effects(readnone)
|
||||
@safe
|
||||
package static func maximumCapacity(forScale scale: UInt8) -> Int {
|
||||
let scale = Swift.max(scale, minimumScale &- 1)
|
||||
let bucketCount: UInt = 1 &<< scale
|
||||
@@ -112,6 +122,7 @@ extension _HTable {
|
||||
/// The minimum hash table scale that can hold the specified number of elements.
|
||||
@usableFromInline
|
||||
@_effects(readnone)
|
||||
@safe
|
||||
package static func minimumScale(forCapacity capacity: Int) -> UInt8 {
|
||||
guard capacity > maximumUnhashedCount else { return 0 }
|
||||
let capacity = UInt(truncatingIfNeeded: Swift.max(capacity, 1))
|
||||
@@ -132,6 +143,7 @@ extension _HTable {
|
||||
|
||||
@usableFromInline
|
||||
@_effects(readnone)
|
||||
@safe
|
||||
package static func dynamicStorageParameters(
|
||||
minimumCapacity: Int
|
||||
) -> (scale: UInt8, capacity: Int) {
|
||||
|
||||
@@ -17,28 +17,35 @@ import InternalCollectionsUtilities
|
||||
|
||||
@usableFromInline
|
||||
@frozen
|
||||
@safe
|
||||
package struct _HTable: ~Copyable {
|
||||
@usableFromInline
|
||||
package typealias Word = _UnsafeBitSet._Word
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@unsafe // FIXME: Only mutations are unsafe
|
||||
package var _count: Int
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@unsafe // FIXME: Only mutations are unsafe
|
||||
package var _capacity: Int
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@unsafe
|
||||
package let _bitmap: UnsafeMutablePointer<Word>?
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@safe
|
||||
package var _maxProbeLength: Int
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@safe
|
||||
package let scale: UInt8
|
||||
|
||||
// FIXME: Add a reservedScale for UniqueSet/UniqueDictonary
|
||||
|
||||
@inlinable
|
||||
@safe
|
||||
internal init(
|
||||
_capacity: Int,
|
||||
scale: UInt8
|
||||
@@ -46,22 +53,23 @@ package struct _HTable: ~Copyable {
|
||||
assert(
|
||||
_capacity >= Self.minimumCapacity(forScale: scale)
|
||||
&& _capacity <= Self.maximumCapacity(forScale: scale))
|
||||
self._count = 0
|
||||
self._capacity = _capacity
|
||||
unsafe self._count = 0
|
||||
unsafe self._capacity = _capacity
|
||||
self._maxProbeLength = 0
|
||||
self.scale = scale
|
||||
if scale == 0 {
|
||||
self._bitmap = nil
|
||||
unsafe self._bitmap = nil
|
||||
} else {
|
||||
assert(scale >= Self.minimumScale && scale <= Self.maximumScale)
|
||||
let wordCount = _HTable.wordCount(forScale: scale)
|
||||
let bitmap = UnsafeMutablePointer<Word>.allocate(capacity: wordCount)
|
||||
bitmap.initialize(repeating: .empty, count: wordCount)
|
||||
self._bitmap = bitmap
|
||||
unsafe bitmap.initialize(repeating: .empty, count: wordCount)
|
||||
unsafe self._bitmap = bitmap
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@safe
|
||||
internal init(capacity: Int) {
|
||||
assert(capacity >= 0)
|
||||
self.init(
|
||||
@@ -70,6 +78,7 @@ package struct _HTable: ~Copyable {
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@safe
|
||||
internal init(minimumCapacity: Int) {
|
||||
precondition(minimumCapacity >= 0, "Capacity must be nonnegative")
|
||||
let p = Self.dynamicStorageParameters(minimumCapacity: minimumCapacity)
|
||||
@@ -79,44 +88,50 @@ package struct _HTable: ~Copyable {
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
deinit {
|
||||
_bitmap?.deallocate()
|
||||
unsafe _bitmap?.deallocate()
|
||||
}
|
||||
}
|
||||
|
||||
extension _HTable {
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
@safe
|
||||
package var isSmall: Bool {
|
||||
_bitmap == nil
|
||||
unsafe _bitmap == nil
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
@safe
|
||||
package var count: Int {
|
||||
_count
|
||||
unsafe _assumeNonNegative(_count)
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
@safe
|
||||
package var capacity: Int {
|
||||
_capacity
|
||||
unsafe _assumeNonNegative(_capacity)
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
@safe
|
||||
package var isEmpty: Bool {
|
||||
_count == 0
|
||||
count == 0
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
@safe
|
||||
package var isFull: Bool {
|
||||
_count == capacity
|
||||
count == capacity
|
||||
}
|
||||
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
@safe
|
||||
package var wordCount: Int {
|
||||
if isSmall { return 0 }
|
||||
return Word.wordCount(forBitCount: bucketCount)
|
||||
@@ -126,18 +141,21 @@ extension _HTable {
|
||||
extension _HTable {
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
@safe
|
||||
package var startBucket: Bucket {
|
||||
Bucket(offset: 0)
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
@safe
|
||||
package var endBucket: Bucket {
|
||||
Bucket(offset: bucketCount)
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
@safe
|
||||
package var storageCapacity: Int {
|
||||
if isSmall { return capacity }
|
||||
return 1 &<< scale
|
||||
@@ -145,18 +163,21 @@ extension _HTable {
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
@safe
|
||||
package var bucketCount: UInt {
|
||||
UInt(bitPattern: storageCapacity)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
@inlinable
|
||||
@safe
|
||||
package func isValid(_ bucket: Bucket) -> Bool {
|
||||
bucket._offset < bucketCount
|
||||
}
|
||||
|
||||
@_transparent
|
||||
@inlinable
|
||||
@safe
|
||||
package func wrapBucket(after bucket: inout Bucket) {
|
||||
assert(isValid(bucket))
|
||||
bucket._offset &+= 1
|
||||
@@ -167,12 +188,14 @@ extension _HTable {
|
||||
|
||||
@_transparent
|
||||
@inlinable
|
||||
@safe
|
||||
package func formBucket(after bucket: inout Bucket) {
|
||||
assert(isValid(bucket))
|
||||
bucket._offset &+= 1
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@safe
|
||||
package var bitmap: Bitmap {
|
||||
@_lifetime(borrow self)
|
||||
get {
|
||||
@@ -182,20 +205,23 @@ extension _HTable {
|
||||
|
||||
@_transparent
|
||||
@inlinable
|
||||
@safe
|
||||
package func isOccupied(_ bucket: Bucket) -> Bool {
|
||||
if isSmall { return bucket._offset < _count }
|
||||
if isSmall { return bucket._offset < count }
|
||||
return bitmap.isOccupied(bucket)
|
||||
}
|
||||
}
|
||||
|
||||
extension _HTable {
|
||||
@_transparent
|
||||
@safe
|
||||
internal func idealBucket(forHashValue hashValue: Int) -> Bucket {
|
||||
let hashValue = UInt(truncatingIfNeeded: hashValue)
|
||||
return Bucket(offset: hashValue & (bucketCount &- 1))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
@safe
|
||||
internal func probeLength(
|
||||
from start: Bucket,
|
||||
to end: Bucket
|
||||
@@ -207,6 +233,7 @@ extension _HTable {
|
||||
}
|
||||
|
||||
@_transparent
|
||||
@safe
|
||||
internal func probeLength(
|
||||
forHashValue hashValue: Int,
|
||||
in bucket: Bucket
|
||||
@@ -218,8 +245,9 @@ extension _HTable {
|
||||
|
||||
extension _HTable {
|
||||
@usableFromInline
|
||||
@safe
|
||||
package mutating func clear() {
|
||||
self._count = 0
|
||||
unsafe self._count = 0
|
||||
self.bitmap.clearAll()
|
||||
self._maxProbeLength = 0
|
||||
}
|
||||
@@ -227,8 +255,9 @@ extension _HTable {
|
||||
|
||||
extension _HTable {
|
||||
@usableFromInline
|
||||
@safe
|
||||
package func isTriviallyIdentical(to other: borrowing Self) -> Bool {
|
||||
self._count == other._count
|
||||
unsafe self._count == other._count
|
||||
&& self._capacity == other._capacity
|
||||
&& self._bitmap == other._bitmap
|
||||
&& self._maxProbeLength == other._maxProbeLength
|
||||
|
||||
@@ -22,7 +22,7 @@ extension RigidArray where Element: ~Copyable {
|
||||
@unsafe
|
||||
internal mutating func _appendUnchecked(_ item: consuming Element) {
|
||||
unsafe _storage.initializeElement(at: _count, to: item)
|
||||
_count &+= 1
|
||||
unsafe _count &+= 1
|
||||
}
|
||||
|
||||
/// Adds an element to the end of the array.
|
||||
@@ -86,14 +86,14 @@ extension RigidArray where Element: ~Copyable {
|
||||
) throws(E) -> Range<Int> {
|
||||
precondition(newItemCount >= 0, "Cannot add a negative number of items")
|
||||
precondition(freeCapacity >= newItemCount, "RigidArray capacity overflow")
|
||||
let buffer = _freeSpace._extracting(first: newItemCount)
|
||||
var span = OutputSpan(buffer: buffer, initializedCount: 0)
|
||||
let buffer = unsafe _freeSpace._extracting(first: newItemCount)
|
||||
var span = unsafe OutputSpan(buffer: buffer, initializedCount: 0)
|
||||
defer {
|
||||
_count &+= span.finalize(for: buffer)
|
||||
unsafe _count &+= unsafe span.finalize(for: buffer)
|
||||
span = OutputSpan()
|
||||
}
|
||||
try initializer(&span)
|
||||
return Range(uncheckedBounds: (count, count &+ span.count))
|
||||
return unsafe Range(uncheckedBounds: (count, count &+ span.count))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,13 +105,13 @@ extension RigidArray where Element: ~Copyable {
|
||||
moving items: UnsafeMutableBufferPointer<Element>
|
||||
) -> Range<Int> {
|
||||
guard items.count > 0 else {
|
||||
return Range(uncheckedBounds: (_count, _count))
|
||||
return unsafe Range(uncheckedBounds: (self.count, self.count))
|
||||
}
|
||||
let c = unsafe _freeSpace._moveInitializePrefix(from: items)
|
||||
assert(c == items.count)
|
||||
let origCount = _count
|
||||
_count &+= items.count
|
||||
return Range(uncheckedBounds: (origCount, _count))
|
||||
let origCount = self.count
|
||||
unsafe _count &+= items.count
|
||||
return unsafe Range(uncheckedBounds: (origCount, self.count))
|
||||
}
|
||||
|
||||
/// Moves the elements of a buffer to the end of this array, leaving the
|
||||
@@ -127,6 +127,7 @@ extension RigidArray where Element: ~Copyable {
|
||||
/// - Complexity: O(`items.count`)
|
||||
@_alwaysEmitIntoClient
|
||||
@discardableResult
|
||||
@unsafe
|
||||
public mutating func append(
|
||||
moving items: UnsafeMutableBufferPointer<Element>
|
||||
) -> Range<Int> {
|
||||
@@ -151,8 +152,8 @@ extension RigidArray where Element: ~Copyable {
|
||||
moving items: inout InputSpan<Element>
|
||||
) -> Range<Int> {
|
||||
// FIXME: Remove this when `InputSpan` starts conforming to RangeReplaceableContainer
|
||||
items.withUnsafeMutableBufferPointer { buffer, count in
|
||||
let source = buffer._extracting(last: count)
|
||||
unsafe items.withUnsafeMutableBufferPointer { buffer, count in
|
||||
let source = unsafe buffer._extracting(last: count)
|
||||
count = 0
|
||||
return unsafe self.append(moving: source)
|
||||
}
|
||||
@@ -176,8 +177,8 @@ extension RigidArray where Element: ~Copyable {
|
||||
) -> Range<Int> {
|
||||
// FIXME: Remove this when `OutputSpan` starts conforming to RangeReplaceableContainer
|
||||
precondition(items.count <= freeCapacity, "RigidArray capacity overflow")
|
||||
return items.withUnsafeMutableBufferPointer { buffer, count in
|
||||
let source = buffer._extracting(first: count)
|
||||
return unsafe items.withUnsafeMutableBufferPointer { buffer, count in
|
||||
let source = unsafe buffer._extracting(first: count)
|
||||
count = 0
|
||||
return unsafe _appendUnchecked(moving: source)
|
||||
}
|
||||
@@ -213,13 +214,13 @@ extension RigidArray {
|
||||
copying newElements: UnsafeBufferPointer<Element>
|
||||
) -> Range<Int> {
|
||||
guard newElements.count > 0 else {
|
||||
return Range(uncheckedBounds: (_count, _count))
|
||||
return unsafe Range(uncheckedBounds: (self.count, self.count))
|
||||
}
|
||||
unsafe _freeSpace.baseAddress.unsafelyUnwrapped.initialize(
|
||||
from: newElements.baseAddress.unsafelyUnwrapped, count: newElements.count)
|
||||
let origCount = _count
|
||||
_count &+= newElements.count
|
||||
return Range(uncheckedBounds: (origCount, _count))
|
||||
let origCount = self.count
|
||||
unsafe _count &+= newElements.count
|
||||
return unsafe Range(uncheckedBounds: (origCount, self.count))
|
||||
}
|
||||
|
||||
/// Copies the elements of a buffer to the end of this array.
|
||||
@@ -234,6 +235,7 @@ extension RigidArray {
|
||||
/// - Complexity: O(`newElements.count`)
|
||||
@_alwaysEmitIntoClient
|
||||
@discardableResult
|
||||
@unsafe
|
||||
public mutating func append(
|
||||
copying newElements: UnsafeBufferPointer<Element>
|
||||
) -> Range<Int> {
|
||||
@@ -255,6 +257,7 @@ extension RigidArray {
|
||||
/// - Complexity: O(`items.count`)
|
||||
@_alwaysEmitIntoClient
|
||||
@discardableResult
|
||||
@unsafe
|
||||
public mutating func append(
|
||||
copying items: UnsafeMutableBufferPointer<Element>
|
||||
) -> Range<Int> {
|
||||
@@ -285,7 +288,7 @@ extension RigidArray {
|
||||
prefixOf items: S
|
||||
) -> S.Iterator {
|
||||
let (it, c) = unsafe items._copyContents(initializing: _freeSpace)
|
||||
_count += c
|
||||
unsafe _count += c
|
||||
return it
|
||||
}
|
||||
|
||||
@@ -298,8 +301,8 @@ extension RigidArray {
|
||||
copying newElements: borrowing Source
|
||||
) throws(Source.Failure)
|
||||
where Source.Element == Element {
|
||||
let target = _freeSpace
|
||||
_count += try newElements._copyContents(intoPrefixOf: target)
|
||||
let target = unsafe _freeSpace
|
||||
unsafe _count += try newElements._copyContents(intoPrefixOf: target)
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
@@ -21,12 +21,12 @@ import SpanPreview
|
||||
extension RigidArray where Element: ~Copyable {
|
||||
@_lifetime(&self)
|
||||
public mutating func _consumeAll() -> InputSpan<Element> {
|
||||
let buffer = _items
|
||||
self._count = 0
|
||||
let result = InputSpan(
|
||||
let buffer = unsafe _items
|
||||
unsafe self._count = 0
|
||||
let result = unsafe InputSpan(
|
||||
buffer: buffer,
|
||||
initializedCount: buffer.count)
|
||||
return _overrideLifetime(result, mutating: &self)
|
||||
return unsafe _overrideLifetime(result, mutating: &self)
|
||||
}
|
||||
|
||||
/// Remove the specified subrange of items from this array,
|
||||
@@ -54,13 +54,13 @@ extension RigidArray where Element: ~Copyable {
|
||||
return subrange.lowerBound
|
||||
}
|
||||
let buffer = unsafe _storage.extracting(subrange)
|
||||
var span = InputSpan(buffer: buffer, initializedCount: buffer.count)
|
||||
var span = unsafe InputSpan(buffer: buffer, initializedCount: buffer.count)
|
||||
|
||||
consumer(&span)
|
||||
_ = consume span
|
||||
|
||||
_closeGap(at: subrange.lowerBound, count: subrange.count)
|
||||
_count -= subrange.count
|
||||
unsafe _closeGap(at: subrange.lowerBound, count: subrange.count)
|
||||
unsafe _count -= subrange.count
|
||||
return subrange.lowerBound
|
||||
}
|
||||
|
||||
@@ -133,9 +133,9 @@ extension RigidArray where Element: ~Copyable {
|
||||
consumingWith consumer: (inout InputSpan<Element>) -> Void
|
||||
) {
|
||||
precondition(
|
||||
n >= 0 && n <= _count,
|
||||
n >= 0 && n <= self.count,
|
||||
"Count of elements to consume is out of bounds")
|
||||
self.consumeSubrange(_count &- n ..< _count, consumingWith: consumer)
|
||||
self.consumeSubrange(self.count &- n ..< self.count, consumingWith: consumer)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -157,40 +157,44 @@ extension RigidArray where Element: ~Copyable {
|
||||
extension RigidArray where Element: ~Copyable {
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
@frozen
|
||||
@safe
|
||||
public struct SubrangeConsumer: ~Copyable, ~Escapable {
|
||||
// FIXME: We have to use our own MutableRef because the standard one
|
||||
// provides no access to the underlying pointer. See deinit why we need it.
|
||||
@usableFromInline
|
||||
@unsafe
|
||||
internal var _base: _MutableRef<RigidArray>
|
||||
|
||||
@usableFromInline
|
||||
@unsafe
|
||||
internal var _offsetRange: Range<Int>
|
||||
|
||||
@usableFromInline
|
||||
@unsafe
|
||||
internal var _remainder: UnsafeMutableBufferPointer<Element>
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@inline(__always)
|
||||
@_lifetime(&_base)
|
||||
internal init(_base: inout RigidArray, offsetRange: Range<Int>) {
|
||||
|
||||
self._remainder = _base._storage._extracting(unchecked: offsetRange)
|
||||
self._base = _MutableRef(&_base)
|
||||
self._offsetRange = offsetRange
|
||||
_base._checkValidBounds(offsetRange)
|
||||
unsafe self._remainder = _base._storage._extracting(unchecked: offsetRange)
|
||||
unsafe self._base = _MutableRef(&_base)
|
||||
unsafe self._offsetRange = offsetRange
|
||||
}
|
||||
|
||||
@inlinable
|
||||
deinit {
|
||||
self._remainder.deinitialize()
|
||||
unsafe self._remainder.deinitialize()
|
||||
|
||||
// FIXME: This needs to be written as
|
||||
// self._base.value.closeGap(offsets: self._offsetRange)
|
||||
// but unfortunately we cannot mutate self in deinit yet.
|
||||
// MutableRef's dereferencing operation is necessarily declared mutating
|
||||
// to avoid exclusivity violations.
|
||||
self._base._pointer.pointee
|
||||
unsafe self._base._pointer.pointee
|
||||
._closeGap(at: _offsetRange.lowerBound, count: _offsetRange.count)
|
||||
self._base._pointer.pointee._count -= _offsetRange.count
|
||||
unsafe self._base._pointer.pointee._count -= _offsetRange.count
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -201,25 +205,25 @@ extension RigidArray.SubrangeConsumer where Element: ~Copyable {
|
||||
|
||||
@inlinable
|
||||
public var count: Int {
|
||||
_remainder.count
|
||||
unsafe _remainder.count
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@_lifetime(&self)
|
||||
@_lifetime(self: copy self)
|
||||
public mutating func drainNext(maxCount: Int) -> InputSpan<Element> {
|
||||
if _remainder.isEmpty {
|
||||
if unsafe _remainder.isEmpty {
|
||||
return .init()
|
||||
}
|
||||
let buffer = _remainder._trim(first: maxCount)
|
||||
return _overrideLifetime(
|
||||
let buffer = unsafe _remainder._trim(first: maxCount)
|
||||
return unsafe _overrideLifetime(
|
||||
InputSpan(buffer: buffer, initializedCount: buffer.count),
|
||||
mutating: &self)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public consuming func finalize() -> Index {
|
||||
_offsetRange.lowerBound
|
||||
unsafe _offsetRange.lowerBound
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -29,7 +29,7 @@ extension RigidArray where Element: ~Copyable {
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
@inline(__always)
|
||||
public var count: Int { _count }
|
||||
public var count: Int { unsafe _assumeNonNegative(_count) }
|
||||
}
|
||||
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
@@ -68,7 +68,7 @@ extension RigidArray where Element: ~Copyable {
|
||||
@_transparent
|
||||
package func _checkItemIndex(_ index: Int) {
|
||||
precondition(
|
||||
UInt(bitPattern: index) < UInt(bitPattern: _count),
|
||||
UInt(bitPattern: index) < UInt(bitPattern: self.count),
|
||||
"Index out of bounds")
|
||||
}
|
||||
|
||||
@@ -76,7 +76,7 @@ extension RigidArray where Element: ~Copyable {
|
||||
@_transparent
|
||||
package func _checkValidIndex(_ index: Int) {
|
||||
precondition(
|
||||
UInt(bitPattern: index) <= UInt(bitPattern: _count),
|
||||
UInt(bitPattern: index) <= UInt(bitPattern: self.count),
|
||||
"Index out of bounds")
|
||||
}
|
||||
|
||||
@@ -84,7 +84,7 @@ extension RigidArray where Element: ~Copyable {
|
||||
@_transparent
|
||||
package func _checkValidBounds(_ subrange: Range<Int>) {
|
||||
precondition(
|
||||
subrange.lowerBound >= 0 && subrange.upperBound <= _count,
|
||||
subrange.lowerBound >= 0 && subrange.upperBound <= self.count,
|
||||
"Index range out of bounds")
|
||||
}
|
||||
}
|
||||
@@ -92,18 +92,20 @@ extension RigidArray where Element: ~Copyable {
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
extension RigidArray where Element: ~Copyable {
|
||||
@inlinable @inline(__always)
|
||||
@unsafe
|
||||
package func _ptr(to index: Int) -> UnsafePointer<Element> {
|
||||
_checkItemIndex(index)
|
||||
let p = _storage.baseAddress.unsafelyUnwrapped.advanced(by: index)
|
||||
return UnsafePointer(p)
|
||||
let p = unsafe _storage.baseAddress.unsafelyUnwrapped.advanced(by: index)
|
||||
return unsafe UnsafePointer(p)
|
||||
}
|
||||
|
||||
@inlinable @inline(__always)
|
||||
@unsafe
|
||||
package mutating func _mutablePtr(
|
||||
to index: Int
|
||||
) -> UnsafeMutablePointer<Element> {
|
||||
_checkItemIndex(index)
|
||||
return _storage.baseAddress.unsafelyUnwrapped.advanced(by: index)
|
||||
return unsafe _storage.baseAddress.unsafelyUnwrapped.advanced(by: index)
|
||||
}
|
||||
|
||||
#if compiler(>=6.4)
|
||||
@@ -119,12 +121,12 @@ extension RigidArray where Element: ~Copyable {
|
||||
@inline(__always)
|
||||
@_unsafeSelfDependentResult
|
||||
borrow {
|
||||
_ptr(to: position).pointee
|
||||
unsafe _ptr(to: position).pointee
|
||||
}
|
||||
@inline(__always)
|
||||
@_unsafeSelfDependentResult
|
||||
mutate {
|
||||
&_mutablePtr(to: position).pointee
|
||||
unsafe &_mutablePtr(to: position).pointee
|
||||
}
|
||||
}
|
||||
#else
|
||||
@@ -139,11 +141,11 @@ extension RigidArray where Element: ~Copyable {
|
||||
public subscript(position: Int) -> Element {
|
||||
@inline(__always)
|
||||
unsafeAddress {
|
||||
_ptr(to: position)
|
||||
unsafe _ptr(to: position)
|
||||
}
|
||||
@inline(__always)
|
||||
unsafeMutableAddress {
|
||||
_mutablePtr(to: position)
|
||||
unsafe _mutablePtr(to: position)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -397,7 +399,7 @@ extension RigidArray where Element: ~Copyable {
|
||||
after index: inout Int
|
||||
) -> MutableSpan<Element> {
|
||||
_checkValidIndex(index)
|
||||
return _mutableSpan(in: Range(uncheckedBounds: (index, count)))
|
||||
return _mutableSpan(in: unsafe Range(uncheckedBounds: (index, count)))
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@@ -410,7 +412,7 @@ extension RigidArray where Element: ~Copyable {
|
||||
precondition(maxCount > 0, "maxCount must be positive")
|
||||
let end = index._clampedUp(
|
||||
towards: count, maxDistance: maxCount, limitedBy: limit)
|
||||
return _mutableSpan(in: Range(uncheckedBounds: (index, end)))
|
||||
return _mutableSpan(in: unsafe Range(uncheckedBounds: (index, end)))
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@@ -437,6 +439,6 @@ extension RigidArray where Element: ~Copyable {
|
||||
precondition(maxCount > 0, "maxCount must be positive")
|
||||
let start = index
|
||||
index = start &- Swift.min(maxCount, start)
|
||||
return _span(in: Range(uncheckedBounds: (start, index)))
|
||||
return _span(in: unsafe Range(uncheckedBounds: (start, index)))
|
||||
}
|
||||
}
|
||||
@@ -166,11 +166,12 @@ extension RigidArray {
|
||||
|
||||
@available(*, deprecated, renamed: "replaceSubrange(_:moving:)")
|
||||
@_alwaysEmitIntoClient
|
||||
@unsafe
|
||||
public mutating func replace(
|
||||
removing subrange: Range<Int>,
|
||||
moving newElements: UnsafeMutableBufferPointer<Element>,
|
||||
) {
|
||||
replaceSubrange(subrange, moving: newElements)
|
||||
unsafe replaceSubrange(subrange, moving: newElements)
|
||||
}
|
||||
|
||||
@available(*, deprecated, renamed: "replaceSubrange(_:moving:)")
|
||||
@@ -202,20 +203,22 @@ extension RigidArray {
|
||||
|
||||
@available(*, deprecated, renamed: "replaceSubrange(_:copying:)")
|
||||
@inlinable
|
||||
@unsafe
|
||||
public mutating func replace(
|
||||
removing subrange: Range<Int>,
|
||||
copying newElements: UnsafeBufferPointer<Element>
|
||||
) {
|
||||
replaceSubrange(subrange, copying: newElements)
|
||||
unsafe replaceSubrange(subrange, copying: newElements)
|
||||
}
|
||||
|
||||
@available(*, deprecated, renamed: "replaceSubrange(_:copying:)")
|
||||
@inlinable
|
||||
@unsafe
|
||||
public mutating func replace(
|
||||
removing subrange: Range<Int>,
|
||||
copying newElements: UnsafeMutableBufferPointer<Element>
|
||||
) {
|
||||
replaceSubrange(subrange, copying: newElements)
|
||||
unsafe replaceSubrange(subrange, copying: newElements)
|
||||
}
|
||||
|
||||
@available(*, deprecated, renamed: "replaceSubrange(_:copying:)")
|
||||
|
||||
@@ -18,7 +18,7 @@ import InternalCollectionsUtilities
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
extension RigidArray where Element: ~Copyable {
|
||||
public func isTriviallyIdentical(to other: borrowing Self) -> Bool {
|
||||
self._storage._isIdentical(to: other._storage)
|
||||
unsafe self._storage._isIdentical(to: other._storage)
|
||||
&& self._count == other._count
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,8 +23,8 @@ extension RigidArray where Element: ~Copyable {
|
||||
@inlinable
|
||||
public init() {
|
||||
unsafe _ptr = ._dangling()
|
||||
_capacity = 0
|
||||
_count = 0
|
||||
unsafe _capacity = 0
|
||||
unsafe _count = 0
|
||||
}
|
||||
|
||||
/// Initializes a new rigid array with the specified capacity and no elements.
|
||||
@@ -33,12 +33,12 @@ extension RigidArray where Element: ~Copyable {
|
||||
precondition(capacity >= 0, "Array capacity must be nonnegative")
|
||||
if capacity > 0 {
|
||||
unsafe _ptr = .allocate(capacity: capacity)
|
||||
_capacity = capacity
|
||||
unsafe _capacity = capacity
|
||||
} else {
|
||||
unsafe _ptr = ._dangling()
|
||||
_capacity = 0
|
||||
unsafe _capacity = 0
|
||||
}
|
||||
_count = 0
|
||||
unsafe _count = 0
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,7 +78,7 @@ extension RigidArray /*where Element: Copyable*/ {
|
||||
public init(repeating repeatedValue: Element, count: Int) {
|
||||
self.init(capacity: count)
|
||||
unsafe _freeSpace.initialize(repeating: repeatedValue)
|
||||
_count = count
|
||||
unsafe _count = count
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -47,7 +47,7 @@ extension RigidArray where Element: ~Copyable {
|
||||
assert(last == target.endIndex)
|
||||
}
|
||||
unsafe _storage.initializeElement(at: index, to: item)
|
||||
_count += 1
|
||||
unsafe _count += 1
|
||||
return index
|
||||
}
|
||||
}
|
||||
@@ -106,13 +106,13 @@ extension RigidArray where Element: ~Copyable {
|
||||
precondition(newItemCount >= 0, "Cannot add a negative number of items")
|
||||
precondition(newItemCount <= freeCapacity, "RigidArray capacity overflow")
|
||||
let target = unsafe _openGap(at: index, count: newItemCount)
|
||||
_count &+= newItemCount
|
||||
var span = OutputSpan(buffer: target, initializedCount: 0)
|
||||
unsafe _count &+= newItemCount
|
||||
var span = unsafe OutputSpan(buffer: target, initializedCount: 0)
|
||||
defer {
|
||||
let c = span.finalize(for: target)
|
||||
let c = unsafe span.finalize(for: target)
|
||||
if c < newItemCount {
|
||||
_closeGap(at: index &+ c, count: newItemCount &- c)
|
||||
_count &-= newItemCount &- c
|
||||
unsafe _closeGap(at: index &+ c, count: newItemCount &- c)
|
||||
unsafe _count &-= newItemCount &- c
|
||||
}
|
||||
span = OutputSpan()
|
||||
}
|
||||
@@ -147,7 +147,7 @@ extension RigidArray where Element: ~Copyable {
|
||||
at index: Int
|
||||
) -> Range<Int> {
|
||||
insert(addingCount: items.count, at: index) { target in
|
||||
target._append(moving: items)
|
||||
unsafe target._append(moving: items)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -175,8 +175,8 @@ extension RigidArray where Element: ~Copyable {
|
||||
at index: Int
|
||||
) -> Range<Int> {
|
||||
// FIXME: Remove when InputSpan starts conforming to RangeReplaceableContainer
|
||||
items.withUnsafeMutableBufferPointer { buffer, count in
|
||||
let source = buffer._extracting(last: count)
|
||||
unsafe items.withUnsafeMutableBufferPointer { buffer, count in
|
||||
let source = unsafe buffer._extracting(last: count)
|
||||
count = 0
|
||||
return unsafe self.insert(moving: source, at: index)
|
||||
}
|
||||
@@ -206,8 +206,8 @@ extension RigidArray where Element: ~Copyable {
|
||||
at index: Int
|
||||
) -> Range<Int> {
|
||||
// FIXME: Remove when OutputSpan starts conforming to RangeReplaceableContainer
|
||||
items.withUnsafeMutableBufferPointer { buffer, count in
|
||||
let source = buffer._extracting(first: count)
|
||||
unsafe items.withUnsafeMutableBufferPointer { buffer, count in
|
||||
let source = unsafe buffer._extracting(first: count)
|
||||
count = 0
|
||||
return unsafe self.insert(moving: source, at: index)
|
||||
}
|
||||
@@ -279,7 +279,7 @@ extension RigidArray {
|
||||
return index ..< index
|
||||
}
|
||||
return self.insert(addingCount: newElements.count, at: index) { target in
|
||||
target._append(copying: newElements)
|
||||
unsafe target._append(copying: newElements)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -358,7 +358,7 @@ extension RigidArray {
|
||||
let res: Range<Int>? = items.withContiguousStorageIfAvailable { buffer in
|
||||
precondition(buffer.count == newCount, "Broken Collection: mismatching count")
|
||||
return self.insert(addingCount: buffer.count, at: index) { target in
|
||||
target._append(copying: buffer)
|
||||
unsafe target._append(copying: buffer)
|
||||
}
|
||||
}
|
||||
if let res { return res }
|
||||
|
||||
@@ -23,7 +23,7 @@ extension RigidArray where Element: ~Copyable {
|
||||
@inlinable
|
||||
public mutating func removeAll() {
|
||||
unsafe _items.deinitialize()
|
||||
_count = 0
|
||||
unsafe _count = 0
|
||||
}
|
||||
|
||||
/// Removes and returns the element at the specified position.
|
||||
@@ -60,8 +60,8 @@ extension RigidArray where Element: ~Copyable {
|
||||
public mutating func remove(at index: Int) -> Element {
|
||||
_checkItemIndex(index)
|
||||
let old = unsafe _storage.moveElement(from: index)
|
||||
_closeGap(at: index, count: 1)
|
||||
_count -= 1
|
||||
unsafe _closeGap(at: index, count: 1)
|
||||
unsafe _count -= 1
|
||||
return old
|
||||
}
|
||||
|
||||
@@ -76,8 +76,8 @@ extension RigidArray where Element: ~Copyable {
|
||||
@discardableResult
|
||||
public mutating func removeLast() -> Element {
|
||||
precondition(!isEmpty, "Cannot remove last element from an empty array")
|
||||
let old = unsafe _storage.moveElement(from: _count - 1)
|
||||
_count -= 1
|
||||
let old = unsafe _storage.moveElement(from: self.count - 1)
|
||||
unsafe _count -= 1
|
||||
return old
|
||||
}
|
||||
|
||||
@@ -96,12 +96,12 @@ extension RigidArray where Element: ~Copyable {
|
||||
public mutating func removeLast(_ k: Int) {
|
||||
if k == 0 { return }
|
||||
precondition(
|
||||
k >= 0 && k <= _count,
|
||||
k >= 0 && k <= self.count,
|
||||
"Count of elements to remove is out of bounds")
|
||||
unsafe _storage.extracting(
|
||||
Range(uncheckedBounds: (_count - k, _count))
|
||||
Range(uncheckedBounds: (self.count - k, self.count))
|
||||
).deinitialize()
|
||||
_count &-= k
|
||||
unsafe _count &-= k
|
||||
}
|
||||
|
||||
/// Removes the specified subrange of elements from the array.
|
||||
@@ -120,8 +120,8 @@ extension RigidArray where Element: ~Copyable {
|
||||
_checkValidBounds(bounds)
|
||||
guard !bounds.isEmpty else { return bounds.lowerBound }
|
||||
unsafe _storage.extracting(bounds).deinitialize()
|
||||
_closeGap(at: bounds.lowerBound, count: bounds.count)
|
||||
_count -= bounds.count
|
||||
unsafe _closeGap(at: bounds.lowerBound, count: bounds.count)
|
||||
unsafe _count -= bounds.count
|
||||
return bounds.lowerBound
|
||||
}
|
||||
|
||||
|
||||
@@ -70,11 +70,12 @@ extension RigidArray where Element: ~Copyable {
|
||||
precondition(
|
||||
newItemCount - subrange.count <= freeCapacity,
|
||||
"RigidArray capacity overflow")
|
||||
return try _uncheckedReplaceSubrange(
|
||||
return unsafe try _uncheckedReplaceSubrange(
|
||||
subrange, addingCount: newItemCount, initializingWith: initializer)
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@unsafe
|
||||
internal mutating func _uncheckedReplaceSubrange<E: Error>(
|
||||
_ subrange: Range<Int>,
|
||||
addingCount newItemCount: Int,
|
||||
@@ -82,20 +83,20 @@ extension RigidArray where Element: ~Copyable {
|
||||
) throws(E) -> Range<Int> {
|
||||
// Destroy removed items
|
||||
unsafe _items.extracting(subrange).deinitialize()
|
||||
let target = _resizeGap(in: subrange, to: newItemCount)
|
||||
var span = OutputSpan(buffer: target, initializedCount: 0)
|
||||
let target = unsafe _resizeGap(in: subrange, to: newItemCount)
|
||||
var span = unsafe OutputSpan(buffer: target, initializedCount: 0)
|
||||
defer {
|
||||
let c = span.finalize(for: target)
|
||||
let c = unsafe span.finalize(for: target)
|
||||
if c < newItemCount {
|
||||
self._closeGap(
|
||||
unsafe self._closeGap(
|
||||
at: subrange.lowerBound &+ c,
|
||||
count: newItemCount &- c)
|
||||
_count &-= newItemCount &- c
|
||||
unsafe _count &-= newItemCount &- c
|
||||
}
|
||||
span = OutputSpan()
|
||||
}
|
||||
try initializer(&span)
|
||||
return Range(uncheckedBounds: (
|
||||
return unsafe Range(uncheckedBounds: (
|
||||
subrange.lowerBound, subrange.lowerBound + newItemCount))
|
||||
}
|
||||
}
|
||||
@@ -163,7 +164,7 @@ extension RigidArray where Element: ~Copyable {
|
||||
precondition(
|
||||
newItemCount - subrange.count <= freeCapacity,
|
||||
"RigidArray capacity overflow")
|
||||
return try _uncheckedReplaceSubrange(
|
||||
return unsafe try _uncheckedReplaceSubrange(
|
||||
subrange,
|
||||
consumingWith: consumer,
|
||||
addingCount: newItemCount,
|
||||
@@ -171,6 +172,7 @@ extension RigidArray where Element: ~Copyable {
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@unsafe
|
||||
internal mutating func _uncheckedReplaceSubrange<E: Error>(
|
||||
_ subrange: Range<Int>,
|
||||
consumingWith consumer: (inout InputSpan<Element>) -> Void,
|
||||
@@ -180,27 +182,27 @@ extension RigidArray where Element: ~Copyable {
|
||||
do {
|
||||
// Consume items to be removed
|
||||
let buffer = unsafe _storage.extracting(subrange)
|
||||
var span = InputSpan(buffer: buffer, initializedCount: buffer.count)
|
||||
var span = unsafe InputSpan(buffer: buffer, initializedCount: buffer.count)
|
||||
consumer(&span)
|
||||
_ = consume span
|
||||
}
|
||||
do {
|
||||
// Insert new items
|
||||
let target = _resizeGap(in: subrange, to: newItemCount)
|
||||
var span = OutputSpan(buffer: target, initializedCount: 0)
|
||||
let target = unsafe _resizeGap(in: subrange, to: newItemCount)
|
||||
var span = unsafe OutputSpan(buffer: target, initializedCount: 0)
|
||||
defer {
|
||||
let c = span.finalize(for: target)
|
||||
let c = unsafe span.finalize(for: target)
|
||||
if c < newItemCount {
|
||||
self._closeGap(
|
||||
unsafe self._closeGap(
|
||||
at: subrange.lowerBound &+ c,
|
||||
count: newItemCount &- c)
|
||||
_count &-= newItemCount &- c
|
||||
unsafe _count &-= newItemCount &- c
|
||||
}
|
||||
span = OutputSpan()
|
||||
}
|
||||
try initializer(&span)
|
||||
}
|
||||
return Range(uncheckedBounds: (
|
||||
return unsafe Range(uncheckedBounds: (
|
||||
subrange.lowerBound, subrange.lowerBound + newItemCount))
|
||||
}
|
||||
#endif
|
||||
@@ -244,7 +246,7 @@ extension RigidArray where Element: ~Copyable {
|
||||
moving newElements: UnsafeMutableBufferPointer<Element>,
|
||||
) -> Range<Int> {
|
||||
replaceSubrange(subrange, addingCount: newElements.count) { target in
|
||||
target.withUnsafeMutableBufferPointer { buffer, count in
|
||||
unsafe target.withUnsafeMutableBufferPointer { buffer, count in
|
||||
count = unsafe buffer._moveInitializePrefix(from: newElements)
|
||||
}
|
||||
}
|
||||
@@ -283,8 +285,8 @@ extension RigidArray where Element: ~Copyable {
|
||||
_ subrange: Range<Int>,
|
||||
moving items: inout InputSpan<Element>
|
||||
) -> Range<Int> {
|
||||
items.withUnsafeMutableBufferPointer { buffer, count in
|
||||
let source = buffer._extracting(last: count)
|
||||
unsafe items.withUnsafeMutableBufferPointer { buffer, count in
|
||||
let source = unsafe buffer._extracting(last: count)
|
||||
count = 0
|
||||
return unsafe self.replaceSubrange(subrange, moving: source)
|
||||
}
|
||||
@@ -323,8 +325,8 @@ extension RigidArray where Element: ~Copyable {
|
||||
_ subrange: Range<Int>,
|
||||
moving items: inout OutputSpan<Element>
|
||||
) -> Range<Int> {
|
||||
items.withUnsafeMutableBufferPointer { buffer, count in
|
||||
let source = buffer._extracting(first: count)
|
||||
unsafe items.withUnsafeMutableBufferPointer { buffer, count in
|
||||
let source = unsafe buffer._extracting(first: count)
|
||||
count = 0
|
||||
return unsafe self.replaceSubrange(subrange, moving: source)
|
||||
}
|
||||
@@ -366,7 +368,7 @@ extension RigidArray where Element: ~Copyable {
|
||||
) -> Range<Int> {
|
||||
// FIXME: Remove this in favor of the generic algorithm over DrainableContainer
|
||||
unsafe newElements._unsafeEdit { buffer, count in
|
||||
let source = buffer._extracting(first: count)
|
||||
let source = unsafe buffer._extracting(first: count)
|
||||
count = 0
|
||||
return unsafe self.replaceSubrange(subrange, moving: source)
|
||||
}
|
||||
@@ -447,7 +449,7 @@ extension RigidArray {
|
||||
copying newElements: UnsafeBufferPointer<Element>
|
||||
) -> Range<Int> {
|
||||
replaceSubrange(subrange, addingCount: newElements.count) { target in
|
||||
target.withUnsafeMutableBufferPointer { buffer, count in
|
||||
unsafe target.withUnsafeMutableBufferPointer { buffer, count in
|
||||
count = unsafe buffer._initializePrefix(copying: newElements)
|
||||
}
|
||||
}
|
||||
@@ -481,6 +483,7 @@ extension RigidArray {
|
||||
/// - Complexity: O(`self.count` + `newElements.count`)
|
||||
@_alwaysEmitIntoClient
|
||||
@discardableResult
|
||||
@unsafe
|
||||
public mutating func replaceSubrange(
|
||||
_ subrange: Range<Int>,
|
||||
copying newElements: UnsafeMutableBufferPointer<Element>
|
||||
@@ -534,7 +537,7 @@ extension RigidArray {
|
||||
newCount: Int
|
||||
) -> Range<Int> {
|
||||
self.replaceSubrange(subrange, addingCount: newCount) { target in
|
||||
target.withUnsafeMutableBufferPointer { dst, dstCount in
|
||||
unsafe target.withUnsafeMutableBufferPointer { dst, dstCount in
|
||||
let done: Void? = newElements.withContiguousStorageIfAvailable { src in
|
||||
let i = unsafe dst._initializePrefix(copying: src)
|
||||
precondition(
|
||||
|
||||
@@ -21,6 +21,7 @@ import InternalCollectionsUtilities
|
||||
/// noncopyable elements.
|
||||
@frozen
|
||||
@available(*, unavailable, message: "RigidArray requires a Swift 6.2 toolchain")
|
||||
@safe
|
||||
public struct RigidArray<Element: ~Copyable>: ~Copyable {
|
||||
@usableFromInline
|
||||
internal var _ptr: UnsafeMutablePointer<Element>
|
||||
@@ -83,33 +84,37 @@ public struct RigidArray<Element: ~Copyable>: ~Copyable {
|
||||
/// the use of ``UniqueArray`` rather than `RigidArray`. (For copyable elements,
|
||||
/// the standard `Array` is an even more convenient choice.)
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
@safe
|
||||
@frozen
|
||||
@safe
|
||||
public struct RigidArray<Element: ~Copyable>: ~Copyable {
|
||||
@usableFromInline
|
||||
@unsafe
|
||||
internal var _ptr: UnsafeMutablePointer<Element>
|
||||
|
||||
@usableFromInline
|
||||
@unsafe // Setting this is unsafe
|
||||
internal var _capacity: Int
|
||||
|
||||
@usableFromInline
|
||||
@unsafe // Setting this is unsafe
|
||||
internal var _count: Int
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
deinit {
|
||||
if _capacity == 0 {
|
||||
if capacity == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
unsafe _ptr.deinitialize(count: _count)
|
||||
unsafe _ptr.deinitialize(count: count)
|
||||
unsafe _ptr.deallocate()
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@unsafe
|
||||
package init(_storage: UnsafeMutableBufferPointer<Element>, count: Int) {
|
||||
unsafe self._ptr = _storage.baseAddress.unsafelyUnwrapped
|
||||
self._capacity = _storage.count
|
||||
self._count = count
|
||||
unsafe self._capacity = _storage.count
|
||||
unsafe self._count = count
|
||||
}
|
||||
}
|
||||
|
||||
@@ -122,6 +127,7 @@ extension RigidArray: @unchecked Sendable where Element: Sendable & ~Copyable {}
|
||||
extension RigidArray where Element: ~Copyable {
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
@unsafe
|
||||
internal var _storage: UnsafeMutableBufferPointer<Element> {
|
||||
unsafe UnsafeMutableBufferPointer<Element>(start: _ptr, count: _capacity)
|
||||
}
|
||||
@@ -131,7 +137,7 @@ extension RigidArray where Element: ~Copyable {
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
@_transparent
|
||||
public var capacity: Int { _assumeNonNegative(_capacity) }
|
||||
public var capacity: Int { unsafe _assumeNonNegative(_capacity) }
|
||||
|
||||
/// The number of additional elements that can be added to this array without
|
||||
/// exceeding its storage capacity.
|
||||
@@ -157,11 +163,13 @@ extension RigidArray where Element: ~Copyable {
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
extension RigidArray where Element: ~Copyable {
|
||||
@inlinable
|
||||
@unsafe
|
||||
internal var _items: UnsafeMutableBufferPointer<Element> {
|
||||
unsafe _storage.extracting(Range(uncheckedBounds: (0, _count)))
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@unsafe
|
||||
internal var _freeSpace: UnsafeMutableBufferPointer<Element> {
|
||||
unsafe _storage.extracting(Range(uncheckedBounds: (_count, capacity)))
|
||||
}
|
||||
@@ -236,21 +244,21 @@ extension RigidArray where Element: ~Copyable {
|
||||
public mutating func edit<E: Error, R: ~Copyable>(
|
||||
_ body: (inout OutputSpan<Element>) throws(E) -> R
|
||||
) throws(E) -> R {
|
||||
var span = OutputSpan(buffer: _storage, initializedCount: _count)
|
||||
var span = unsafe OutputSpan(buffer: _storage, initializedCount: _count)
|
||||
defer {
|
||||
_count = span.finalize(for: _storage)
|
||||
unsafe _count = unsafe span.finalize(for: _storage)
|
||||
span = OutputSpan()
|
||||
}
|
||||
return try body(&span)
|
||||
}
|
||||
|
||||
// FIXME: Stop using and remove this in favor of `edit`
|
||||
@unsafe
|
||||
@inlinable
|
||||
@unsafe
|
||||
internal mutating func _unsafeEdit<E: Error, R: ~Copyable>(
|
||||
_ body: (UnsafeMutableBufferPointer<Element>, inout Int) throws(E) -> R
|
||||
) throws(E) -> R {
|
||||
defer { precondition(_count >= 0 && _count <= capacity) }
|
||||
defer { precondition(count >= 0 && count <= capacity) }
|
||||
return unsafe try body(_storage, &_count)
|
||||
}
|
||||
}
|
||||
@@ -259,14 +267,14 @@ extension RigidArray where Element: ~Copyable {
|
||||
extension RigidArray where Element: ~Copyable {
|
||||
@inlinable
|
||||
internal func _contiguousSubrange(following index: inout Int) -> Range<Int> {
|
||||
precondition(index >= 0 && index <= _count, "Index out of bounds")
|
||||
defer { index = _count }
|
||||
return unsafe Range(uncheckedBounds: (index, _count))
|
||||
precondition(index >= 0 && index <= count, "Index out of bounds")
|
||||
defer { index = count }
|
||||
return unsafe Range(uncheckedBounds: (index, count))
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func _contiguousSubrange(preceding index: inout Int) -> Range<Int> {
|
||||
precondition(index >= 0 && index <= _count, "Index out of bounds")
|
||||
precondition(index >= 0 && index <= count, "Index out of bounds")
|
||||
defer { index = 0 }
|
||||
return unsafe Range(uncheckedBounds: (0, index))
|
||||
}
|
||||
@@ -374,12 +382,12 @@ extension RigidArray where Element: ~Copyable {
|
||||
let i = unsafe newStorage.moveInitialize(fromContentsOf: self._items)
|
||||
assert(i == count)
|
||||
|
||||
if _capacity != 0 {
|
||||
if capacity != 0 {
|
||||
unsafe _storage.deallocate()
|
||||
}
|
||||
|
||||
unsafe _ptr = newStorage.baseAddress.unsafelyUnwrapped
|
||||
_capacity = newStorage.count
|
||||
unsafe self._capacity = newStorage.count
|
||||
}
|
||||
|
||||
/// Ensure that the array has capacity to store the specified number of
|
||||
@@ -423,7 +431,7 @@ extension RigidArray {
|
||||
var result = RigidArray<Element>(capacity: capacity)
|
||||
let initialized = unsafe result._storage.initialize(fromContentsOf: _items)
|
||||
precondition(initialized == count)
|
||||
result._count = count
|
||||
unsafe result._count = count
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -434,6 +442,7 @@ extension RigidArray {
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
extension RigidArray where Element: ~Copyable {
|
||||
@inlinable
|
||||
@unsafe
|
||||
internal mutating func _closeGap(
|
||||
at index: Int, count: Int
|
||||
) {
|
||||
@@ -451,13 +460,13 @@ extension RigidArray where Element: ~Copyable {
|
||||
internal mutating func _openGap(
|
||||
at index: Int, count: Int
|
||||
) -> UnsafeMutableBufferPointer<Element> {
|
||||
assert(index >= 0 && index <= _count)
|
||||
assert(index >= 0 && index <= self.count)
|
||||
assert(count <= freeCapacity)
|
||||
guard count > 0 else { return unsafe _storage.extracting(index ..< index) }
|
||||
let source = unsafe _storage.extracting(
|
||||
Range(uncheckedBounds: (index, _count)))
|
||||
Range(uncheckedBounds: (index, self.count)))
|
||||
let target = unsafe _storage.extracting(
|
||||
Range(uncheckedBounds: (index + count, _count + count)))
|
||||
Range(uncheckedBounds: (index + count, self.count + count)))
|
||||
let i = unsafe target.moveInitialize(fromContentsOf: source)
|
||||
assert(i == target.count)
|
||||
return unsafe _storage.extracting(
|
||||
@@ -475,16 +484,16 @@ extension RigidArray where Element: ~Copyable {
|
||||
internal mutating func _resizeGap(
|
||||
in subrange: Range<Int>, to newItemCount: Int
|
||||
) -> UnsafeMutableBufferPointer<Element> {
|
||||
assert(subrange.lowerBound >= 0 && subrange.upperBound <= _count)
|
||||
assert(subrange.lowerBound >= 0 && subrange.upperBound <= self.count)
|
||||
assert(newItemCount >= 0 && newItemCount - subrange.count <= freeCapacity)
|
||||
if newItemCount > subrange.count {
|
||||
_ = unsafe _openGap(
|
||||
at: subrange.upperBound, count: newItemCount - subrange.count)
|
||||
} else if newItemCount < subrange.count {
|
||||
_closeGap(
|
||||
unsafe _closeGap(
|
||||
at: subrange.lowerBound + newItemCount, count: subrange.count - newItemCount)
|
||||
}
|
||||
_count += newItemCount - subrange.count
|
||||
unsafe self._count += newItemCount - subrange.count
|
||||
let gapRange = unsafe Range(
|
||||
uncheckedBounds: (subrange.lowerBound, subrange.lowerBound + newItemCount))
|
||||
return unsafe _storage.extracting(gapRange)
|
||||
|
||||
@@ -27,13 +27,13 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable {
|
||||
inout InputSpan<Value>
|
||||
) -> Void
|
||||
) {
|
||||
let keys = self._keys._memberBuf
|
||||
let values = self._valueBuf
|
||||
_keys._table.consumeAll { buckets in
|
||||
let keyBuffer = keys._extracting(buckets)
|
||||
let valueBuffer = values._extracting(buckets)
|
||||
var keySpan = InputSpan(buffer: keyBuffer, initializedCount: keyBuffer.count)
|
||||
var valueSpan = InputSpan(buffer: valueBuffer, initializedCount: valueBuffer.count)
|
||||
let keys = unsafe self._keys._memberBuf
|
||||
let values = unsafe self._valueBuf
|
||||
unsafe _keys._table.consumeAll { buckets in
|
||||
let keyBuffer = unsafe keys._extracting(buckets)
|
||||
let valueBuffer = unsafe values._extracting(buckets)
|
||||
var keySpan = unsafe InputSpan(buffer: keyBuffer, initializedCount: keyBuffer.count)
|
||||
var valueSpan = unsafe InputSpan(buffer: valueBuffer, initializedCount: valueBuffer.count)
|
||||
consumer(&keySpan, &valueSpan)
|
||||
_ = consume keySpan
|
||||
_ = consume valueSpan
|
||||
@@ -42,16 +42,17 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable {
|
||||
#endif
|
||||
|
||||
@inlinable
|
||||
@unsafe
|
||||
public mutating func _consumeAll(
|
||||
consumingWith consumer: (
|
||||
UnsafeMutableBufferPointer<Key>,
|
||||
UnsafeMutableBufferPointer<Value>
|
||||
) -> Void
|
||||
) {
|
||||
let keys = self._keys._memberBuf
|
||||
let values = self._valueBuf
|
||||
_keys._table.consumeAll { buckets in
|
||||
consumer(keys._extracting(buckets), values._extracting(buckets))
|
||||
let keys = unsafe self._keys._memberBuf
|
||||
let values = unsafe self._valueBuf
|
||||
unsafe _keys._table.consumeAll { buckets in
|
||||
unsafe consumer(keys._extracting(buckets), values._extracting(buckets))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ import InternalCollectionsUtilities
|
||||
extension RigidDictionary where Key: ~Copyable, Value: ~Copyable {
|
||||
@inlinable
|
||||
public func isTriviallyIdentical(to other: borrowing Self) -> Bool {
|
||||
self._keys.isTriviallyIdentical(to: other._keys)
|
||||
unsafe self._keys.isTriviallyIdentical(to: other._keys)
|
||||
&& self._values == other._values
|
||||
}
|
||||
}
|
||||
@@ -38,16 +38,16 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable {
|
||||
|
||||
guard self.count == other.count else { return false }
|
||||
|
||||
var it = self._keys._table.makeBucketIterator()
|
||||
var it = unsafe self._keys._table.makeBucketIterator()
|
||||
while let next = it.nextOccupiedRegion() {
|
||||
var lb = next.lowerBound
|
||||
while lb < next.upperBound {
|
||||
let res = other._find(self._keyPtr(at: lb).pointee)
|
||||
let res = unsafe other._find(self._keyPtr(at: lb).pointee)
|
||||
guard let rb = res.bucket else { return false }
|
||||
|
||||
let lp = self._valuePtr(at: lb)
|
||||
let rp = other._valuePtr(at: rb)
|
||||
guard areEquivalent(lp.pointee, rp.pointee) else { return false }
|
||||
let lp = unsafe self._valuePtr(at: lb)
|
||||
let rp = unsafe other._valuePtr(at: rb)
|
||||
guard unsafe areEquivalent(lp.pointee, rp.pointee) else { return false }
|
||||
lb._offset &+= 1
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,15 +26,15 @@ extension RigidDictionary where Value: Hashable & ~Copyable {
|
||||
@inlinable
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
var commutativeHash = 0
|
||||
var it = self._keys._table.makeBucketIterator()
|
||||
var it = unsafe self._keys._table.makeBucketIterator()
|
||||
while let next = it.nextOccupiedRegion() {
|
||||
var b = next.lowerBound
|
||||
while b < next.upperBound {
|
||||
// Note that we use a copy of our own hasher here. This makes hash values
|
||||
// dependent on its state, eliminating static collision patterns.
|
||||
var elementHasher = hasher
|
||||
_keyPtr(at: b).pointee.hash(into: &elementHasher)
|
||||
_valuePtr(at: b).pointee.hash(into: &elementHasher)
|
||||
unsafe _keyPtr(at: b).pointee.hash(into: &elementHasher)
|
||||
unsafe _valuePtr(at: b).pointee.hash(into: &elementHasher)
|
||||
commutativeHash ^= elementHasher.finalize()
|
||||
b._offset &+= 1
|
||||
}
|
||||
|
||||
@@ -57,35 +57,39 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable {
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
extension RigidDictionary where Key: ~Copyable, Value: ~Copyable {
|
||||
@frozen
|
||||
@safe
|
||||
public struct Element: ~Copyable, ~Escapable {
|
||||
// FIXME: See if using (the real) `struct Borrow` would make sense here.
|
||||
@_alwaysEmitIntoClient
|
||||
@unsafe
|
||||
package var _key: UnsafePointer<Key>
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@unsafe
|
||||
package var _value: UnsafePointer<Value>
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@_lifetime(borrow _base)
|
||||
@safe
|
||||
package init(
|
||||
_base: borrowing RigidDictionary<Key, Value>,
|
||||
bucket: _Bucket
|
||||
) {
|
||||
assert(_base._isOccupied(bucket))
|
||||
self._key = .init(_base._keyPtr(at: bucket))
|
||||
self._value = .init(_base._valuePtr(at: bucket))
|
||||
unsafe self._key = .init(_base._keyPtr(at: bucket))
|
||||
unsafe self._value = .init(_base._valuePtr(at: bucket))
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public var key: Key {
|
||||
// FIXME: This should be a borrow accessor
|
||||
unsafeAddress { _key }
|
||||
@_unsafeSelfDependentResult
|
||||
borrow { unsafe _key.pointee }
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public var value: Value {
|
||||
// FIXME: This should be a borrow accessor
|
||||
unsafeAddress { _value }
|
||||
@_unsafeSelfDependentResult
|
||||
borrow { unsafe _value.pointee }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
extension RigidDictionary where Key: ~Copyable, Value: ~Copyable {
|
||||
@available(SwiftStdlib 6.4, *)
|
||||
@frozen
|
||||
@safe
|
||||
public struct Indices: ~Escapable {
|
||||
@_alwaysEmitIntoClient
|
||||
package let _base: Ref<_HTable>
|
||||
@@ -33,7 +34,7 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable {
|
||||
public var indices: Indices {
|
||||
@_lifetime(borrow self)
|
||||
get {
|
||||
Indices(_base: self._keys._table)
|
||||
unsafe Indices(_base: self._keys._table)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -71,7 +72,7 @@ where Key: ~Copyable, Value: ~Copyable
|
||||
public func makeBorrowingIterator() -> BorrowingIterator {
|
||||
let bit = self._base.value.makeBucketIterator()
|
||||
// FIXME: This override really should not be necessary. Check if the real `struct Borrow` fixes it.
|
||||
let override = _overrideLifetime(bit, copying: self)
|
||||
let override = unsafe _overrideLifetime(bit, copying: self)
|
||||
return BorrowingIterator(_it: override)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,14 +26,14 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable {
|
||||
|
||||
@inlinable
|
||||
package init(_table: consuming _HTable) {
|
||||
let keys = RigidSet<Key>(_table: _table)
|
||||
let keys = unsafe RigidSet<Key>(_table: _table)
|
||||
let values: UnsafeMutablePointer<Value>
|
||||
if keys.capacity == 0 {
|
||||
values = ._dangling()
|
||||
unsafe values = ._dangling()
|
||||
} else {
|
||||
values = .allocate(capacity: keys._storageCapacity)
|
||||
unsafe values = .allocate(capacity: keys._storageCapacity)
|
||||
}
|
||||
self.init(_keys: keys, values: values)
|
||||
unsafe self.init(_keys: keys, values: values)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
|
||||
@@ -18,48 +18,50 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable {
|
||||
@inlinable
|
||||
@inline(__always)
|
||||
@discardableResult
|
||||
@unsafe
|
||||
package mutating func _insertNew(
|
||||
_ key: consuming Key,
|
||||
hashValue: Int,
|
||||
_ value: consuming Value
|
||||
) -> _Bucket {
|
||||
precondition(!isFull, "RigidDictionary capacity overflow")
|
||||
let keys = _keyBuf
|
||||
let values = _valueBuf
|
||||
if self._keys._table.isSmall {
|
||||
let bucket = self._keys._table.insertNew_Small(
|
||||
let keys = unsafe _keyBuf
|
||||
let values = unsafe _valueBuf
|
||||
if self._keys._isSmall {
|
||||
let bucket = unsafe self._keys._table.insertNew_Small(
|
||||
swapper: {
|
||||
swap(&key, &keys[$0])
|
||||
swap(&value, &values[$0])
|
||||
unsafe swap(&key, &keys[$0])
|
||||
unsafe swap(&value, &values[$0])
|
||||
})
|
||||
keys._initializeElement(at: bucket, to: key)
|
||||
values._initializeElement(at: bucket, to: value)
|
||||
unsafe keys._initializeElement(at: bucket, to: key)
|
||||
unsafe values._initializeElement(at: bucket, to: value)
|
||||
return bucket
|
||||
}
|
||||
return _insertNew_Large(key, hashValue: hashValue, value)
|
||||
return unsafe _insertNew_Large(key, hashValue: hashValue, value)
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@inline(__always)
|
||||
@unsafe
|
||||
package mutating func _insertNew_Large(
|
||||
_ key: consuming Key,
|
||||
hashValue: Int,
|
||||
_ value: consuming Value
|
||||
) -> _Bucket {
|
||||
let keys = _keyBuf
|
||||
let values = _valueBuf
|
||||
let keys = unsafe _keyBuf
|
||||
let values = unsafe _valueBuf
|
||||
let seed = self._keys._seed
|
||||
let bucket = self._keys._table.insertNew_Large(
|
||||
let bucket = unsafe self._keys._table.insertNew_Large(
|
||||
hashValue: hashValue,
|
||||
hashGenerator: {
|
||||
keys[$0]._rawHashValue(seed: seed)
|
||||
unsafe keys[$0]._rawHashValue(seed: seed)
|
||||
},
|
||||
swapper: { bucket in
|
||||
swap(&key, &keys[bucket])
|
||||
swap(&value, &values[bucket])
|
||||
unsafe swap(&key, &keys[bucket])
|
||||
unsafe swap(&value, &values[bucket])
|
||||
})
|
||||
keys.initializeElement(at: bucket.offset, to: key)
|
||||
values.initializeElement(at: bucket.offset, to: value)
|
||||
unsafe keys.initializeElement(at: bucket.offset, to: key)
|
||||
unsafe values.initializeElement(at: bucket.offset, to: value)
|
||||
return bucket
|
||||
}
|
||||
|
||||
@@ -74,7 +76,7 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable {
|
||||
if r.bucket != nil {
|
||||
return value
|
||||
}
|
||||
self._insertNew(key, hashValue: r.hashValue, value)
|
||||
unsafe self._insertNew(key, hashValue: r.hashValue, value)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -86,9 +88,9 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable {
|
||||
) -> Value? {
|
||||
let r = _find(key)
|
||||
if let bucket = r.bucket {
|
||||
return exchange(&_valuePtr(at: bucket).pointee, with: value)
|
||||
return unsafe exchange(&_valuePtr(at: bucket).pointee, with: value)
|
||||
}
|
||||
self._insertNew(key, hashValue: r.hashValue, value)
|
||||
unsafe self._insertNew(key, hashValue: r.hashValue, value)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -106,7 +108,7 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable {
|
||||
bucket = b
|
||||
} else {
|
||||
let value = try body(key)
|
||||
bucket = self._insertNew(key, hashValue: r.hashValue, value)
|
||||
bucket = unsafe self._insertNew(key, hashValue: r.hashValue, value)
|
||||
}
|
||||
return _borrowValue(at: bucket)
|
||||
}
|
||||
@@ -123,19 +125,19 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable {
|
||||
let r = _keys._find(key)
|
||||
bucket = r.bucket
|
||||
if let bucket {
|
||||
value = _valuePtr(at: bucket).move()
|
||||
value = unsafe _valuePtr(at: bucket).move()
|
||||
}
|
||||
var key: Key? = key // To work around inability to consume key in deinit
|
||||
defer {
|
||||
if let bucket {
|
||||
if let value = value.take() { // Simple update
|
||||
_valuePtr(at: bucket).initialize(to: value)
|
||||
unsafe _valuePtr(at: bucket).initialize(to: value)
|
||||
} else { // Removal
|
||||
self._keyPtr(at: bucket).deinitialize(count: 1)
|
||||
_resolveHole(at: bucket)
|
||||
unsafe self._keyPtr(at: bucket).deinitialize(count: 1)
|
||||
unsafe _resolveHole(at: bucket)
|
||||
}
|
||||
} else if let value = value.take() { // Insertion
|
||||
self._insertNew(key.take()!, hashValue: r.hashValue, value)
|
||||
unsafe self._insertNew(key.take()!, hashValue: r.hashValue, value)
|
||||
}
|
||||
}
|
||||
return try updater(&value)
|
||||
|
||||
@@ -44,7 +44,7 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable {
|
||||
forKey key: borrowing Key
|
||||
) -> Ref<Value>? {
|
||||
guard let bucket = self._find(key).bucket else { return nil }
|
||||
return Ref(unsafeAddress: _valuePtr(at: bucket), borrowing: self)
|
||||
return unsafe Ref(unsafeAddress: _valuePtr(at: bucket), borrowing: self)
|
||||
}
|
||||
|
||||
/// Checks if the given key is present in the `RigidDictionary`, and returns
|
||||
@@ -60,7 +60,7 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable {
|
||||
forKey key: borrowing Key
|
||||
) -> MutableRef<Value>? {
|
||||
guard let bucket = self._find(key).bucket else { return nil }
|
||||
return MutableRef(unsafeAddress: _valuePtr(at: bucket), mutating: &self)
|
||||
return unsafe MutableRef(unsafeAddress: _valuePtr(at: bucket), mutating: &self)
|
||||
}
|
||||
|
||||
/// A stand-in for a `struct Ref`-returning lookup operation.
|
||||
@@ -73,23 +73,23 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable {
|
||||
_ body: (borrowing Value) throws(E) -> R?
|
||||
) throws(E) -> R? {
|
||||
guard let bucket = self._find(key).bucket else { return nil }
|
||||
return try body(_valueBuf[bucket])
|
||||
return unsafe try body(_valueBuf[bucket])
|
||||
}
|
||||
|
||||
@available(SwiftStdlib 6.4, *)
|
||||
@_alwaysEmitIntoClient
|
||||
@_lifetime(borrow self)
|
||||
package func _borrowKey(at bucket: _Bucket) -> Ref<Key> {
|
||||
assert(_keys._table.isOccupied(bucket))
|
||||
return Ref(unsafeAddress: _keyPtr(at: bucket), borrowing: self)
|
||||
assert(unsafe _keys._table.isOccupied(bucket))
|
||||
return unsafe Ref(unsafeAddress: _keyPtr(at: bucket), borrowing: self)
|
||||
}
|
||||
|
||||
@available(SwiftStdlib 6.4, *)
|
||||
@_alwaysEmitIntoClient
|
||||
@_lifetime(borrow self)
|
||||
package func _borrowValue(at bucket: _Bucket) -> Ref<Value> {
|
||||
assert(_keys._table.isOccupied(bucket))
|
||||
return Ref(unsafeAddress: _valuePtr(at: bucket), borrowing: self)
|
||||
assert(unsafe _keys._table.isOccupied(bucket))
|
||||
return unsafe Ref(unsafeAddress: _valuePtr(at: bucket), borrowing: self)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -24,10 +24,10 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable {
|
||||
|
||||
@inlinable
|
||||
package mutating func _removeValue(at bucket: _Bucket) -> Value {
|
||||
assert(self._keys._table.isOccupied(bucket))
|
||||
self._keyPtr(at: bucket).deinitialize(count: 1)
|
||||
let oldValue = self._valuePtr(at: bucket).move()
|
||||
_resolveHole(at: bucket)
|
||||
assert(unsafe self._keys._table.isOccupied(bucket))
|
||||
unsafe self._keyPtr(at: bucket).deinitialize(count: 1)
|
||||
let oldValue = unsafe self._valuePtr(at: bucket).move()
|
||||
unsafe _resolveHole(at: bucket)
|
||||
return oldValue
|
||||
}
|
||||
|
||||
@@ -35,19 +35,20 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable {
|
||||
/// moved out (e.g., by `updateValue(forKey:with:)`). Handles key
|
||||
/// deinitialization and hole resolution without touching the value slot.
|
||||
@inlinable
|
||||
@unsafe
|
||||
package mutating func _resolveHole(at bucket: _Bucket) {
|
||||
assert(self._keys._table.isOccupied(bucket))
|
||||
self._keys._table.createHole(at: bucket)
|
||||
assert(unsafe self._keys._table.isOccupied(bucket))
|
||||
unsafe self._keys._table.createHole(at: bucket)
|
||||
let seed = self._keys._seed
|
||||
let keys = self._keys._members.unsafelyUnwrapped
|
||||
self._keys._table.resolveHole(
|
||||
let keys = unsafe self._keys._members.unsafelyUnwrapped
|
||||
unsafe self._keys._table.resolveHole(
|
||||
at: bucket,
|
||||
hashGenerator: {
|
||||
keys[$0.offset]._rawHashValue(seed: seed)
|
||||
unsafe keys[$0.offset]._rawHashValue(seed: seed)
|
||||
},
|
||||
mover: {
|
||||
(keys + $1.offset).initialize(to: (keys + $0.offset).move())
|
||||
(_values + $1.offset).initialize(to: (_values + $0.offset).move())
|
||||
unsafe (keys + $1.offset).initialize(to: (keys + $0.offset).move())
|
||||
unsafe (_values + $1.offset).initialize(to: (_values + $0.offset).move())
|
||||
})
|
||||
}
|
||||
|
||||
@@ -57,18 +58,19 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable {
|
||||
///
|
||||
/// This operation is intended to be used just before resizing the table.
|
||||
@inlinable
|
||||
@unsafe
|
||||
package mutating func _punchHole(at bucket: _Bucket) -> Value {
|
||||
assert(self._keys._table.isOccupied(bucket))
|
||||
self._keys._table.createHole(at: bucket)
|
||||
self._keyPtr(at: bucket).deinitialize(count: 1)
|
||||
assert(unsafe self._keys._table.isOccupied(bucket))
|
||||
unsafe self._keys._table.createHole(at: bucket)
|
||||
unsafe self._keyPtr(at: bucket).deinitialize(count: 1)
|
||||
|
||||
let oldValue = self._valuePtr(at: bucket).move()
|
||||
let keys = self._keys._members.unsafelyUnwrapped
|
||||
self._keys._table.finalizeHole(
|
||||
let oldValue = unsafe self._valuePtr(at: bucket).move()
|
||||
let keys = unsafe self._keys._members.unsafelyUnwrapped
|
||||
unsafe self._keys._table.finalizeHole(
|
||||
at: bucket,
|
||||
mover: {
|
||||
(keys + $1.offset).initialize(to: (keys + $0.offset).move())
|
||||
(_values + $1.offset).initialize(to: (_values + $0.offset).move())
|
||||
unsafe (keys + $1.offset).initialize(to: (keys + $0.offset).move())
|
||||
unsafe (_values + $1.offset).initialize(to: (_values + $0.offset).move())
|
||||
})
|
||||
return oldValue
|
||||
}
|
||||
@@ -76,9 +78,9 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable {
|
||||
@inlinable
|
||||
public mutating func removeAll() {
|
||||
if isEmpty { return }
|
||||
_deinitializeValues()
|
||||
_keys._deinitializeMembers()
|
||||
_keys._table.clear()
|
||||
unsafe _deinitializeValues()
|
||||
unsafe _keys._deinitializeMembers()
|
||||
unsafe _keys._table.clear()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -34,14 +34,14 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable {
|
||||
scale: UInt8,
|
||||
capacity: Int,
|
||||
) {
|
||||
assert(scale != self._keys._table.scale || capacity != self.capacity)
|
||||
assert(unsafe scale != self._keys._table.scale || capacity != self.capacity)
|
||||
assert(self.count <= capacity)
|
||||
assert(capacity <= _HTable.maximumCapacity(forScale: scale))
|
||||
assert(capacity >= _HTable.minimumCapacity(forScale: scale))
|
||||
if scale != 0, scale == self._keys._table.scale {
|
||||
if scale != 0, unsafe scale == self._keys._table.scale {
|
||||
// Large result with matching scales. We don't need to rehash or
|
||||
// reallocate, we just need to update the logical capacity.
|
||||
self._keys._table._capacity = capacity
|
||||
unsafe self._keys._table._capacity = capacity
|
||||
return
|
||||
}
|
||||
|
||||
@@ -51,36 +51,36 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable {
|
||||
return
|
||||
}
|
||||
|
||||
let sourceKeys = old._keys._members.unsafelyUnwrapped
|
||||
let sourceValues = old._values
|
||||
let targetKeys = self._keys._members.unsafelyUnwrapped
|
||||
let targetValues = self._values
|
||||
if self._keys._table.isSmall {
|
||||
self._keys._table.migrateItems_Small(from: &old._keys._table) { src, dst in
|
||||
(targetKeys + dst.offset).initialize(to: (sourceKeys + src.offset).move())
|
||||
(targetValues + dst.offset).initialize(to: (sourceValues + src.offset).move())
|
||||
let sourceKeys = unsafe old._keys._members.unsafelyUnwrapped
|
||||
let sourceValues = unsafe old._values
|
||||
let targetKeys = unsafe self._keys._members.unsafelyUnwrapped
|
||||
let targetValues = unsafe self._values
|
||||
if self._keys._isSmall {
|
||||
unsafe self._keys._table.migrateItems_Small(from: &old._keys._table) { src, dst in
|
||||
unsafe (targetKeys + dst.offset).initialize(to: (sourceKeys + src.offset).move())
|
||||
unsafe (targetValues + dst.offset).initialize(to: (sourceValues + src.offset).move())
|
||||
}
|
||||
} else {
|
||||
let seed = self._keys._seed
|
||||
var srcKey = sourceKeys
|
||||
var srcValue = sourceValues
|
||||
self._keys._table.migrateItems_Large(
|
||||
var srcKey = unsafe sourceKeys
|
||||
var srcValue = unsafe sourceValues
|
||||
unsafe self._keys._table.migrateItems_Large(
|
||||
from: &old._keys._table,
|
||||
selector: {
|
||||
srcKey = sourceKeys + $0.offset
|
||||
srcValue = sourceValues + $0.offset
|
||||
return srcKey.pointee._rawHashValue(seed: seed)
|
||||
unsafe srcKey = sourceKeys + $0.offset
|
||||
unsafe srcValue = sourceValues + $0.offset
|
||||
return unsafe srcKey.pointee._rawHashValue(seed: seed)
|
||||
},
|
||||
hashGenerator: {
|
||||
targetKeys[$0.offset]._rawHashValue(seed: seed)
|
||||
unsafe targetKeys[$0.offset]._rawHashValue(seed: seed)
|
||||
},
|
||||
swapper: {
|
||||
swap(&srcKey.pointee, &targetKeys[$0.offset])
|
||||
swap(&srcValue.pointee, &targetValues[$0.offset])
|
||||
unsafe swap(&srcKey.pointee, &targetKeys[$0.offset])
|
||||
unsafe swap(&srcValue.pointee, &targetValues[$0.offset])
|
||||
},
|
||||
finalizer: {
|
||||
(targetKeys + $0.offset).initialize(to: srcKey.move())
|
||||
(targetValues + $0.offset).initialize(to: srcValue.move())
|
||||
unsafe (targetKeys + $0.offset).initialize(to: srcKey.move())
|
||||
unsafe (targetValues + $0.offset).initialize(to: srcValue.move())
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ import InternalCollectionsUtilities
|
||||
#if compiler(<6.4)
|
||||
@available(*, unavailable, message: "RigidDictionary requires a Swift 6.4 toolchain")
|
||||
@frozen
|
||||
@safe
|
||||
public struct RigidDictionary<
|
||||
Key: Hashable,
|
||||
Value: ~Copyable
|
||||
@@ -31,6 +32,7 @@ public struct RigidDictionary<
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
@frozen
|
||||
@_addressableForDependencies
|
||||
@safe
|
||||
public struct RigidDictionary<
|
||||
Key: Hashable & ~Copyable,
|
||||
Value: ~Copyable
|
||||
@@ -42,17 +44,19 @@ public struct RigidDictionary<
|
||||
package var _keys: RigidSet<Key>
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@unsafe
|
||||
package var _values: UnsafeMutablePointer<Value>
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
@unsafe
|
||||
package init(
|
||||
_keys: consuming RigidSet<Key>,
|
||||
values: UnsafeMutablePointer<Value>
|
||||
) {
|
||||
assert((values != ._dangling()) == (_keys._members != nil))
|
||||
assert(unsafe (values != ._dangling()) == (_keys._members != nil))
|
||||
self._keys = _keys
|
||||
self._values = values
|
||||
unsafe self._values = values
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@@ -61,17 +65,18 @@ public struct RigidDictionary<
|
||||
// and once in `_keys.deinit`. `self` not being mutable really hurts us
|
||||
// here.
|
||||
if !isEmpty {
|
||||
_deinitializeValues()
|
||||
_values.deallocate()
|
||||
unsafe _deinitializeValues()
|
||||
unsafe _values.deallocate()
|
||||
}
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@unsafe
|
||||
internal func _deinitializeValues() {
|
||||
let values = _valueBuf
|
||||
var it = _keys._table.makeBucketIterator()
|
||||
let values = unsafe _valueBuf
|
||||
var it = unsafe _keys._table.makeBucketIterator()
|
||||
while let range = it.nextOccupiedRegion() {
|
||||
values.extracting(range._offsets).deinitialize()
|
||||
unsafe values.extracting(range._offsets).deinitialize()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -81,13 +86,13 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable {
|
||||
@inlinable
|
||||
@inline(__always)
|
||||
public var count: Int {
|
||||
_assumeNonNegative(_keys._table.count)
|
||||
_keys.count
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@inline(__always)
|
||||
public var capacity: Int {
|
||||
_assumeNonNegative(_keys._table.capacity)
|
||||
_keys.capacity
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@@ -105,7 +110,7 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable {
|
||||
@inlinable
|
||||
@inline(__always)
|
||||
public var freeCapacity: Int {
|
||||
_assumeNonNegative(capacity &- count)
|
||||
_keys.freeCapacity
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@@ -113,37 +118,47 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable {
|
||||
public var _scale: UInt8 {
|
||||
_keys._scale
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
public var _isSmall: Bool {
|
||||
_keys._isSmall
|
||||
}
|
||||
}
|
||||
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
extension RigidDictionary where Key: ~Copyable, Value: ~Copyable {
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
@unsafe
|
||||
internal var _keyBuf: UnsafeMutableBufferPointer<Key> {
|
||||
_keys._memberBuf
|
||||
unsafe _keys._memberBuf
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
@unsafe
|
||||
internal var _valueBuf: UnsafeMutableBufferPointer<Value> {
|
||||
.init(start: _values, count: Int(bitPattern: _keys._table.bucketCount))
|
||||
unsafe .init(start: _values, count: Int(bitPattern: _keys._table.bucketCount))
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
@unsafe
|
||||
internal func _valuePtr(
|
||||
at bucket: _HTable.Bucket
|
||||
) -> UnsafeMutablePointer<Value> {
|
||||
assert(_keys._table.isValid(bucket))
|
||||
return _values.advanced(by: bucket.offset)
|
||||
assert(unsafe _keys._table.isValid(bucket))
|
||||
return unsafe _values.advanced(by: bucket.offset)
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
@unsafe
|
||||
internal func _keyPtr(
|
||||
at bucket: _HTable.Bucket
|
||||
) -> UnsafeMutablePointer<Key> {
|
||||
_keys._memberPtr(at: bucket)
|
||||
unsafe _keys._memberPtr(at: bucket)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -24,10 +24,10 @@ extension RigidSet where Element: ~Copyable {
|
||||
public mutating func consumeAll(
|
||||
consumingWith consumer: (inout InputSpan<Element>) -> Void
|
||||
) {
|
||||
let storage = self._memberBuf
|
||||
_table.consumeAll { buckets in
|
||||
let buffer = storage._extracting(buckets)
|
||||
var span = InputSpan(buffer: buffer, initializedCount: buffer.count)
|
||||
let storage = unsafe self._memberBuf
|
||||
unsafe _table.consumeAll { buckets in
|
||||
let buffer = unsafe storage._extracting(buckets)
|
||||
var span = unsafe InputSpan(buffer: buffer, initializedCount: buffer.count)
|
||||
consumer(&span)
|
||||
_ = consume span
|
||||
}
|
||||
@@ -38,9 +38,9 @@ extension RigidSet where Element: ~Copyable {
|
||||
public mutating func _consumeAll(
|
||||
consumingWith consumer: (UnsafeMutableBufferPointer<Element>) -> Void
|
||||
) {
|
||||
let storage = self._memberBuf
|
||||
_table.consumeAll { buckets in
|
||||
consumer(storage._extracting(buckets))
|
||||
let storage = unsafe self._memberBuf
|
||||
unsafe _table.consumeAll { buckets in
|
||||
unsafe consumer(storage._extracting(buckets))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,21 +24,21 @@ extension RigidSet where Element: ~Copyable {
|
||||
chains: Bool = false,
|
||||
buckets: Bool = false,
|
||||
) -> String {
|
||||
var s = _table.describe(bitmap: bitmap)
|
||||
var s = unsafe _table.describe(bitmap: bitmap)
|
||||
if chains {
|
||||
s += "\n"
|
||||
s += _chainDescription
|
||||
}
|
||||
if buckets, !_table.isSmall, !_table.isEmpty {
|
||||
if buckets, !_isSmall, !isEmpty {
|
||||
s += "\nBuckets:"
|
||||
var it = _table.makeBucketIterator()
|
||||
var it = unsafe _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 idealBucket = unsafe _table.idealBucket(forHashValue: hashValue)
|
||||
let s1 = String(b.offset)._lpad(5)
|
||||
let s2 = String(idealBucket.offset)._rpad(5)
|
||||
s += "\(s1)→\(s2) "
|
||||
@@ -62,22 +62,22 @@ extension RigidSet where Element: ~Copyable {
|
||||
public func _probeLengthCounts() -> (successful: [Int], unsuccessful: [Int]) {
|
||||
var positiveLengths: [Int: Int] = [:]
|
||||
var negativeLengths: [Int: Int] = [:]
|
||||
var it = self._table.makeBucketIterator()
|
||||
var prev = self._table.startBucket
|
||||
var it = unsafe self._table.makeBucketIterator()
|
||||
var prev = unsafe self._table.startBucket
|
||||
while let next = it.nextOccupiedRegion() {
|
||||
negativeLengths[0, default: 0] += next.lowerBound.offset - prev.offset
|
||||
var b = next.lowerBound
|
||||
while b != next.upperBound {
|
||||
let hashValue = self._hashValue(at: b)
|
||||
let pl = _table.probeLength(forHashValue: hashValue, in: b)
|
||||
let pl = unsafe _table.probeLength(forHashValue: hashValue, in: b)
|
||||
positiveLengths[pl, default: 0] += 1
|
||||
|
||||
var nl = next.upperBound.offset - b.offset
|
||||
#if !COLLECTIONS_NO_ROBIN_HOOD_HASHING
|
||||
nl = Swift.min(nl, _table._maxProbeLength)
|
||||
nl = Swift.min(nl, unsafe _table._maxProbeLength)
|
||||
#endif
|
||||
negativeLengths[nl, default: 0] += 1
|
||||
_table.formBucket(after: &b)
|
||||
unsafe _table.formBucket(after: &b)
|
||||
}
|
||||
prev = next.upperBound
|
||||
}
|
||||
@@ -118,8 +118,8 @@ extension RigidSet where Element: ~Copyable {
|
||||
histogram += "\n"
|
||||
sum += (length + 1) * count
|
||||
}
|
||||
if _table.count > 0 {
|
||||
let avg = Double((sum * 1000 + 500) / _table.count) / 1000.0
|
||||
if unsafe _table.count > 0 {
|
||||
let avg = unsafe Double((sum * 1000 + 500) / _table.count) / 1000.0
|
||||
str += " AVG: \(avg)\n"
|
||||
}
|
||||
str += histogram
|
||||
@@ -138,8 +138,8 @@ extension RigidSet where Element: ~Copyable {
|
||||
histogram += "\n"
|
||||
sum += length * count
|
||||
}
|
||||
if _table.storageCapacity > 0 {
|
||||
let avg = Double((sum * 1000 + 500) / _table.storageCapacity) / 1000.0
|
||||
if unsafe _table.storageCapacity > 0 {
|
||||
let avg = unsafe Double((sum * 1000 + 500) / _table.storageCapacity) / 1000.0
|
||||
str += " AVG: \(avg)\n"
|
||||
}
|
||||
str += histogram
|
||||
@@ -162,7 +162,7 @@ extension RigidSet where Element: ~Copyable {
|
||||
public func _checkInvariants(
|
||||
failureHandler: (String) -> Void
|
||||
) {
|
||||
_table.checkInvariants(
|
||||
unsafe _table.checkInvariants(
|
||||
failureHandler: failureHandler,
|
||||
hashGenerator: { _hashValue(at: $0) })
|
||||
}
|
||||
|
||||
@@ -24,43 +24,6 @@ extension RigidSet where Element: ~Copyable {
|
||||
) throws(E) -> Void {
|
||||
try self.insert(addingCount: maximumCount, initializingWith: initializer)
|
||||
}
|
||||
|
||||
#if UnstableContainersPreview
|
||||
@available(*, deprecated, renamed: "insert(addingCount:from:)")
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func insert<
|
||||
E: Error,
|
||||
P: Producer<Element, E> & ~Copyable & ~Escapable
|
||||
>(
|
||||
maximumCount: Int?,
|
||||
from producer: inout P
|
||||
) throws(E)
|
||||
where P.Element: ~Copyable
|
||||
{
|
||||
try self.insert(addingCount: maximumCount, from: &producer)
|
||||
}
|
||||
#endif
|
||||
|
||||
#if UnstableContainersPreview
|
||||
@available(*, deprecated, renamed: "insert(addingCount:from:)")
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func insert<
|
||||
D: Drain<Element> & ~Copyable & ~Escapable
|
||||
>(
|
||||
maximumCount: Int?,
|
||||
from drain: inout D
|
||||
) {
|
||||
var remainder = drain.count
|
||||
while remainder > 0 {
|
||||
var span = drain.drainNext(maxCount: remainder)
|
||||
guard !span.isEmpty else { break }
|
||||
remainder &-= span.count
|
||||
while let next = span.popFirst() {
|
||||
self.insert(next)
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ import InternalCollectionsUtilities
|
||||
extension RigidSet where Element: ~Copyable {
|
||||
@inlinable
|
||||
public func isTriviallyIdentical(to other: borrowing Self) -> Bool {
|
||||
self._members == other._members
|
||||
unsafe self._members == other._members
|
||||
&& self._table.isTriviallyIdentical(to: other._table)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ extension RigidSet where Element: ~Copyable {
|
||||
let next = it.nextSpan()
|
||||
var i = 0
|
||||
while i < next.count {
|
||||
hash ^= next[unchecked: i]._rawHashValue(seed: seed)
|
||||
hash ^= unsafe next[unchecked: i]._rawHashValue(seed: seed)
|
||||
i &+= 1
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,22 +74,22 @@ extension RigidSet where Element: ~Copyable {
|
||||
|
||||
@inlinable
|
||||
public var startIndex: Index {
|
||||
if _table.isSmall { return Index(_bucket: _Bucket(offset: 0)) }
|
||||
guard let b = _table.bitmap.firstOccupiedBucket(from: _Bucket(offset: 0))
|
||||
if _isSmall { return Index(_bucket: _Bucket(offset: 0)) }
|
||||
guard let b = unsafe _table.bitmap.firstOccupiedBucket(from: _Bucket(offset: 0))
|
||||
else { return endIndex }
|
||||
return Index(_bucket: b)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Index {
|
||||
if _table.isSmall { return Index(_offset: count) }
|
||||
return Index(_bucket: _table.endBucket)
|
||||
if _isSmall { return Index(_offset: count) }
|
||||
return unsafe Index(_bucket: _table.endBucket)
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
package func _isOccupied(_ bucket: _Bucket) -> Bool {
|
||||
_table.isValid(bucket) && _table.isOccupied(bucket)
|
||||
unsafe _table.isValid(bucket) && _table.isOccupied(bucket)
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@@ -115,13 +115,13 @@ extension RigidSet where Element: ~Copyable {
|
||||
@inlinable
|
||||
public func index(after index: Index) -> Index {
|
||||
_checkItemIndex(index)
|
||||
if _table.isSmall {
|
||||
if _isSmall {
|
||||
return Index(_bucket: _Bucket(offset: index._bucket._offset &+ 1))
|
||||
}
|
||||
var start = index._bucket
|
||||
start._offset &+= 1
|
||||
guard start < _table.endBucket else { return Index(_bucket: start) }
|
||||
guard let b = _table.bitmap.firstOccupiedBucket(from: start)
|
||||
guard unsafe start < _table.endBucket else { return Index(_bucket: start) }
|
||||
guard let b = unsafe _table.bitmap.firstOccupiedBucket(from: start)
|
||||
else { return endIndex }
|
||||
return Index(_bucket: b)
|
||||
}
|
||||
@@ -131,7 +131,7 @@ extension RigidSet where Element: ~Copyable {
|
||||
@_unsafeSelfDependentResult
|
||||
borrow {
|
||||
_checkItemIndex(index)
|
||||
return _memberPtr(at: index._bucket).pointee
|
||||
return unsafe _memberPtr(at: index._bucket).pointee
|
||||
}
|
||||
}
|
||||
|
||||
@@ -142,20 +142,20 @@ extension RigidSet where Element: ~Copyable {
|
||||
) -> Span<Element> {
|
||||
_checkValidIndex(index)
|
||||
if index == endIndex { return .init() }
|
||||
if _table.isSmall {
|
||||
if _isSmall {
|
||||
let start = Int(index._offset)
|
||||
let end = _table.count
|
||||
let items = _memberBuf.extracting(start ..< end)
|
||||
let end = self.count
|
||||
let items = unsafe _memberBuf.extracting(start ..< end)
|
||||
index = Index(_offset: end)
|
||||
let span = Span(_unsafeElements: items)
|
||||
return _overrideLifetime(span, borrowing: self)
|
||||
let span = unsafe Span(_unsafeElements: items)
|
||||
return unsafe _overrideLifetime(span, borrowing: self)
|
||||
}
|
||||
let buckets = _table.bitmap.nextOccupiedRegion(
|
||||
let buckets = unsafe _table.bitmap.nextOccupiedRegion(
|
||||
from: &index._bucket, maxCount: .max, limit: _table.endBucket)
|
||||
let span = Span(
|
||||
let span = unsafe Span(
|
||||
_unsafeStart: _memberPtr(at: buckets.lowerBound),
|
||||
count: buckets._offsets.count)
|
||||
return _overrideLifetime(span, borrowing: self)
|
||||
return unsafe _overrideLifetime(span, borrowing: self)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@@ -168,22 +168,22 @@ extension RigidSet where Element: ~Copyable {
|
||||
precondition(maxCount > 0, "maxCount must be positive")
|
||||
if index == endIndex { return .init() }
|
||||
let limit = limit._offset < index._offset ? endIndex : limit
|
||||
if _table.isSmall {
|
||||
if _isSmall {
|
||||
let start = Int(index._offset)
|
||||
var c = Swift.min(maxCount, _table.count - start)
|
||||
var c = unsafe Swift.min(maxCount, _table.count - start)
|
||||
var end = start
|
||||
end._advance(by: &c, limitedBy: Int(limit._offset))
|
||||
let items = _memberBuf.extracting(start ..< end)
|
||||
let items = unsafe _memberBuf.extracting(start ..< end)
|
||||
index = Index(_offset: end)
|
||||
let span = Span(_unsafeElements: items)
|
||||
return _overrideLifetime(span, borrowing: self)
|
||||
let span = unsafe Span(_unsafeElements: items)
|
||||
return unsafe _overrideLifetime(span, borrowing: self)
|
||||
}
|
||||
let buckets = _table.bitmap.nextOccupiedRegion(
|
||||
let buckets = unsafe _table.bitmap.nextOccupiedRegion(
|
||||
from: &index._bucket, maxCount: maxCount, limit: limit._bucket)
|
||||
let span = Span(
|
||||
let span = unsafe Span(
|
||||
_unsafeStart: _memberPtr(at: buckets.lowerBound),
|
||||
count: buckets._offsets.count)
|
||||
return _overrideLifetime(span, borrowing: self)
|
||||
return unsafe _overrideLifetime(span, borrowing: self)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ extension RigidSet where Element: ~Copyable {
|
||||
@inlinable
|
||||
public init(capacity: Int) {
|
||||
precondition(capacity >= 0, "Capacity must be nonnegative")
|
||||
self.init(_table: _HTable(capacity: capacity))
|
||||
unsafe self.init(_table: _HTable(capacity: capacity))
|
||||
}
|
||||
|
||||
@inlinable
|
||||
|
||||
@@ -49,13 +49,13 @@ extension RigidSet where Element: ~Copyable {
|
||||
hashValue: Int
|
||||
) -> _Bucket {
|
||||
precondition(!isFull, "RigidSet capacity overflow")
|
||||
let storage = _memberBuf
|
||||
if _table.isSmall {
|
||||
let bucket = _table.insertNew_Small(
|
||||
let storage = unsafe _memberBuf
|
||||
if _isSmall {
|
||||
let bucket = unsafe _table.insertNew_Small(
|
||||
swapper: {
|
||||
swap(&item, &storage[$0])
|
||||
unsafe swap(&item, &storage[$0])
|
||||
})
|
||||
storage._initializeElement(at: bucket, to: item)
|
||||
unsafe storage._initializeElement(at: bucket, to: item)
|
||||
return bucket
|
||||
}
|
||||
return _insertNew_Large(item, hashValue: hashValue)
|
||||
@@ -67,17 +67,17 @@ extension RigidSet where Element: ~Copyable {
|
||||
_ item: consuming Element,
|
||||
hashValue: Int
|
||||
) -> _Bucket {
|
||||
let storage = _memberBuf
|
||||
let storage = unsafe _memberBuf
|
||||
let seed = self._seed
|
||||
let bucket = _table.insertNew_Large(
|
||||
let bucket = unsafe _table.insertNew_Large(
|
||||
hashValue: hashValue,
|
||||
hashGenerator: {
|
||||
storage[$0]._rawHashValue(seed: seed)
|
||||
unsafe storage[$0]._rawHashValue(seed: seed)
|
||||
},
|
||||
swapper: {
|
||||
swap(&item, &storage[$0])
|
||||
unsafe swap(&item, &storage[$0])
|
||||
})
|
||||
storage.initializeElement(at: bucket.offset, to: item)
|
||||
unsafe storage.initializeElement(at: bucket.offset, to: item)
|
||||
return bucket
|
||||
}
|
||||
|
||||
@@ -94,7 +94,7 @@ extension RigidSet where Element: ~Copyable {
|
||||
) -> Element? {
|
||||
let r = _find(item)
|
||||
if let bucket = r.bucket {
|
||||
return exchange(&_memberPtr(at: bucket).pointee, with: item)
|
||||
return unsafe exchange(&_memberPtr(at: bucket).pointee, with: item)
|
||||
}
|
||||
_insertNew(item, hashValue: r.hashValue)
|
||||
return nil
|
||||
@@ -176,7 +176,7 @@ extension RigidSet /* where Element: Copyable */ {
|
||||
) {
|
||||
var i = 0
|
||||
while i < items.count {
|
||||
self.insert(items[unchecked: i])
|
||||
unsafe self.insert(items[unchecked: i])
|
||||
i &+= 1
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,56 +35,61 @@ extension RigidSet: Iterable where Element: ~Copyable {
|
||||
package borrowing func _validateIterator(
|
||||
_ iterator: borrowing BorrowingIterator
|
||||
) -> Bool {
|
||||
iterator._baseAddress == UnsafePointer(self._members)
|
||||
unsafe iterator._baseAddress == UnsafePointer(self._members)
|
||||
&& iterator._bucketIterator._words == UnsafePointer(self._table._bitmap)
|
||||
}
|
||||
|
||||
@frozen
|
||||
@safe
|
||||
public struct BorrowingIterator:
|
||||
BorrowingIteratorProtocol,
|
||||
~Copyable,
|
||||
~Escapable
|
||||
{
|
||||
@_alwaysEmitIntoClient
|
||||
@unsafe
|
||||
package var _baseAddress: UnsafePointer<Element>?
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
package var _bucketIterator: _HTable.BucketIterator
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
package var _endBucket: _Bucket
|
||||
package let _endBucket: _Bucket
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@_lifetime(borrow _set)
|
||||
@safe
|
||||
package init(
|
||||
_set: borrowing RigidSet<Element>
|
||||
) {
|
||||
self._baseAddress = .init(_set._members)
|
||||
self._bucketIterator = _set._table.makeBucketIterator()
|
||||
unsafe self._baseAddress = .init(_set._members)
|
||||
self._bucketIterator = unsafe _set._table.makeBucketIterator()
|
||||
self._endBucket = self._bucketIterator._endBucket
|
||||
_bucketIterator.advanceToOccupied()
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@_lifetime(borrow _set)
|
||||
@unsafe
|
||||
package init(
|
||||
_set: borrowing RigidSet<Element>,
|
||||
from start: Index,
|
||||
to end: Index
|
||||
) {
|
||||
self._baseAddress = .init(_set._members)
|
||||
self._bucketIterator = _set._table.makeBucketIterator(from: start._bucket)
|
||||
unsafe self._baseAddress = .init(_set._members)
|
||||
self._bucketIterator = unsafe _set._table.makeBucketIterator(from: start._bucket)
|
||||
self._endBucket = end._bucket
|
||||
_bucketIterator.advanceToOccupied()
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@_lifetime(copy self)
|
||||
@unsafe
|
||||
internal func _span(from start: _Bucket, to end: _Bucket) -> Span<Element> {
|
||||
let items = UnsafeBufferPointer(
|
||||
let items = unsafe UnsafeBufferPointer(
|
||||
start: _baseAddress.unsafelyUnwrapped + start.offset,
|
||||
count: end.offset - start.offset)
|
||||
return _overrideLifetime(Span(_unsafeElements: items), copying: self)
|
||||
return unsafe _overrideLifetime(Span(_unsafeElements: items), copying: self)
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@@ -103,7 +108,7 @@ extension RigidSet: Iterable where Element: ~Copyable {
|
||||
end = _endBucket
|
||||
_bucketIterator.advanceToEnd()
|
||||
}
|
||||
return _span(from: start, to: end)
|
||||
return unsafe _span(from: start, to: end)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,15 +19,15 @@ extension RigidSet where Element: ~Copyable {
|
||||
package borrowing func _find(
|
||||
_ item: borrowing Element
|
||||
) -> (bucket: _Bucket?, hashValue: Int) {
|
||||
let storage = _memberBuf
|
||||
if _table.isSmall {
|
||||
let bucket = _table.find_Small(tester: { storage[$0] == item })
|
||||
let storage = unsafe _memberBuf
|
||||
if _isSmall {
|
||||
let bucket = unsafe _table.find_Small { unsafe storage[$0] == item }
|
||||
return (bucket, 0)
|
||||
}
|
||||
let hashValue = _hashValue(for: item)
|
||||
let bucket = _table.find_Large(
|
||||
let bucket = unsafe _table.find_Large(
|
||||
hashValue: hashValue,
|
||||
tester: { storage[$0] == item })
|
||||
tester: { unsafe storage[$0] == item })
|
||||
return (bucket, hashValue)
|
||||
}
|
||||
|
||||
@@ -40,8 +40,8 @@ extension RigidSet where Element: ~Copyable {
|
||||
@_alwaysEmitIntoClient
|
||||
@_lifetime(borrow self)
|
||||
package func _borrowValue(at bucket: _Bucket) -> Ref<Element> {
|
||||
assert(self._table.isOccupied(bucket))
|
||||
return Ref(unsafeAddress: self._memberPtr(at: bucket), borrowing: self)
|
||||
assert(unsafe self._table.isOccupied(bucket))
|
||||
return unsafe Ref(unsafeAddress: self._memberPtr(at: bucket), borrowing: self)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ extension RigidSet where Element: ~Copyable {
|
||||
public mutating func remove(_ member: borrowing Element) -> Element? {
|
||||
let r = _find(member)
|
||||
guard let bucket = r.bucket else { return nil }
|
||||
return _remove(at: bucket)
|
||||
return unsafe _remove(at: bucket)
|
||||
}
|
||||
|
||||
/// Remove the member currently at the specified occupied bucket,
|
||||
@@ -28,33 +28,35 @@ extension RigidSet where Element: ~Copyable {
|
||||
///
|
||||
/// This operation is intended to be used just before resizing the table.
|
||||
@inlinable
|
||||
@unsafe
|
||||
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(
|
||||
assert(unsafe _table.isOccupied(bucket))
|
||||
unsafe _table.createHole(at: bucket)
|
||||
let result = unsafe _memberPtr(at: bucket).move()
|
||||
let members = unsafe _members.unsafelyUnwrapped
|
||||
unsafe _table.finalizeHole(
|
||||
at: bucket,
|
||||
mover: {
|
||||
(members + $1.offset).initialize(to: (members + $0.offset).move())
|
||||
unsafe (members + $1.offset).initialize(to: (members + $0.offset).move())
|
||||
})
|
||||
return result
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@unsafe
|
||||
package mutating func _remove(at bucket: _Bucket) -> Element {
|
||||
assert(_table.isOccupied(bucket))
|
||||
_table.createHole(at: bucket)
|
||||
let result = _memberPtr(at: bucket).move()
|
||||
assert(unsafe _table.isOccupied(bucket))
|
||||
unsafe _table.createHole(at: bucket)
|
||||
let result = unsafe _memberPtr(at: bucket).move()
|
||||
let seed = self._seed
|
||||
let members = _members.unsafelyUnwrapped
|
||||
_table.resolveHole(
|
||||
let members = unsafe _members.unsafelyUnwrapped
|
||||
unsafe _table.resolveHole(
|
||||
at: bucket,
|
||||
hashGenerator: {
|
||||
members[$0.offset]._rawHashValue(seed: seed)
|
||||
unsafe members[$0.offset]._rawHashValue(seed: seed)
|
||||
},
|
||||
mover: {
|
||||
(members + $1.offset).initialize(to: (members + $0.offset).move())
|
||||
unsafe (members + $1.offset).initialize(to: (members + $0.offset).move())
|
||||
})
|
||||
return result
|
||||
}
|
||||
@@ -62,8 +64,8 @@ extension RigidSet where Element: ~Copyable {
|
||||
@inlinable
|
||||
public mutating func removeAll() {
|
||||
if isEmpty { return }
|
||||
_deinitializeMembers()
|
||||
_table.clear()
|
||||
unsafe _deinitializeMembers()
|
||||
unsafe _table.clear()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -34,48 +34,48 @@ extension RigidSet where Element: ~Copyable {
|
||||
scale: UInt8,
|
||||
capacity: Int,
|
||||
) {
|
||||
assert(scale != self._table.scale || capacity != self.capacity)
|
||||
assert(unsafe scale != self._table.scale || capacity != self.capacity)
|
||||
assert(self.count <= capacity)
|
||||
assert(capacity <= _HTable.maximumCapacity(forScale: scale))
|
||||
assert(capacity >= _HTable.minimumCapacity(forScale: scale))
|
||||
if scale != 0, scale == self._table.scale {
|
||||
if scale != 0, unsafe scale == self._table.scale {
|
||||
// Large result with matching scales. We don't need to rehash or
|
||||
// reallocate, we just need to update the logical capacity.
|
||||
self._table._capacity = capacity
|
||||
unsafe self._table._capacity = capacity
|
||||
return
|
||||
}
|
||||
|
||||
let newTable = _HTable(_capacity: capacity, scale: scale)
|
||||
var old = exchange(&self, with: Self(_table: newTable))
|
||||
var old = unsafe 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())
|
||||
let source = unsafe old._members.unsafelyUnwrapped
|
||||
let target = unsafe self._members.unsafelyUnwrapped
|
||||
if _isSmall {
|
||||
unsafe self._table.migrateItems_Small(from: &old._table) { src, dst in
|
||||
unsafe (target + dst.offset).initialize(to: (source + src.offset).move())
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
let seed = self._seed
|
||||
var src = source
|
||||
self._table.migrateItems_Large(
|
||||
var src = unsafe source
|
||||
unsafe self._table.migrateItems_Large(
|
||||
from: &old._table,
|
||||
selector: {
|
||||
src = source + $0.offset
|
||||
return src.pointee._rawHashValue(seed: seed)
|
||||
unsafe src = source + $0.offset
|
||||
return unsafe src.pointee._rawHashValue(seed: seed)
|
||||
},
|
||||
hashGenerator: {
|
||||
target[$0.offset]._rawHashValue(seed: seed)
|
||||
unsafe target[$0.offset]._rawHashValue(seed: seed)
|
||||
},
|
||||
swapper: {
|
||||
swap(&src.pointee, &target[$0.offset])
|
||||
unsafe swap(&src.pointee, &target[$0.offset])
|
||||
},
|
||||
finalizer: {
|
||||
(target + $0.offset).initialize(to: src.move())
|
||||
unsafe (target + $0.offset).initialize(to: src.move())
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
@@ -30,44 +30,50 @@ public struct RigidSet<Element: Hashable>: ~Copyable {
|
||||
/// elements.
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
@frozen
|
||||
@safe
|
||||
public struct RigidSet<Element: Hashable & ~Copyable>: ~Copyable {
|
||||
@usableFromInline
|
||||
package typealias _Bucket = _HTable.Bucket
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@unsafe
|
||||
package var _members: UnsafeMutablePointer<Element>?
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@unsafe // FIXME: Only mutations are unsafe
|
||||
package var _table: _HTable
|
||||
|
||||
@inlinable
|
||||
@_transparent
|
||||
@unsafe
|
||||
package init(
|
||||
_table: consuming _HTable
|
||||
) {
|
||||
assert(_table.isEmpty)
|
||||
if _table.capacity == 0 {
|
||||
self._members = nil
|
||||
unsafe self._members = nil
|
||||
} else {
|
||||
self._members = .allocate(capacity: _table.storageCapacity)
|
||||
unsafe self._members = .allocate(capacity: _table.storageCapacity)
|
||||
}
|
||||
self._table = _table
|
||||
unsafe self._table = _table
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
deinit {
|
||||
if !isEmpty {
|
||||
_deinitializeMembers()
|
||||
unsafe _deinitializeMembers()
|
||||
}
|
||||
_members?.deallocate()
|
||||
unsafe _members?.deallocate()
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@unsafe
|
||||
internal func _deinitializeMembers() {
|
||||
let storage = _memberBuf
|
||||
var it = _table.makeBucketIterator()
|
||||
// FIXME: This should be declared mutating and update stored properties.
|
||||
let storage = unsafe _memberBuf
|
||||
var it = unsafe _table.makeBucketIterator()
|
||||
while let range = it.nextOccupiedRegion() {
|
||||
storage._extracting(unchecked: range._offsets).deinitialize()
|
||||
unsafe storage._extracting(unchecked: range._offsets).deinitialize()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -77,13 +83,13 @@ extension RigidSet where Element: ~Copyable {
|
||||
@inlinable
|
||||
@inline(__always)
|
||||
public var count: Int {
|
||||
_assumeNonNegative(_table.count)
|
||||
unsafe _assumeNonNegative(_table.count)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@inline(__always)
|
||||
public var capacity: Int {
|
||||
_assumeNonNegative(_table.capacity)
|
||||
unsafe _assumeNonNegative(_table.capacity)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@@ -107,13 +113,19 @@ extension RigidSet where Element: ~Copyable {
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
public var _scale: UInt8 {
|
||||
_table.scale
|
||||
unsafe _table.scale
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
public var _storageCapacity: Int {
|
||||
_table.storageCapacity
|
||||
unsafe _table.storageCapacity
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
public var _isSmall: Bool {
|
||||
unsafe _table.isSmall
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,17 +133,19 @@ extension RigidSet where Element: ~Copyable {
|
||||
extension RigidSet where Element: ~Copyable {
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
@unsafe
|
||||
internal var _memberBuf: UnsafeMutableBufferPointer<Element> {
|
||||
.init(start: _members, count: Int(bitPattern: _table.bucketCount))
|
||||
unsafe .init(start: _members, count: Int(bitPattern: _table.bucketCount))
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
@unsafe
|
||||
internal func _memberPtr(
|
||||
at bucket: _Bucket
|
||||
) -> UnsafeMutablePointer<Element> {
|
||||
assert(_table.isValid(bucket))
|
||||
return _members.unsafelyUnwrapped.advanced(by: bucket.offset)
|
||||
assert(unsafe _table.isValid(bucket))
|
||||
return unsafe _members.unsafelyUnwrapped.advanced(by: bucket.offset)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -140,9 +154,9 @@ extension RigidSet where Element: ~Copyable {
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _seed: Int {
|
||||
#if COLLECTIONS_DETERMINISTIC_HASHING
|
||||
Int(_table.scale)
|
||||
unsafe Int(_table.scale)
|
||||
#else
|
||||
Int(bitPattern: _members)
|
||||
unsafe Int(bitPattern: _members)
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -151,8 +165,8 @@ extension RigidSet where Element: ~Copyable {
|
||||
internal borrowing func _hashValue(
|
||||
at bucket: _Bucket
|
||||
) -> Int {
|
||||
assert(bucket.offset >= 0 && bucket.offset < _table.storageCapacity)
|
||||
return _hashValue(for: _members.unsafelyUnwrapped[bucket.offset])
|
||||
assert(unsafe bucket.offset >= 0 && bucket.offset < _table.storageCapacity)
|
||||
return unsafe _hashValue(for: _members.unsafelyUnwrapped[bucket.offset])
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
|
||||
@@ -89,7 +89,7 @@ extension UniqueArray where Element: ~Copyable {
|
||||
moving items: UnsafeMutableBufferPointer<Element>
|
||||
) -> Range<Int> {
|
||||
_ensureFreeCapacity(items.count)
|
||||
return _storage._appendUnchecked(moving: items)
|
||||
return unsafe _storage._appendUnchecked(moving: items)
|
||||
}
|
||||
|
||||
#if UnstableContainersPreview
|
||||
@@ -131,8 +131,8 @@ extension UniqueArray where Element: ~Copyable {
|
||||
moving items: inout OutputSpan<Element>
|
||||
) -> Range<Int> {
|
||||
_ensureFreeCapacity(items.count)
|
||||
return items.withUnsafeMutableBufferPointer { buffer, count in
|
||||
let source = buffer._extracting(first: count)
|
||||
return unsafe items.withUnsafeMutableBufferPointer { buffer, count in
|
||||
let source = unsafe buffer._extracting(first: count)
|
||||
count = 0
|
||||
return unsafe _storage._appendUnchecked(moving: source)
|
||||
}
|
||||
@@ -159,9 +159,9 @@ extension UniqueArray where Element: ~Copyable {
|
||||
// FIXME: Remove in favor of the generic RRC algorithm
|
||||
_ensureFreeCapacity(items.count)
|
||||
return items.edit { source in
|
||||
source.withUnsafeMutableBufferPointer { buffer, count in
|
||||
unsafe source.withUnsafeMutableBufferPointer { buffer, count in
|
||||
count = 0
|
||||
return _storage.append(moving: buffer._extracting(first: count))
|
||||
return unsafe _storage.append(moving: buffer._extracting(first: count))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,11 +95,11 @@ extension UniqueArray where Element: ~Copyable {
|
||||
public subscript(position: Int) -> Element {
|
||||
@inline(__always)
|
||||
unsafeAddress {
|
||||
_storage._ptr(to: position)
|
||||
unsafe _storage._ptr(to: position)
|
||||
}
|
||||
@inline(__always)
|
||||
unsafeMutableAddress {
|
||||
_storage._mutablePtr(to: position)
|
||||
unsafe _storage._mutablePtr(to: position)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -184,7 +184,7 @@ extension UniqueArray where Element: ~Copyable {
|
||||
removing subrange: Range<Int>,
|
||||
moving newElements: UnsafeMutableBufferPointer<Element>,
|
||||
) {
|
||||
replaceSubrange(subrange, moving: newElements)
|
||||
unsafe replaceSubrange(subrange, moving: newElements)
|
||||
}
|
||||
|
||||
#if UnstableContainersPreview
|
||||
@@ -258,7 +258,7 @@ extension UniqueArray {
|
||||
removing subrange: Range<Int>,
|
||||
copying newElements: UnsafeBufferPointer<Element>
|
||||
) {
|
||||
replaceSubrange(subrange, copying: newElements)
|
||||
unsafe replaceSubrange(subrange, copying: newElements)
|
||||
}
|
||||
|
||||
@available(*, deprecated, renamed: "replace(_:copying:)")
|
||||
@@ -267,7 +267,7 @@ extension UniqueArray {
|
||||
removing subrange: Range<Int>,
|
||||
copying newElements: UnsafeMutableBufferPointer<Element>
|
||||
) {
|
||||
self.replaceSubrange(subrange, copying: newElements)
|
||||
unsafe self.replaceSubrange(subrange, copying: newElements)
|
||||
}
|
||||
|
||||
@available(*, deprecated, renamed: "replace(_:copying:)")
|
||||
|
||||
@@ -39,27 +39,6 @@ extension UniqueArray /*where Element: Copyable*/ {
|
||||
}
|
||||
#endif
|
||||
|
||||
#if false // TODO
|
||||
extension UniqueArray where Element: ~Copyable {
|
||||
@inlinable
|
||||
@inline(__always)
|
||||
@_lifetime(borrow self)
|
||||
public func borrowElement(at index: Int) -> Ref<Element> {
|
||||
_storage.borrowElement(at: index)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if false // TODO
|
||||
extension UniqueArray where Element: ~Copyable {
|
||||
@inlinable
|
||||
@_lifetime(&self)
|
||||
public mutating func mutateElement(at index: Int) -> Mut<Element> {
|
||||
_storage.mutateElement(at: index)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if false // TODO
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
extension UniqueArray where Element: ~Copyable {
|
||||
|
||||
@@ -113,13 +113,14 @@ extension UniqueArray where Element: ~Copyable {
|
||||
/// - Complexity: O(`self.count` + `items.count`)
|
||||
@_alwaysEmitIntoClient
|
||||
@discardableResult
|
||||
@unsafe
|
||||
public mutating func insert(
|
||||
moving items: UnsafeMutableBufferPointer<Element>,
|
||||
at index: Int
|
||||
) -> Range<Int> {
|
||||
// FIXME: Avoid moving the subsequent elements twice.
|
||||
_ensureFreeCapacity(items.count)
|
||||
return _storage.insert(moving: items, at: index)
|
||||
return unsafe _storage.insert(moving: items, at: index)
|
||||
}
|
||||
|
||||
#if UnstableContainersPreview
|
||||
@@ -231,6 +232,7 @@ extension UniqueArray {
|
||||
/// - Complexity: O(`self.count` + `newElements.count`)
|
||||
@inlinable
|
||||
@discardableResult
|
||||
@unsafe
|
||||
public mutating func insert(
|
||||
copying newElements: UnsafeBufferPointer<Element>, at index: Int
|
||||
) -> Range<Int> {
|
||||
@@ -262,6 +264,7 @@ extension UniqueArray {
|
||||
/// - Complexity: O(`self.count` + `newElements.count`)
|
||||
@inlinable
|
||||
@discardableResult
|
||||
@unsafe
|
||||
public mutating func insert(
|
||||
copying newElements: UnsafeMutableBufferPointer<Element>,
|
||||
at index: Int
|
||||
|
||||
@@ -70,7 +70,7 @@ extension UniqueArray where Element: ~Copyable {
|
||||
precondition(newItemCount >= 0, "Cannot add a negative number of items")
|
||||
// FIXME: Avoid moving the subsequent elements twice on resize.
|
||||
_ensureFreeCapacity(newItemCount - subrange.count)
|
||||
return try _storage._uncheckedReplaceSubrange(
|
||||
return unsafe try _storage._uncheckedReplaceSubrange(
|
||||
subrange,
|
||||
addingCount: newItemCount,
|
||||
initializingWith: initializer)
|
||||
@@ -139,7 +139,7 @@ extension UniqueArray where Element: ~Copyable {
|
||||
_storage._checkValidBounds(subrange)
|
||||
precondition(newItemCount >= 0, "Cannot add a negative number of items")
|
||||
_ensureFreeCapacity(newItemCount - subrange.count)
|
||||
return try _storage._uncheckedReplaceSubrange(
|
||||
return unsafe try _storage._uncheckedReplaceSubrange(
|
||||
subrange,
|
||||
consumingWith: consumer,
|
||||
addingCount: newItemCount,
|
||||
@@ -181,13 +181,14 @@ extension UniqueArray where Element: ~Copyable {
|
||||
/// - Complexity: O(`self.count` + `newElements.count`)
|
||||
@_alwaysEmitIntoClient
|
||||
@discardableResult
|
||||
@unsafe
|
||||
public mutating func replaceSubrange(
|
||||
_ subrange: Range<Int>,
|
||||
moving newElements: UnsafeMutableBufferPointer<Element>,
|
||||
) -> Range<Int> {
|
||||
// FIXME: Avoid moving the subsequent elements twice.
|
||||
_ensureFreeCapacity(newElements.count - subrange.count)
|
||||
return _storage.replaceSubrange(subrange, moving: newElements)
|
||||
return unsafe _storage.replaceSubrange(subrange, moving: newElements)
|
||||
}
|
||||
|
||||
#if UnstableContainersPreview
|
||||
@@ -381,6 +382,7 @@ extension UniqueArray {
|
||||
@_alwaysEmitIntoClient
|
||||
@inline(__always)
|
||||
@discardableResult
|
||||
@unsafe
|
||||
public mutating func replaceSubrange(
|
||||
_ subrange: Range<Int>,
|
||||
copying newElements: UnsafeBufferPointer<Element>
|
||||
|
||||
@@ -32,13 +32,14 @@ extension UniqueDictionary where Key: ~Copyable, Value: ~Copyable {
|
||||
#endif
|
||||
|
||||
@inlinable
|
||||
@unsafe
|
||||
public mutating func _consumeAll(
|
||||
consumingWith consumer: (
|
||||
UnsafeMutableBufferPointer<Key>,
|
||||
UnsafeMutableBufferPointer<Value>
|
||||
) -> Void
|
||||
) {
|
||||
_storage._consumeAll(consumingWith: consumer)
|
||||
unsafe _storage._consumeAll(consumingWith: consumer)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -25,10 +25,10 @@ extension UniqueDictionary where Key: ~Copyable, Value: ~Copyable {
|
||||
if bucket != nil {
|
||||
return value
|
||||
}
|
||||
if _ensureFreeCapacity(1), !_storage._keys._table.isSmall {
|
||||
if _ensureFreeCapacity(1), !_storage._isSmall {
|
||||
hashValue = _storage._keys._hashValue(for: key)
|
||||
}
|
||||
_storage._insertNew(key, hashValue: hashValue, value)
|
||||
unsafe _storage._insertNew(key, hashValue: hashValue, value)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -40,12 +40,12 @@ extension UniqueDictionary where Key: ~Copyable, Value: ~Copyable {
|
||||
) -> Value? {
|
||||
var (bucket, hashValue) = _storage._find(key)
|
||||
if let bucket {
|
||||
return exchange(&_storage._valuePtr(at: bucket).pointee, with: value)
|
||||
return unsafe exchange(&_storage._valuePtr(at: bucket).pointee, with: value)
|
||||
}
|
||||
if _ensureFreeCapacity(1), !_storage._keys._table.isSmall {
|
||||
if _ensureFreeCapacity(1), !_storage._isSmall {
|
||||
hashValue = _storage._keys._hashValue(for: key)
|
||||
}
|
||||
_storage._insertNew(key, hashValue: hashValue, value)
|
||||
unsafe _storage._insertNew(key, hashValue: hashValue, value)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -64,10 +64,10 @@ extension UniqueDictionary where Key: ~Copyable, Value: ~Copyable {
|
||||
} else {
|
||||
let value = try body(key)
|
||||
var hashValue = r.hashValue
|
||||
if _ensureFreeCapacity(1), !_storage._keys._table.isSmall {
|
||||
if _ensureFreeCapacity(1), !_storage._isSmall {
|
||||
hashValue = _storage._keys._hashValue(for: key)
|
||||
}
|
||||
bucket = _storage._insertNew(key, hashValue: hashValue, value)
|
||||
bucket = unsafe _storage._insertNew(key, hashValue: hashValue, value)
|
||||
}
|
||||
return _storage._borrowValue(at: bucket)
|
||||
}
|
||||
@@ -84,25 +84,25 @@ extension UniqueDictionary where Key: ~Copyable, Value: ~Copyable {
|
||||
let r = _storage._find(key)
|
||||
bucket = r.bucket
|
||||
if let bucket {
|
||||
value = _storage._valuePtr(at: bucket).move()
|
||||
value = unsafe _storage._valuePtr(at: bucket).move()
|
||||
}
|
||||
|
||||
var key: Key? = key // To work around inability to consume key in deinit
|
||||
defer {
|
||||
if let bucket {
|
||||
if let value = value.take() { // Simple update
|
||||
_storage._valuePtr(at: bucket).initialize(to: value)
|
||||
unsafe _storage._valuePtr(at: bucket).initialize(to: value)
|
||||
} else { // Removal
|
||||
_ = _removeValue(at: bucket)
|
||||
_ = unsafe _removeValue(at: bucket)
|
||||
}
|
||||
} else if let value = value.take() {
|
||||
// Insertion.
|
||||
let key = key.take()!
|
||||
var hashValue = r.hashValue
|
||||
if _ensureFreeCapacity(1), !_storage._keys._table.isSmall {
|
||||
if _ensureFreeCapacity(1), !_storage._isSmall {
|
||||
hashValue = _storage._keys._hashValue(for: key)
|
||||
}
|
||||
_storage._insertNew(key, hashValue: hashValue, value)
|
||||
unsafe _storage._insertNew(key, hashValue: hashValue, value)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ extension UniqueDictionary where Key: ~Copyable, Value: ~Copyable {
|
||||
forKey key: borrowing Key
|
||||
) -> Ref<Value>? {
|
||||
// FIXME: Why is this override necessary? Is it sound? It was triggered by RigidDictionary becoming `@_addressableForDependencies`.
|
||||
_overrideLifetime(_storage.value(forKey: key), borrowing: self)
|
||||
unsafe _overrideLifetime(_storage.value(forKey: key), borrowing: self)
|
||||
}
|
||||
|
||||
/// Checks if the given key is present in the `RigidDictionary`, and returns
|
||||
|
||||
@@ -19,17 +19,18 @@ extension UniqueDictionary where Key: ~Copyable, Value: ~Copyable {
|
||||
public mutating func removeValue(forKey key: borrowing Key) -> Value? {
|
||||
let r = _storage._keys._find(key)
|
||||
guard let bucket = r.bucket else { return nil }
|
||||
return _removeValue(at: bucket)
|
||||
return unsafe _removeValue(at: bucket)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@unsafe
|
||||
package mutating func _removeValue(at bucket: _Bucket) -> Value {
|
||||
guard self.count <= _HTable.minimumCapacity(forScale: self._scale) else {
|
||||
return _storage._removeValue(at: bucket)
|
||||
}
|
||||
|
||||
// Shrink storage.
|
||||
let result = _storage._punchHole(at: bucket)
|
||||
let result = unsafe _storage._punchHole(at: bucket)
|
||||
_resize(minimumCapacity: self.count)
|
||||
return result
|
||||
}
|
||||
|
||||
@@ -47,13 +47,13 @@ extension UniqueDictionary where Key: ~Copyable, Value: ~Copyable {
|
||||
@inlinable
|
||||
@inline(__always)
|
||||
public var count: Int {
|
||||
_assumeNonNegative(_storage._keys._table._count)
|
||||
_storage.count
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@inline(__always)
|
||||
public var capacity: Int {
|
||||
_assumeNonNegative(_storage._keys._table._capacity)
|
||||
_storage.capacity
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@@ -71,7 +71,7 @@ extension UniqueDictionary where Key: ~Copyable, Value: ~Copyable {
|
||||
@inlinable
|
||||
@inline(__always)
|
||||
public var freeCapacity: Int {
|
||||
_assumeNonNegative(capacity &- count)
|
||||
_storage.freeCapacity
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
|
||||
@@ -23,18 +23,15 @@ extension UniqueSet where Element: ~Copyable {
|
||||
public mutating func consumeAll(
|
||||
consumingWith consumer: (inout InputSpan<Element>) -> Void
|
||||
) {
|
||||
self._consumeAll { buffer in
|
||||
var span = InputSpan(buffer: buffer, initializedCount: buffer.count)
|
||||
consumer(&span)
|
||||
_ = consume span
|
||||
}
|
||||
_storage.consumeAll(consumingWith: consumer)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@unsafe
|
||||
public mutating func _consumeAll(
|
||||
consumingWith consumer: (UnsafeMutableBufferPointer<Element>) -> Void
|
||||
) {
|
||||
_storage._consumeAll(consumingWith: consumer)
|
||||
unsafe _storage._consumeAll(consumingWith: consumer)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ extension UniqueSet where Element: ~Copyable {
|
||||
public init(minimumCapacity: Int) {
|
||||
precondition(minimumCapacity >= 0, "Capacity must be nonnegative")
|
||||
let table = _HTable(minimumCapacity: minimumCapacity)
|
||||
self.init(_storage: RigidSet(_table: table))
|
||||
unsafe self.init(_storage: RigidSet(_table: table))
|
||||
}
|
||||
|
||||
@inlinable
|
||||
|
||||
@@ -24,7 +24,7 @@ extension UniqueSet where Element: ~Copyable {
|
||||
return .init(bucket: bucket, remnant: item)
|
||||
}
|
||||
var hashValue = r.hashValue
|
||||
if _ensureFreeCapacity(1), !_storage._table.isSmall {
|
||||
if _ensureFreeCapacity(1), !_isSmall {
|
||||
hashValue = _storage._hashValue(for: item)
|
||||
}
|
||||
let bucket = _storage._insertNew(item, hashValue: hashValue)
|
||||
@@ -44,7 +44,7 @@ extension UniqueSet where Element: ~Copyable {
|
||||
) -> Element? {
|
||||
var r = self._insert(item)
|
||||
guard let remnant = r.remnant.take() else { return nil }
|
||||
return exchange(
|
||||
return unsafe exchange(
|
||||
&_storage._memberPtr(at: r.bucket).pointee,
|
||||
with: remnant)
|
||||
}
|
||||
|
||||
@@ -16,12 +16,13 @@
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
extension UniqueSet where Element: ~Copyable {
|
||||
@inlinable
|
||||
@unsafe
|
||||
package mutating func _remove(at bucket: _Bucket) -> Element {
|
||||
guard self.count <= _HTable.minimumCapacity(forScale: self._scale) else {
|
||||
return _storage._remove(at: bucket)
|
||||
return unsafe _storage._remove(at: bucket)
|
||||
}
|
||||
// Shrink storage.
|
||||
let result = _storage._punchHole(at: bucket)
|
||||
let result = unsafe _storage._punchHole(at: bucket)
|
||||
_resize(minimumCapacity: self.count)
|
||||
return result
|
||||
}
|
||||
@@ -30,7 +31,7 @@ extension UniqueSet where Element: ~Copyable {
|
||||
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)
|
||||
return unsafe _remove(at: bucket)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
|
||||
@@ -69,7 +69,13 @@ extension UniqueSet where Element: ~Copyable {
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
public var _scale: UInt8 {
|
||||
_storage._table.scale
|
||||
unsafe _storage._table.scale
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
public var _isSmall: Bool {
|
||||
_storage._isSmall
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -157,14 +157,14 @@ extension BitArray {
|
||||
|
||||
extension BitArray {
|
||||
public mutating func toggleAll() {
|
||||
_update { handle in
|
||||
let w = handle._mutableWords
|
||||
for i in 0 ..< handle._words.count {
|
||||
w[i].formComplement()
|
||||
unsafe _update { handle in
|
||||
let w = unsafe handle._mutableWords
|
||||
for i in unsafe 0 ..< handle._words.count {
|
||||
unsafe w[i].formComplement()
|
||||
}
|
||||
let p = handle.end
|
||||
if p.bit > 0 {
|
||||
w[p.word].subtract(_Word(upTo: p.bit).complement())
|
||||
unsafe w[p.word].subtract(_Word(upTo: p.bit).complement())
|
||||
}
|
||||
}
|
||||
_checkInvariants()
|
||||
@@ -173,22 +173,22 @@ extension BitArray {
|
||||
public mutating func toggleAll(in range: Range<Int>) {
|
||||
precondition(range.upperBound <= count, "Range out of bounds")
|
||||
guard !range.isEmpty else { return }
|
||||
_update { handle in
|
||||
let words = handle._mutableWords
|
||||
unsafe _update { handle in
|
||||
let words = unsafe handle._mutableWords
|
||||
let start = _BitPosition(range.lowerBound)
|
||||
let end = _BitPosition(range.upperBound)
|
||||
if start.word == end.word {
|
||||
let bits = _Word(from: start.bit, to: end.bit)
|
||||
words[start.word].formSymmetricDifference(bits)
|
||||
unsafe words[start.word].formSymmetricDifference(bits)
|
||||
return
|
||||
}
|
||||
words[start.word].formSymmetricDifference(
|
||||
unsafe words[start.word].formSymmetricDifference(
|
||||
_Word(upTo: start.bit).complement())
|
||||
for i in stride(from: start.word + 1, to: end.word, by: 1) {
|
||||
words[i].formComplement()
|
||||
unsafe words[i].formComplement()
|
||||
}
|
||||
if end.bit > 0 {
|
||||
words[end.word].formSymmetricDifference(_Word(upTo: end.bit))
|
||||
unsafe words[end.word].formSymmetricDifference(_Word(upTo: end.bit))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,11 +15,14 @@
|
||||
import InternalCollectionsUtilities
|
||||
#endif
|
||||
|
||||
@unsafe
|
||||
internal struct _ChunkedBitsForwardIterator {
|
||||
internal typealias _BitPosition = _UnsafeBitSet.Index
|
||||
|
||||
internal let words: UnsafeBufferPointer<_Word>
|
||||
@safe
|
||||
internal let end: _BitPosition
|
||||
@safe
|
||||
internal var position: _BitPosition
|
||||
|
||||
internal init(
|
||||
@@ -28,7 +31,7 @@ internal struct _ChunkedBitsForwardIterator {
|
||||
) {
|
||||
assert(range.lowerBound >= 0)
|
||||
assert(range.upperBound <= words.count * _Word.capacity)
|
||||
self.words = words
|
||||
unsafe self.words = words
|
||||
self.end = _BitPosition(range.upperBound)
|
||||
self.position = _BitPosition(range.lowerBound)
|
||||
}
|
||||
@@ -38,7 +41,7 @@ internal struct _ChunkedBitsForwardIterator {
|
||||
let (w, b) = position.split
|
||||
if w == end.word {
|
||||
position = end
|
||||
return (
|
||||
return unsafe (
|
||||
bits: words[w]
|
||||
.intersection(_Word(upTo: end.bit))
|
||||
.shiftedDown(by: b),
|
||||
@@ -46,15 +49,18 @@ internal struct _ChunkedBitsForwardIterator {
|
||||
}
|
||||
let c = _Word._capacity - b
|
||||
position.value += c
|
||||
return (bits: words[w].shiftedDown(by: b), count: c)
|
||||
return unsafe (bits: words[w].shiftedDown(by: b), count: c)
|
||||
}
|
||||
}
|
||||
|
||||
@unsafe
|
||||
internal struct _ChunkedBitsBackwardIterator {
|
||||
internal typealias _BitPosition = _UnsafeBitSet.Index
|
||||
|
||||
internal let words: UnsafeBufferPointer<_Word>
|
||||
@safe
|
||||
internal let start: _BitPosition
|
||||
@safe
|
||||
internal var position: _BitPosition
|
||||
|
||||
internal init(
|
||||
@@ -63,7 +69,7 @@ internal struct _ChunkedBitsBackwardIterator {
|
||||
) {
|
||||
assert(range.lowerBound >= 0)
|
||||
assert(range.upperBound <= words.count * _Word.capacity)
|
||||
self.words = words
|
||||
unsafe self.words = words
|
||||
self.start = _BitPosition(range.lowerBound)
|
||||
self.position = _BitPosition(range.upperBound)
|
||||
}
|
||||
@@ -73,7 +79,7 @@ internal struct _ChunkedBitsBackwardIterator {
|
||||
let (w, b) = position.endSplit
|
||||
if w == start.word {
|
||||
position = start
|
||||
return (
|
||||
return unsafe (
|
||||
bits: words[w]
|
||||
.intersection(_Word(upTo: b))
|
||||
.shiftedDown(by: start.bit),
|
||||
@@ -81,7 +87,7 @@ internal struct _ChunkedBitsBackwardIterator {
|
||||
}
|
||||
let c = b
|
||||
position.value -= c
|
||||
return (bits: words[w].intersection(_Word(upTo: b)), count: c)
|
||||
return unsafe (bits: words[w].intersection(_Word(upTo: b)), count: c)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -176,14 +176,14 @@ extension BitArray: RandomAccessCollection, MutableCollection {
|
||||
public subscript(position: Int) -> Bool {
|
||||
get {
|
||||
precondition(position >= 0 && position < _count, "Index out of bounds")
|
||||
return _read { handle in
|
||||
handle[position]
|
||||
return unsafe _read { handle in
|
||||
unsafe handle[position]
|
||||
}
|
||||
}
|
||||
set {
|
||||
precondition(position >= 0 && position < _count, "Index out of bounds")
|
||||
return _update { handle in
|
||||
handle[position] = newValue
|
||||
return unsafe _update { handle in
|
||||
unsafe handle[position] = newValue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,8 +20,8 @@ extension BitArray {
|
||||
from range: Range<Int>,
|
||||
to target: Int
|
||||
) {
|
||||
_update { handle in
|
||||
handle.copy(from: range, to: target)
|
||||
unsafe _update { handle in
|
||||
unsafe handle.copy(from: range, to: target)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,8 +30,8 @@ extension BitArray {
|
||||
in source: UnsafeBufferPointer<_Word>,
|
||||
to target: Int
|
||||
) {
|
||||
_update { handle in
|
||||
handle.copy(from: range, in: source, to: target)
|
||||
unsafe _update { handle in
|
||||
unsafe handle.copy(from: range, in: source, to: target)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,7 +48,7 @@ extension BitArray {
|
||||
) {
|
||||
let range = source._bounds
|
||||
source.base._storage.withUnsafeBufferPointer { words in
|
||||
self._copy(from: range, in: words, to: target)
|
||||
unsafe self._copy(from: range, in: words, to: target)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,7 +56,7 @@ extension BitArray {
|
||||
from source: S,
|
||||
to range: Range<Int>
|
||||
) where S.Element == Bool {
|
||||
_update { $0.copy(from: source, to: range) }
|
||||
unsafe _update { unsafe $0.copy(from: source, to: range) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,21 +66,21 @@ extension BitArray._UnsafeHandle {
|
||||
) {
|
||||
assert(count <= _Word.capacity)
|
||||
assert(count == _Word.capacity || bits.shiftedDown(by: count).isEmpty)
|
||||
assert(target.value + count <= _count)
|
||||
assert(target.value + count <= self.count)
|
||||
let start = target.split
|
||||
let end = _BitPosition(target.value + count).endSplit
|
||||
let words = _mutableWords
|
||||
let words = unsafe _mutableWords
|
||||
if start.word == end.word {
|
||||
let mask = _Word(from: start.bit, to: end.bit)
|
||||
words[start.word].formIntersection(mask.complement())
|
||||
words[start.word].formUnion(bits.shiftedUp(by: start.bit))
|
||||
unsafe words[start.word].formIntersection(mask.complement())
|
||||
unsafe words[start.word].formUnion(bits.shiftedUp(by: start.bit))
|
||||
return
|
||||
}
|
||||
assert(start.word + 1 == end.word)
|
||||
words[start.word].formIntersection(_Word(upTo: start.bit))
|
||||
words[start.word].formUnion(bits.shiftedUp(by: start.bit))
|
||||
words[end.word].formIntersection(_Word(upTo: end.bit).complement())
|
||||
words[end.word].formUnion(
|
||||
unsafe words[start.word].formIntersection(_Word(upTo: start.bit))
|
||||
unsafe words[start.word].formUnion(bits.shiftedUp(by: start.bit))
|
||||
unsafe words[end.word].formIntersection(_Word(upTo: end.bit).complement())
|
||||
unsafe words[end.word].formUnion(
|
||||
bits.shiftedDown(by: _Word._capacity &- start.bit))
|
||||
}
|
||||
|
||||
@@ -91,7 +91,7 @@ extension BitArray._UnsafeHandle {
|
||||
assert(
|
||||
range.lowerBound >= 0 && range.upperBound <= self.count,
|
||||
"Source range out of bounds")
|
||||
copy(from: range, in: _words, to: target)
|
||||
unsafe copy(from: range, in: _words, to: target)
|
||||
}
|
||||
|
||||
internal mutating func copy(
|
||||
@@ -114,17 +114,17 @@ extension BitArray._UnsafeHandle {
|
||||
let upperSource = _BitPosition(range.upperBound).endSplit
|
||||
|
||||
|
||||
let targetPtr = _words._ptr(at: target.word)
|
||||
let lowerSourcePtr = source._ptr(at: lowerSource.word)
|
||||
let upperSourcePtr = source._ptr(at: upperSource.word)
|
||||
let targetPtr = unsafe _words._ptr(at: target.word)
|
||||
let lowerSourcePtr = unsafe source._ptr(at: lowerSource.word)
|
||||
let upperSourcePtr = unsafe source._ptr(at: upperSource.word)
|
||||
|
||||
if targetPtr < lowerSourcePtr || targetPtr > upperSourcePtr {
|
||||
if unsafe targetPtr < lowerSourcePtr || targetPtr > upperSourcePtr {
|
||||
return true
|
||||
}
|
||||
if targetPtr == lowerSourcePtr, target.bit < lowerSource.bit {
|
||||
if unsafe targetPtr == lowerSourcePtr, target.bit < lowerSource.bit {
|
||||
return true
|
||||
}
|
||||
if targetPtr == upperSourcePtr, target.bit >= upperSource.bit {
|
||||
if unsafe targetPtr == upperSourcePtr, target.bit >= upperSource.bit {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
@@ -132,20 +132,20 @@ extension BitArray._UnsafeHandle {
|
||||
|
||||
if goForward() {
|
||||
// Copy forward from a disjoint or following overlapping range.
|
||||
var src = _ChunkedBitsForwardIterator(words: source, range: range)
|
||||
var src = unsafe _ChunkedBitsForwardIterator(words: source, range: range)
|
||||
var dst = _BitPosition(target)
|
||||
while let (bits, count) = src.next() {
|
||||
_copy(bits: bits, count: count, to: dst)
|
||||
while let (bits, count) = unsafe src.next() {
|
||||
unsafe _copy(bits: bits, count: count, to: dst)
|
||||
dst.value += count
|
||||
}
|
||||
assert(dst.value == target + range.count)
|
||||
} else {
|
||||
// Copy backward from a non-following overlapping range.
|
||||
var src = _ChunkedBitsBackwardIterator(words: source, range: range)
|
||||
var src = unsafe _ChunkedBitsBackwardIterator(words: source, range: range)
|
||||
var dst = _BitPosition(target + range.count)
|
||||
while let (bits, count) = src.next() {
|
||||
while let (bits, count) = unsafe src.next() {
|
||||
dst.value -= count
|
||||
_copy(bits: bits, count: count, to: dst)
|
||||
unsafe _copy(bits: bits, count: count, to: dst)
|
||||
}
|
||||
assert(dst.value == target)
|
||||
}
|
||||
@@ -163,14 +163,14 @@ extension BitArray._UnsafeHandle {
|
||||
if pos.bit > 0 {
|
||||
let (bits, count) = it._nextChunk(
|
||||
maxCount: _Word._capacity - pos.bit)
|
||||
_copy(bits: bits, count: count, to: pos)
|
||||
unsafe _copy(bits: bits, count: count, to: pos)
|
||||
pos.value += count
|
||||
}
|
||||
while true {
|
||||
let (bits, count) = it._nextChunk()
|
||||
guard count > 0 else { break }
|
||||
assert(pos.bit == 0)
|
||||
_copy(bits: bits, count: count, to: pos)
|
||||
unsafe _copy(bits: bits, count: count, to: pos)
|
||||
pos.value += count
|
||||
}
|
||||
precondition(pos.value == range.upperBound)
|
||||
|
||||
@@ -66,14 +66,14 @@ extension BitArray {
|
||||
var result: String
|
||||
if #available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *) {
|
||||
result = String(unsafeUninitializedCapacity: self.count + 2) { target in
|
||||
target.initializeElement(at: count + 1, to: ._asciiGT)
|
||||
unsafe target.initializeElement(at: count + 1, to: ._asciiGT)
|
||||
var i = count
|
||||
for v in self {
|
||||
target.initializeElement(at: i, to: v ? ._ascii1 : ._ascii0)
|
||||
unsafe target.initializeElement(at: i, to: v ? ._ascii1 : ._ascii0)
|
||||
i &-= 1
|
||||
}
|
||||
assert(i == 0)
|
||||
target.initializeElement(at: 0, to: ._asciiLT)
|
||||
unsafe target.initializeElement(at: 0, to: ._asciiLT)
|
||||
return count + 2
|
||||
}
|
||||
} else {
|
||||
|
||||
@@ -16,7 +16,7 @@ extension BitArray {
|
||||
///
|
||||
/// - Parameter value: The Boolean value to which to set the array's elements.
|
||||
public mutating func fill(with value: Bool = true) {
|
||||
fill(in: Range(uncheckedBounds: (0, count)), with: value)
|
||||
fill(in: unsafe Range(uncheckedBounds: (0, count)), with: value)
|
||||
}
|
||||
|
||||
/// Set every bit of this array within the specified range to `value`
|
||||
@@ -25,11 +25,11 @@ extension BitArray {
|
||||
/// - Parameter range: The range whose elements to overwrite.
|
||||
/// - Parameter value: The Boolean value to which to set the array's elements.
|
||||
public mutating func fill(in range: Range<Int>, with value: Bool = true) {
|
||||
_update { handle in
|
||||
unsafe _update { handle in
|
||||
if value {
|
||||
handle.fill(in: range)
|
||||
unsafe handle.fill(in: range)
|
||||
} else {
|
||||
handle.clear(in: range)
|
||||
unsafe handle.clear(in: range)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,13 +75,13 @@ extension BitArray {
|
||||
isSigned: Bool,
|
||||
body: (Int, UInt) -> Bool
|
||||
) -> Bool {
|
||||
self._read {
|
||||
guard $0._words.count > 0 else { return false }
|
||||
unsafe self._read {
|
||||
guard unsafe $0._words.count > 0 else { return false }
|
||||
|
||||
var isNegative = false
|
||||
let end = $0.end.endSplit
|
||||
assert(end.bit > 0)
|
||||
let last = $0._words[end.word]
|
||||
let last = unsafe $0._words[end.word]
|
||||
if isSigned, last.contains(end.bit - 1) {
|
||||
// Sign extend last word
|
||||
isNegative = true
|
||||
@@ -92,7 +92,7 @@ extension BitArray {
|
||||
return isNegative
|
||||
}
|
||||
for i in stride(from: end.word - 1, through: 0, by: -1) {
|
||||
if !body(i, $0._words[i].value) { return isNegative }
|
||||
if unsafe !body(i, $0._words[i].value) { return isNegative }
|
||||
}
|
||||
return isNegative
|
||||
}
|
||||
|
||||
@@ -38,8 +38,8 @@ extension BitArray: LosslessStringConvertible {
|
||||
if digits.utf8.first == ._asciiLT, digits.utf8.last == ._asciiGT {
|
||||
digits = digits.dropFirst().dropLast()
|
||||
}
|
||||
let bits: BitArray? = digits.utf8.withContiguousStorageIfAvailable { buffer in
|
||||
Self(_utf8Digits: buffer)
|
||||
let bits: BitArray? = unsafe digits.utf8.withContiguousStorageIfAvailable { buffer in
|
||||
unsafe Self(_utf8Digits: buffer)
|
||||
} ?? Self(_utf8Digits: description.utf8)
|
||||
guard let bits = bits else {
|
||||
return nil
|
||||
@@ -51,10 +51,10 @@ extension BitArray: LosslessStringConvertible {
|
||||
let c = utf8.count
|
||||
self.init(repeating: false, count: c)
|
||||
var i = c &- 1
|
||||
let success = _update { handle in
|
||||
let success = unsafe _update { handle in
|
||||
for byte in utf8 {
|
||||
if byte == ._ascii1 {
|
||||
handle.set(at: i)
|
||||
unsafe handle.set(at: i)
|
||||
} else {
|
||||
guard byte == ._ascii0 else { return false }
|
||||
}
|
||||
|
||||
@@ -251,8 +251,8 @@ extension BitArray {
|
||||
}
|
||||
_count += 1
|
||||
if newElement {
|
||||
_update { handle in
|
||||
handle._mutableWords[word].value |= 1 &<< bit
|
||||
unsafe _update { handle in
|
||||
unsafe handle._mutableWords[word].value |= 1 &<< bit
|
||||
}
|
||||
}
|
||||
_checkInvariants()
|
||||
@@ -288,7 +288,7 @@ extension BitArray {
|
||||
maxCount: _Word._capacity - pos.bit)
|
||||
guard count > 0 else { return }
|
||||
_count += count
|
||||
_update { $0._copy(bits: bits, count: count, to: pos) }
|
||||
unsafe _update { unsafe $0._copy(bits: bits, count: count, to: pos) }
|
||||
pos.value += count
|
||||
}
|
||||
while true {
|
||||
@@ -297,7 +297,7 @@ extension BitArray {
|
||||
assert(pos.bit == 0)
|
||||
_storage.append(.empty)
|
||||
_count += count
|
||||
_update { $0._copy(bits: bits, count: count, to: pos) }
|
||||
unsafe _update { unsafe $0._copy(bits: bits, count: count, to: pos) }
|
||||
pos.value += count
|
||||
}
|
||||
_checkInvariants()
|
||||
@@ -363,9 +363,9 @@ extension BitArray {
|
||||
}
|
||||
let c = count
|
||||
_count += 1
|
||||
_update { handle in
|
||||
handle.copy(from: i ..< c, to: i + 1)
|
||||
handle[i] = newElement
|
||||
unsafe _update { handle in
|
||||
unsafe handle.copy(from: i ..< c, to: i + 1)
|
||||
unsafe handle[i] = newElement
|
||||
}
|
||||
_checkInvariants()
|
||||
}
|
||||
@@ -484,7 +484,7 @@ extension BitArray {
|
||||
range.lowerBound >= 0 && range.upperBound <= count,
|
||||
"Bounds out of range")
|
||||
_copy(
|
||||
from: Range(uncheckedBounds: (range.upperBound, count)),
|
||||
from: unsafe Range(uncheckedBounds: (range.upperBound, count)),
|
||||
to: range.lowerBound)
|
||||
_removeLast(range.count)
|
||||
_checkInvariants()
|
||||
|
||||
@@ -74,7 +74,7 @@ extension BitArray {
|
||||
self = .init()
|
||||
return
|
||||
}
|
||||
self._copy(from: Range(uncheckedBounds: (amount, count)), to: 0)
|
||||
self._copy(from: unsafe Range(uncheckedBounds: (amount, count)), to: 0)
|
||||
self._removeLast(count &- amount)
|
||||
}
|
||||
}
|
||||
@@ -102,11 +102,11 @@ extension BitArray {
|
||||
/// // bits is now 0000000
|
||||
public mutating func maskingShiftLeft(by amount: Int) {
|
||||
guard amount != 0 else { return }
|
||||
_update {
|
||||
unsafe _update {
|
||||
if amount > 0 {
|
||||
$0._maskingShiftLeft(by: amount)
|
||||
unsafe $0._maskingShiftLeft(by: amount)
|
||||
} else {
|
||||
$0._maskingShiftRight(by: -amount)
|
||||
unsafe $0._maskingShiftRight(by: -amount)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -131,11 +131,11 @@ extension BitArray {
|
||||
/// // bits is now 0000000
|
||||
public mutating func maskingShiftRight(by amount: Int) {
|
||||
guard amount != 0 else { return }
|
||||
_update {
|
||||
unsafe _update {
|
||||
if amount > 0 {
|
||||
$0._maskingShiftRight(by: amount)
|
||||
unsafe $0._maskingShiftRight(by: amount)
|
||||
} else {
|
||||
$0._maskingShiftLeft(by: -amount)
|
||||
unsafe $0._maskingShiftLeft(by: -amount)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -146,19 +146,19 @@ extension BitArray._UnsafeHandle {
|
||||
assert(amount > 0)
|
||||
let d = Swift.min(amount, self.count)
|
||||
if d == amount {
|
||||
let range = Range(uncheckedBounds: (0, self.count &- d))
|
||||
self.copy(from: range, to: d)
|
||||
let range = unsafe Range(uncheckedBounds: (0, self.count &- d))
|
||||
unsafe self.copy(from: range, to: d)
|
||||
}
|
||||
self.clear(in: Range(uncheckedBounds: (0, d)))
|
||||
unsafe self.clear(in: Range(uncheckedBounds: (0, d)))
|
||||
}
|
||||
|
||||
internal mutating func _maskingShiftRight(by amount: Int) {
|
||||
assert(amount > 0)
|
||||
let d = Swift.min(amount, self.count)
|
||||
if d == amount {
|
||||
let range = Range(uncheckedBounds: (d, self.count))
|
||||
self.copy(from: range, to: 0)
|
||||
let range = unsafe Range(uncheckedBounds: (d, self.count))
|
||||
unsafe self.copy(from: range, to: 0)
|
||||
}
|
||||
self.clear(in: Range(uncheckedBounds: (self.count &- d, self.count)))
|
||||
unsafe self.clear(in: Range(uncheckedBounds: (self.count &- d, self.count)))
|
||||
}
|
||||
}
|
||||
@@ -16,8 +16,7 @@ import InternalCollectionsUtilities
|
||||
#endif
|
||||
|
||||
extension BitArray {
|
||||
@_spi(Testing)
|
||||
public var _capacity: Int {
|
||||
package var _capacity: Int {
|
||||
_storage.capacity * _Word.capacity
|
||||
}
|
||||
}
|
||||
@@ -20,24 +20,29 @@ extension BitArray {
|
||||
/// primitives.
|
||||
@usableFromInline
|
||||
@frozen
|
||||
@unsafe
|
||||
internal struct _UnsafeHandle {
|
||||
@usableFromInline
|
||||
internal typealias _BitPosition = _UnsafeBitSet.Index
|
||||
|
||||
@usableFromInline
|
||||
@unsafe
|
||||
internal let _words: UnsafeBufferPointer<_Word>
|
||||
|
||||
@usableFromInline
|
||||
@unsafe // Setter
|
||||
internal var _count: UInt
|
||||
|
||||
#if DEBUG
|
||||
/// True when this handle does not support table mutations.
|
||||
/// (This is only checked in debug builds.)
|
||||
@usableFromInline
|
||||
@safe
|
||||
internal let _mutable: Bool
|
||||
#endif
|
||||
|
||||
@inline(__always)
|
||||
@safe
|
||||
internal func ensureMutable() {
|
||||
#if DEBUG
|
||||
assert(_mutable)
|
||||
@@ -46,7 +51,7 @@ extension BitArray {
|
||||
|
||||
internal var _mutableWords: UnsafeMutableBufferPointer<_Word> {
|
||||
ensureMutable()
|
||||
return UnsafeMutableBufferPointer(mutating: _words)
|
||||
return unsafe UnsafeMutableBufferPointer(mutating: _words)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@@ -58,8 +63,8 @@ extension BitArray {
|
||||
) {
|
||||
assert(count <= words.count * _Word.capacity)
|
||||
assert(count > (words.count - 1) * _Word.capacity)
|
||||
self._words = words
|
||||
self._count = count
|
||||
unsafe self._words = words
|
||||
unsafe self._count = count
|
||||
#if DEBUG
|
||||
self._mutable = mutable
|
||||
#endif
|
||||
@@ -72,7 +77,7 @@ extension BitArray {
|
||||
count: UInt,
|
||||
mutable: Bool
|
||||
) {
|
||||
self.init(
|
||||
unsafe self.init(
|
||||
words: UnsafeBufferPointer(words),
|
||||
count: count,
|
||||
mutable: mutable)
|
||||
@@ -81,42 +86,45 @@ extension BitArray {
|
||||
}
|
||||
|
||||
extension BitArray._UnsafeHandle {
|
||||
@safe
|
||||
@_transparent
|
||||
internal var count: Int {
|
||||
Int(_count)
|
||||
unsafe Int(_count)
|
||||
}
|
||||
|
||||
@safe
|
||||
internal var end: _BitPosition {
|
||||
_BitPosition(_count)
|
||||
unsafe _BitPosition(_count)
|
||||
}
|
||||
|
||||
internal func set(at position: Int) {
|
||||
ensureMutable()
|
||||
assert(position >= 0 && position < _count)
|
||||
assert(position >= 0 && position < count)
|
||||
let (word, bit) = _BitPosition(UInt(position)).split
|
||||
_mutableWords[word].insert(bit)
|
||||
unsafe _mutableWords[word].insert(bit)
|
||||
}
|
||||
|
||||
internal func clear(at position: Int) {
|
||||
ensureMutable()
|
||||
assert(position >= 0 && position < _count)
|
||||
assert(position >= 0 && position < count)
|
||||
let (word, bit) = _BitPosition(UInt(position)).split
|
||||
_mutableWords[word].remove(bit)
|
||||
unsafe _mutableWords[word].remove(bit)
|
||||
}
|
||||
|
||||
internal subscript(position: Int) -> Bool {
|
||||
get {
|
||||
assert(position >= 0 && position < _count)
|
||||
assert(position >= 0 && position < count)
|
||||
let (word, bit) = _BitPosition(UInt(position)).split
|
||||
return _words[word].contains(bit)
|
||||
return unsafe _words[word].contains(bit)
|
||||
}
|
||||
set {
|
||||
ensureMutable()
|
||||
assert(position >= 0 && position < _count)
|
||||
assert(position >= 0 && position < count)
|
||||
let (word, bit) = _BitPosition(UInt(position)).split
|
||||
if newValue {
|
||||
_mutableWords[word].insert(bit)
|
||||
unsafe _mutableWords[word].insert(bit)
|
||||
} else {
|
||||
_mutableWords[word].remove(bit)
|
||||
unsafe _mutableWords[word].remove(bit)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -131,16 +139,16 @@ extension BitArray._UnsafeHandle {
|
||||
guard range.count > 0 else { return }
|
||||
let (lw, lb) = _BitPosition(range.lowerBound).split
|
||||
let (uw, ub) = _BitPosition(range.upperBound).endSplit
|
||||
let words = _mutableWords
|
||||
let words = unsafe _mutableWords
|
||||
guard lw != uw else {
|
||||
words[lw].formUnion(_Word(from: lb, to: ub))
|
||||
unsafe words[lw].formUnion(_Word(from: lb, to: ub))
|
||||
return
|
||||
}
|
||||
words[lw].formUnion(_Word(upTo: lb).complement())
|
||||
unsafe words[lw].formUnion(_Word(upTo: lb).complement())
|
||||
for w in lw + 1 ..< uw {
|
||||
words[w] = _Word.allBits
|
||||
unsafe words[w] = _Word.allBits
|
||||
}
|
||||
words[uw].formUnion(_Word(upTo: ub))
|
||||
unsafe words[uw].formUnion(_Word(upTo: ub))
|
||||
}
|
||||
|
||||
internal mutating func clear(in range: Range<Int>) {
|
||||
@@ -151,15 +159,15 @@ extension BitArray._UnsafeHandle {
|
||||
guard range.count > 0 else { return }
|
||||
let (lw, lb) = _BitPosition(range.lowerBound).split
|
||||
let (uw, ub) = _BitPosition(range.upperBound).endSplit
|
||||
let words = _mutableWords
|
||||
let words = unsafe _mutableWords
|
||||
guard lw != uw else {
|
||||
words[lw].subtract(_Word(from: lb, to: ub))
|
||||
unsafe words[lw].subtract(_Word(from: lb, to: ub))
|
||||
return
|
||||
}
|
||||
words[lw].subtract(_Word(upTo: lb).complement())
|
||||
unsafe words[lw].subtract(_Word(upTo: lb).complement())
|
||||
for w in lw + 1 ..< uw {
|
||||
words[w] = _Word.empty
|
||||
unsafe words[w] = _Word.empty
|
||||
}
|
||||
words[uw].subtract(_Word(upTo: ub))
|
||||
unsafe words[uw].subtract(_Word(upTo: ub))
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,7 @@ import InternalCollectionsUtilities
|
||||
/// See `BitSet` for an alternative form of the same underlying data
|
||||
/// structure, treating it as a set of nonnegative integers corresponding to
|
||||
/// `true` bits.
|
||||
@safe
|
||||
public struct BitArray {
|
||||
@usableFromInline
|
||||
internal typealias _BitPosition = _UnsafeBitSet.Index
|
||||
@@ -58,9 +59,9 @@ extension BitArray {
|
||||
_ body: (_UnsafeHandle) throws -> R
|
||||
) rethrows -> R {
|
||||
try _storage.withUnsafeBufferPointer { words in
|
||||
let handle = _UnsafeHandle(
|
||||
let handle = unsafe _UnsafeHandle(
|
||||
words: words, count: _count, mutable: false)
|
||||
return try body(handle)
|
||||
return unsafe try body(handle)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,8 +73,8 @@ extension BitArray {
|
||||
_checkInvariants()
|
||||
}
|
||||
return try _storage.withUnsafeMutableBufferPointer { words in
|
||||
var handle = _UnsafeHandle(words: words, count: _count, mutable: true)
|
||||
return try body(&handle)
|
||||
var handle = unsafe _UnsafeHandle(words: words, count: _count, mutable: true)
|
||||
return unsafe try body(&handle)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -66,9 +66,9 @@ extension BitSet: Sequence {
|
||||
internal init(_ bitset: BitSet) {
|
||||
self.bitset = bitset
|
||||
self.index = 0
|
||||
self.word = bitset._read { handle in
|
||||
self.word = unsafe bitset._read { handle in
|
||||
guard handle.wordCount > 0 else { return .empty }
|
||||
return handle._words[0]
|
||||
return unsafe handle._words[0]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,10 +77,10 @@ extension BitSet: Sequence {
|
||||
self.bitset = _bitset
|
||||
let (word, bit) = start._position.split
|
||||
self.index = word
|
||||
self.word = bitset._read { handle in
|
||||
self.word = unsafe bitset._read { handle in
|
||||
precondition(word <= handle.wordCount, "Invalid index")
|
||||
guard word < handle.wordCount else { return .empty }
|
||||
var w = handle._words[word]
|
||||
var w = unsafe handle._words[word]
|
||||
w.removeAll(upTo: bit)
|
||||
return w
|
||||
}
|
||||
@@ -103,10 +103,10 @@ extension BitSet: Sequence {
|
||||
let i = _UnsafeHandle.Index(word: index, bit: bit)
|
||||
return Int(truncatingIfNeeded: i.value)
|
||||
}
|
||||
return bitset._read { handle in
|
||||
return unsafe bitset._read { handle in
|
||||
while (index + 1) < handle.wordCount {
|
||||
index += 1
|
||||
word = handle._words[index]
|
||||
word = unsafe handle._words[index]
|
||||
if let bit = word.next() {
|
||||
let i = _UnsafeHandle.Index(word: index, bit: bit)
|
||||
return Int(truncatingIfNeeded: i.value)
|
||||
@@ -135,7 +135,7 @@ extension BitSet: Collection, BidirectionalCollection {
|
||||
/// - Note: `BitSet.Counted` is a variant of this type that keeps a running
|
||||
/// total of its element count, for use cases that require an O(1) count.
|
||||
public var count: Int {
|
||||
return _read { $0.count }
|
||||
return unsafe _read { unsafe $0.count }
|
||||
}
|
||||
|
||||
/// The position of the first element in a nonempty set, or `endIndex`
|
||||
@@ -143,7 +143,7 @@ extension BitSet: Collection, BidirectionalCollection {
|
||||
///
|
||||
/// - Complexity: O(*min*) where *min* is the value of the first element.
|
||||
public var startIndex: Index {
|
||||
Index(_position: _read { $0.startIndex })
|
||||
Index(_position: unsafe _read { unsafe $0.startIndex })
|
||||
}
|
||||
|
||||
/// The collection's "past the end" position--that is, the position one step
|
||||
@@ -185,9 +185,9 @@ extension BitSet: Collection, BidirectionalCollection {
|
||||
/// (Each call needs to search for the next `true` bit in the underlying
|
||||
/// storage.)
|
||||
public func index(after index: Index) -> Index {
|
||||
_read { handle in
|
||||
assert(handle._isReachable(index._position), "Invalid index")
|
||||
let pos = handle.index(after: index._position)
|
||||
unsafe _read { handle in
|
||||
assert(unsafe handle._isReachable(index._position), "Invalid index")
|
||||
let pos = unsafe handle.index(after: index._position)
|
||||
return Index(_position: pos)
|
||||
}
|
||||
}
|
||||
@@ -205,9 +205,9 @@ extension BitSet: Collection, BidirectionalCollection {
|
||||
/// (Each call needs to search for the next `true` bit in the underlying
|
||||
/// storage.)
|
||||
public func index(before index: Index) -> Index {
|
||||
_read { handle in
|
||||
assert(handle._isReachable(index._position), "Invalid index")
|
||||
let pos = handle.index(before: index._position)
|
||||
unsafe _read { handle in
|
||||
assert(unsafe handle._isReachable(index._position), "Invalid index")
|
||||
let pos = unsafe handle.index(before: index._position)
|
||||
return Index(_position: pos)
|
||||
}
|
||||
}
|
||||
@@ -223,10 +223,10 @@ extension BitSet: Collection, BidirectionalCollection {
|
||||
/// - Complexity: O(*d*), where *d* is the difference of the values
|
||||
/// 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")
|
||||
return handle.distance(from: start._position, to: end._position)
|
||||
unsafe _read { handle in
|
||||
assert(unsafe handle._isReachable(start._position), "Invalid start index")
|
||||
assert(unsafe handle._isReachable(end._position), "Invalid end index")
|
||||
return unsafe handle.distance(from: start._position, to: end._position)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -247,9 +247,9 @@ extension BitSet: Collection, BidirectionalCollection {
|
||||
/// - Complexity: O(*d*), where *d* is the difference of the values
|
||||
/// 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")
|
||||
let pos = handle.index(index._position, offsetBy: distance)
|
||||
unsafe _read { handle in
|
||||
assert(unsafe handle._isReachable(index._position), "Invalid index")
|
||||
let pos = unsafe handle.index(index._position, offsetBy: distance)
|
||||
return Index(_position: pos)
|
||||
}
|
||||
}
|
||||
@@ -277,10 +277,10 @@ extension BitSet: Collection, BidirectionalCollection {
|
||||
public func index(
|
||||
_ 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")
|
||||
return handle.index(
|
||||
unsafe _read { handle in
|
||||
assert(unsafe handle._isReachable(i._position), "Invalid index")
|
||||
assert(unsafe handle._isReachable(limit._position), "Invalid limit index")
|
||||
return unsafe handle.index(
|
||||
i._position, offsetBy: distance, limitedBy: limit._position
|
||||
).map { Index(_position: $0) }
|
||||
}
|
||||
|
||||
@@ -76,8 +76,8 @@ extension BitSet {
|
||||
} else if member >= _capacity {
|
||||
return
|
||||
}
|
||||
_updateThenShrink { handle, shrink in
|
||||
shrink = handle.update(member, to: newValue)
|
||||
unsafe _updateThenShrink { handle, shrink in
|
||||
shrink = unsafe handle.update(member, to: newValue)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -98,27 +98,27 @@ extension BitSet {
|
||||
///
|
||||
/// - Complexity: Equivalent to two invocations of `index(after:)`.
|
||||
public subscript(members bounds: Range<Int>) -> Slice<BitSet> {
|
||||
let bounds: Range<Index> = _read { handle in
|
||||
let bounds: Range<Index> = unsafe _read { handle in
|
||||
let bounds = bounds._clampedToUInt()
|
||||
var lower = _UnsafeBitSet.Index(bounds.lowerBound)
|
||||
if lower >= handle.endIndex {
|
||||
lower = handle.endIndex
|
||||
} else if !handle.contains(lower.value) {
|
||||
lower = handle.index(after: lower)
|
||||
} else if unsafe !handle.contains(lower.value) {
|
||||
lower = unsafe handle.index(after: lower)
|
||||
}
|
||||
assert(lower == handle.endIndex || handle.contains(lower.value))
|
||||
assert(unsafe lower == handle.endIndex || handle.contains(lower.value))
|
||||
|
||||
var upper = _UnsafeBitSet.Index(bounds.upperBound)
|
||||
if upper <= lower {
|
||||
upper = lower
|
||||
} else if upper >= handle.endIndex {
|
||||
upper = handle.endIndex
|
||||
} else if !handle.contains(upper.value) {
|
||||
upper = handle.index(after: upper)
|
||||
} else if unsafe !handle.contains(upper.value) {
|
||||
upper = unsafe handle.index(after: upper)
|
||||
}
|
||||
assert(upper == handle.endIndex || handle.contains(upper.value))
|
||||
assert(unsafe upper == handle.endIndex || handle.contains(upper.value))
|
||||
assert(lower <= upper)
|
||||
return Range(
|
||||
return unsafe Range(
|
||||
uncheckedBounds: (Index(_position: lower), Index(_position: upper)))
|
||||
}
|
||||
return Slice(base: self, bounds: bounds)
|
||||
@@ -187,10 +187,10 @@ extension BitSet {
|
||||
) rethrows -> Self {
|
||||
var words = [_Word](repeating: .empty, count: _storage.count)
|
||||
try words.withUnsafeMutableBufferPointer { buffer in
|
||||
var target = _UnsafeHandle(words: buffer, mutable: true)
|
||||
var target = unsafe _UnsafeHandle(words: buffer, mutable: true)
|
||||
for i in self {
|
||||
guard try isIncluded(i) else { continue }
|
||||
target.insert(UInt(i))
|
||||
unsafe target.insert(UInt(i))
|
||||
}
|
||||
}
|
||||
return BitSet(_words: words)
|
||||
|
||||
@@ -186,31 +186,31 @@ extension BitSet {
|
||||
includingTail: Bool,
|
||||
using function: (_Word, _Word) -> _Word
|
||||
) {
|
||||
let w1 = handles.0._words
|
||||
let w2 = handles.1._words
|
||||
let w1 = unsafe handles.0._words
|
||||
let w2 = unsafe handles.1._words
|
||||
let capacity = (
|
||||
includingTail
|
||||
? Swift.max(w1.count, w2.count)
|
||||
: Swift.min(w1.count, w2.count))
|
||||
_storage = Array(unsafeUninitializedCapacity: capacity) { buffer, count in
|
||||
_storage = unsafe Array(unsafeUninitializedCapacity: capacity) { buffer, count in
|
||||
let sharedCount = Swift.min(w1.count, w2.count)
|
||||
for w in 0 ..< sharedCount {
|
||||
buffer.initializeElement(at: w, to: function(w1[w], w2[w]))
|
||||
unsafe buffer.initializeElement(at: w, to: function(w1[w], w2[w]))
|
||||
}
|
||||
if includingTail {
|
||||
if w1.count < w2.count {
|
||||
for w in w1.count ..< w2.count {
|
||||
buffer.initializeElement(at: w, to: function(_Word.empty, w2[w]))
|
||||
unsafe buffer.initializeElement(at: w, to: function(_Word.empty, w2[w]))
|
||||
}
|
||||
} else {
|
||||
for w in w2.count ..< w1.count {
|
||||
buffer.initializeElement(at: w, to: function(w1[w], _Word.empty))
|
||||
unsafe buffer.initializeElement(at: w, to: function(w1[w], _Word.empty))
|
||||
}
|
||||
}
|
||||
}
|
||||
// Adjust the word count based on results.
|
||||
count = capacity
|
||||
while count > 0, buffer[count - 1].isEmpty {
|
||||
while count > 0, unsafe buffer[count - 1].isEmpty {
|
||||
count -= 1
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ extension BitSet {
|
||||
/// - Complexity: O(1)
|
||||
@usableFromInline
|
||||
internal func _contains(_ member: UInt) -> Bool {
|
||||
_read { $0.contains(member) }
|
||||
unsafe _read { unsafe $0.contains(member) }
|
||||
}
|
||||
|
||||
/// Returns a Boolean value that indicates whether the given element exists
|
||||
@@ -64,7 +64,7 @@ extension BitSet {
|
||||
@usableFromInline
|
||||
internal mutating func _insert(_ newMember: UInt) -> Bool {
|
||||
_ensureCapacity(forValue: newMember)
|
||||
return _update { $0.insert(newMember) }
|
||||
return unsafe _update { unsafe $0.insert(newMember) }
|
||||
}
|
||||
|
||||
/// Inserts the given element in the set if it is not already present.
|
||||
@@ -114,8 +114,8 @@ extension BitSet {
|
||||
@discardableResult
|
||||
@usableFromInline
|
||||
internal mutating func _remove(_ member: UInt) -> Bool {
|
||||
_updateThenShrink { handle, shrink in
|
||||
shrink = handle.remove(member)
|
||||
unsafe _updateThenShrink { handle, shrink in
|
||||
shrink = unsafe handle.remove(member)
|
||||
return shrink
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,12 +27,12 @@ extension BitSet {
|
||||
///
|
||||
/// - Complexity: O(*max*), where *max* is the largest item in either set.
|
||||
public mutating func formIntersection(_ other: BitSet) {
|
||||
other._read { source in
|
||||
unsafe other._read { source in
|
||||
if source.wordCount < _storage.count {
|
||||
self._storage.removeLast(_storage.count - source.wordCount)
|
||||
}
|
||||
_updateThenShrink { target, shrink in
|
||||
target.combineSharedPrefix(
|
||||
unsafe _updateThenShrink { target, shrink in
|
||||
unsafe target.combineSharedPrefix(
|
||||
with: source, using: { $0.formIntersection($1) })
|
||||
}
|
||||
}
|
||||
@@ -71,8 +71,8 @@ extension BitSet {
|
||||
if _storage.count - lastWord - 1 > 0 {
|
||||
_storage.removeLast(_storage.count - lastWord - 1)
|
||||
}
|
||||
_updateThenShrink { handle, shrink in
|
||||
handle.formIntersection(other)
|
||||
unsafe _updateThenShrink { handle, shrink in
|
||||
unsafe handle.formIntersection(other)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -29,9 +29,9 @@ extension BitSet {
|
||||
/// - Complexity: O(*max*), where *max* is the largest item in either set.
|
||||
public mutating func formSymmetricDifference(_ other: BitSet) {
|
||||
_ensureCapacity(limit: other._capacity)
|
||||
_updateThenShrink { target, shrink in
|
||||
other._read { source in
|
||||
target.combineSharedPrefix(
|
||||
unsafe _updateThenShrink { target, shrink in
|
||||
unsafe other._read { source in
|
||||
unsafe target.combineSharedPrefix(
|
||||
with: source, using: { $0.formSymmetricDifference($1) })
|
||||
}
|
||||
}
|
||||
@@ -68,8 +68,8 @@ extension BitSet {
|
||||
}
|
||||
guard !other.isEmpty else { return }
|
||||
_ensureCapacity(limit: other.upperBound)
|
||||
_updateThenShrink { handle, shrink in
|
||||
handle.formSymmetricDifference(other)
|
||||
unsafe _updateThenShrink { handle, shrink in
|
||||
unsafe handle.formSymmetricDifference(other)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -28,9 +28,9 @@ extension BitSet {
|
||||
/// - Complexity: O(*max*), where *max* is the largest item in either input.
|
||||
public mutating func formUnion(_ other: BitSet) {
|
||||
_ensureCapacity(limit: other._capacity)
|
||||
_update { target in
|
||||
other._read { source in
|
||||
target.combineSharedPrefix(with: source) { $0.formUnion($1) }
|
||||
unsafe _update { target in
|
||||
unsafe other._read { source in
|
||||
unsafe target.combineSharedPrefix(with: source) { $0.formUnion($1) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -64,8 +64,8 @@ extension BitSet {
|
||||
}
|
||||
guard !other.isEmpty else { return }
|
||||
_ensureCapacity(limit: other.upperBound)
|
||||
_update { handle in
|
||||
handle.formUnion(other)
|
||||
unsafe _update { handle in
|
||||
unsafe handle.formUnion(other)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -28,9 +28,9 @@ extension BitSet {
|
||||
///
|
||||
/// - Complexity: O(*max*), where *max* is the largest item in either set.
|
||||
public func intersection(_ other: BitSet) -> BitSet {
|
||||
self._read { first in
|
||||
other._read { second in
|
||||
Self(
|
||||
unsafe self._read { first in
|
||||
unsafe other._read { second in
|
||||
unsafe Self(
|
||||
_combining: (first, second),
|
||||
includingTail: false,
|
||||
using: { $0.intersection($1) })
|
||||
|
||||
@@ -30,12 +30,12 @@ extension BitSet {
|
||||
///
|
||||
/// - Complexity: O(*max*), where *max* is the largest item in either input.
|
||||
public func isDisjoint(with other: BitSet) -> Bool {
|
||||
self._read { first in
|
||||
other._read { second in
|
||||
let w1 = first._words
|
||||
let w2 = second._words
|
||||
unsafe self._read { first in
|
||||
unsafe other._read { second in
|
||||
let w1 = unsafe first._words
|
||||
let w2 = unsafe second._words
|
||||
for i in 0 ..< Swift.min(w1.count, w2.count) {
|
||||
if !w1[i].intersection(w2[i]).isEmpty { return false }
|
||||
if unsafe !w1[i].intersection(w2[i]).isEmpty { return false }
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -72,7 +72,7 @@ extension BitSet {
|
||||
///
|
||||
/// - Complexity: O(*max*), where *max* is the largest item in `self`.
|
||||
public func isDisjoint(with other: Range<Int>) -> Bool {
|
||||
_read { $0.isDisjoint(with: other._clampedToUInt()) }
|
||||
unsafe _read { unsafe $0.isDisjoint(with: other._clampedToUInt()) }
|
||||
}
|
||||
|
||||
/// Returns a Boolean value that indicates whether the set has no members in
|
||||
|
||||
@@ -43,7 +43,7 @@ extension BitSet {
|
||||
public func isEqualSet(to other: Range<Int>) -> Bool {
|
||||
if other.isEmpty { return isEmpty }
|
||||
guard let other = other._toUInt() else { return false }
|
||||
return _read { $0.isEqualSet(to: other) }
|
||||
return unsafe _read { unsafe $0.isEqualSet(to: other) }
|
||||
}
|
||||
|
||||
/// Returns a Boolean value indicating whether this bit set contains the same
|
||||
|
||||
@@ -37,19 +37,19 @@ extension BitSet {
|
||||
///
|
||||
/// - Complexity: O(*max*), where *max* is the largest item in `self`.
|
||||
public func isStrictSubset(of other: BitSet) -> Bool {
|
||||
self._read { first in
|
||||
other._read { second in
|
||||
let w1 = first._words
|
||||
let w2 = second._words
|
||||
unsafe self._read { first in
|
||||
unsafe other._read { second in
|
||||
let w1 = unsafe first._words
|
||||
let w2 = unsafe second._words
|
||||
if w1.count > w2.count {
|
||||
return false
|
||||
}
|
||||
var strict = w1.count < w2.count
|
||||
for i in 0 ..< w1.count {
|
||||
if !w1[i].subtracting(w2[i]).isEmpty {
|
||||
if unsafe !w1[i].subtracting(w2[i]).isEmpty {
|
||||
return false
|
||||
}
|
||||
strict = strict || w1[i] != w2[i]
|
||||
strict = unsafe strict || w1[i] != w2[i]
|
||||
}
|
||||
return strict
|
||||
}
|
||||
@@ -133,7 +133,7 @@ extension BitSet {
|
||||
}
|
||||
|
||||
let selfCount = self.count
|
||||
return _UnsafeHandle.withTemporaryBitSet(
|
||||
return unsafe _UnsafeHandle.withTemporaryBitSet(
|
||||
wordCount: _storage.count
|
||||
) { seen in
|
||||
var strict = false
|
||||
@@ -144,7 +144,7 @@ extension BitSet {
|
||||
strict = true
|
||||
continue
|
||||
}
|
||||
if seen.insert(UInt(i)) {
|
||||
if unsafe seen.insert(UInt(i)) {
|
||||
c &+= 1
|
||||
if c == selfCount {
|
||||
while !strict, let i = it.next() {
|
||||
|
||||
@@ -82,7 +82,7 @@ extension BitSet {
|
||||
return false
|
||||
}
|
||||
guard let r = other._toUInt() else { return false }
|
||||
return _read { $0.isSuperset(of: r) }
|
||||
return unsafe _read { unsafe $0.isSuperset(of: r) }
|
||||
}
|
||||
|
||||
/// Returns a Boolean value that indicates whether this set is a strict
|
||||
@@ -118,14 +118,14 @@ extension BitSet {
|
||||
if let other = _specialize(other, for: Range<Int>.self) {
|
||||
return isStrictSuperset(of: other)
|
||||
}
|
||||
return _UnsafeHandle.withTemporaryBitSet(
|
||||
return unsafe _UnsafeHandle.withTemporaryBitSet(
|
||||
wordCount: _storage.count
|
||||
) { seen in
|
||||
for i in other {
|
||||
guard contains(i) else { return false }
|
||||
seen.insert(UInt(i))
|
||||
unsafe seen.insert(UInt(i))
|
||||
}
|
||||
return !_storage.elementsEqual(seen._words)
|
||||
return unsafe !_storage.elementsEqual(seen._words)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -35,15 +35,15 @@ extension BitSet {
|
||||
///
|
||||
/// - Complexity: O(*max*), where *max* is the largest item in `self`.
|
||||
public func isSubset(of other: BitSet) -> Bool {
|
||||
self._read { first in
|
||||
other._read { second in
|
||||
let w1 = first._words
|
||||
let w2 = second._words
|
||||
unsafe self._read { first in
|
||||
unsafe other._read { second in
|
||||
let w1 = unsafe first._words
|
||||
let w2 = unsafe second._words
|
||||
if w1.count > w2.count {
|
||||
return false
|
||||
}
|
||||
for i in 0 ..< w1.count {
|
||||
if !w1[i].subtracting(w2[i]).isEmpty {
|
||||
if unsafe !w1[i].subtracting(w2[i]).isEmpty {
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -84,7 +84,7 @@ extension BitSet {
|
||||
///
|
||||
/// - Complexity: O(*max*), where *max* is the largest item in `self`.
|
||||
public func isSubset(of other: Range<Int>) -> Bool {
|
||||
_read { $0.isSubset(of: other._clampedToUInt()) }
|
||||
unsafe _read { unsafe $0.isSubset(of: other._clampedToUInt()) }
|
||||
}
|
||||
|
||||
/// Returns a Boolean value that indicates whether this set is a subset of
|
||||
|
||||
@@ -71,7 +71,7 @@ extension BitSet {
|
||||
public func isSuperset(of other: Range<Int>) -> Bool {
|
||||
if other.isEmpty { return true }
|
||||
guard let r = other._toUInt() else { return false }
|
||||
return _read { $0.isSuperset(of: r) }
|
||||
return unsafe _read { unsafe $0.isSuperset(of: r) }
|
||||
}
|
||||
|
||||
/// Returns a Boolean value that indicates whether this set is a superset of
|
||||
|
||||
@@ -27,9 +27,9 @@ extension BitSet {
|
||||
///
|
||||
/// - Complexity: O(*max*), where *max* is the largest item in either input.
|
||||
public mutating func subtract(_ other: BitSet) {
|
||||
_updateThenShrink { target, shrink in
|
||||
other._read { source in
|
||||
target.combineSharedPrefix(
|
||||
unsafe _updateThenShrink { target, shrink in
|
||||
unsafe other._read { source in
|
||||
unsafe target.combineSharedPrefix(
|
||||
with: source,
|
||||
using: { $0.subtract($1) }
|
||||
)
|
||||
@@ -67,8 +67,8 @@ extension BitSet {
|
||||
@usableFromInline
|
||||
internal mutating func _subtract(_ other: Range<UInt>) {
|
||||
guard !other.isEmpty else { return }
|
||||
_updateThenShrink { handle, shrink in
|
||||
handle.subtract(other)
|
||||
unsafe _updateThenShrink { handle, shrink in
|
||||
unsafe handle.subtract(other)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,9 +110,9 @@ extension BitSet {
|
||||
|
||||
@usableFromInline
|
||||
internal mutating func _subtract(_ next: () -> UInt?) {
|
||||
_updateThenShrink { handle, shrink in
|
||||
unsafe _updateThenShrink { handle, shrink in
|
||||
while let value = next() {
|
||||
handle.remove(value)
|
||||
unsafe handle.remove(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,9 +29,9 @@ extension BitSet {
|
||||
///
|
||||
/// - Complexity: O(*max*), where *max* is the largest item in either input.
|
||||
public func subtracting(_ other: BitSet) -> BitSet {
|
||||
self._read { first in
|
||||
other._read { second in
|
||||
Self(
|
||||
unsafe self._read { first in
|
||||
unsafe other._read { second in
|
||||
unsafe Self(
|
||||
_combining: (first, second),
|
||||
includingTail: true,
|
||||
using: { $0.subtracting($1) })
|
||||
|
||||
@@ -29,9 +29,9 @@ extension BitSet {
|
||||
///
|
||||
/// - Complexity: O(*max*), where *max* is the largest item in either set.
|
||||
public func symmetricDifference(_ other: BitSet) -> BitSet {
|
||||
self._read { first in
|
||||
other._read { second in
|
||||
Self(
|
||||
unsafe self._read { first in
|
||||
unsafe other._read { second in
|
||||
unsafe Self(
|
||||
_combining: (first, second),
|
||||
includingTail: true,
|
||||
using: { $0.symmetricDifference($1) })
|
||||
|
||||
@@ -26,9 +26,9 @@ extension BitSet {
|
||||
///
|
||||
/// - Complexity: O(*max*), where *max* is the largest item in either input.
|
||||
public func union(_ other: BitSet) -> BitSet {
|
||||
self._read { first in
|
||||
other._read { second in
|
||||
Self(
|
||||
unsafe self._read { first in
|
||||
unsafe other._read { second in
|
||||
unsafe Self(
|
||||
_combining: (first, second),
|
||||
includingTail: true,
|
||||
using: { $0.union($1) })
|
||||
|
||||
@@ -23,14 +23,14 @@ extension BitSet {
|
||||
extension _UnsafeBitSet {
|
||||
@inline(__always)
|
||||
internal func _isReachable(_ index: Index) -> Bool {
|
||||
index == endIndex || contains(index.value)
|
||||
unsafe index == endIndex || contains(index.value)
|
||||
}
|
||||
}
|
||||
|
||||
extension _UnsafeBitSet {
|
||||
internal func _emptySuffix() -> Int {
|
||||
var i = wordCount - 1
|
||||
while i >= 0, _words[i].isEmpty {
|
||||
while i >= 0, unsafe _words[i].isEmpty {
|
||||
i -= 1
|
||||
}
|
||||
return wordCount - 1 - i
|
||||
@@ -46,7 +46,7 @@ extension _UnsafeBitSet {
|
||||
ensureMutable()
|
||||
let c = Swift.min(self.wordCount, other.wordCount)
|
||||
for w in 0 ..< c {
|
||||
function(&self._mutableWords[w], other._words[w])
|
||||
unsafe function(&self._mutableWords[w], other._words[w])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -62,15 +62,15 @@ extension _UnsafeBitSet {
|
||||
if l.word == u.word {
|
||||
guard l.word < wordCount else { return }
|
||||
let w = _Word(from: l.bit, to: u.bit)
|
||||
_mutableWords[l.word].formUnion(w)
|
||||
unsafe _mutableWords[l.word].formUnion(w)
|
||||
return
|
||||
}
|
||||
_mutableWords[l.word].formUnion(_Word(upTo: l.bit).complement())
|
||||
unsafe _mutableWords[l.word].formUnion(_Word(upTo: l.bit).complement())
|
||||
for w in l.word + 1 ..< u.word {
|
||||
_mutableWords[w] = .allBits
|
||||
unsafe _mutableWords[w] = .allBits
|
||||
}
|
||||
if u.word < wordCount {
|
||||
_mutableWords[u.word].formUnion(_Word(upTo: u.bit))
|
||||
unsafe _mutableWords[u.word].formUnion(_Word(upTo: u.bit))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,21 +81,21 @@ extension _UnsafeBitSet {
|
||||
let u = Index(Swift.min(range.upperBound, capacity))
|
||||
|
||||
for w in 0 ..< l.word {
|
||||
_mutableWords[w] = .empty
|
||||
unsafe _mutableWords[w] = .empty
|
||||
}
|
||||
|
||||
if l.word == u.word {
|
||||
guard l.word < wordCount else { return }
|
||||
|
||||
let w = _Word(from: l.bit, to: u.bit)
|
||||
_mutableWords[l.word].formIntersection(w)
|
||||
unsafe _mutableWords[l.word].formIntersection(w)
|
||||
return
|
||||
}
|
||||
|
||||
_mutableWords[l.word].formIntersection(_Word(upTo: l.bit).complement())
|
||||
unsafe _mutableWords[l.word].formIntersection(_Word(upTo: l.bit).complement())
|
||||
if u.word < wordCount {
|
||||
_mutableWords[u.word].formIntersection(_Word(upTo: u.bit))
|
||||
_mutableWords[(u.word + 1)...].update(repeating: .empty)
|
||||
unsafe _mutableWords[u.word].formIntersection(_Word(upTo: u.bit))
|
||||
unsafe _mutableWords[(u.word + 1)...].update(repeating: .empty)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -109,16 +109,16 @@ extension _UnsafeBitSet {
|
||||
if l.word == u.word {
|
||||
guard l.word < wordCount else { return }
|
||||
let w = _Word(from: l.bit, to: u.bit)
|
||||
_mutableWords[l.word].formSymmetricDifference(w)
|
||||
unsafe _mutableWords[l.word].formSymmetricDifference(w)
|
||||
return
|
||||
}
|
||||
_mutableWords[l.word]
|
||||
unsafe _mutableWords[l.word]
|
||||
.formSymmetricDifference(_Word(upTo: l.bit).complement())
|
||||
for w in l.word + 1 ..< u.word {
|
||||
_mutableWords[w].formComplement()
|
||||
unsafe _mutableWords[w].formComplement()
|
||||
}
|
||||
if u.word < wordCount {
|
||||
_mutableWords[u.word].formSymmetricDifference(_Word(upTo: u.bit))
|
||||
unsafe _mutableWords[u.word].formSymmetricDifference(_Word(upTo: u.bit))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -131,20 +131,20 @@ extension _UnsafeBitSet {
|
||||
if l.word == u.word {
|
||||
guard l.word < wordCount else { return }
|
||||
let w = _Word(from: l.bit, to: u.bit)
|
||||
_mutableWords[l.word].subtract(w)
|
||||
unsafe _mutableWords[l.word].subtract(w)
|
||||
return
|
||||
}
|
||||
|
||||
_mutableWords[l.word].subtract(_Word(upTo: l.bit).complement())
|
||||
_mutableWords[(l.word + 1) ..< u.word].update(repeating: .empty)
|
||||
unsafe _mutableWords[l.word].subtract(_Word(upTo: l.bit).complement())
|
||||
unsafe _mutableWords[(l.word + 1) ..< u.word].update(repeating: .empty)
|
||||
if u.word < wordCount {
|
||||
_mutableWords[u.word].subtract(_Word(upTo: u.bit))
|
||||
unsafe _mutableWords[u.word].subtract(_Word(upTo: u.bit))
|
||||
}
|
||||
}
|
||||
|
||||
@_effects(releasenone)
|
||||
internal func isDisjoint(with range: Range<UInt>) -> Bool {
|
||||
if self.isEmpty { return true }
|
||||
if unsafe self.isEmpty { return true }
|
||||
let lower = Index(Swift.min(range.lowerBound, capacity))
|
||||
let upper = Index(Swift.min(range.upperBound, capacity))
|
||||
if lower == upper { return true }
|
||||
@@ -152,47 +152,47 @@ extension _UnsafeBitSet {
|
||||
if lower.word == upper.word {
|
||||
guard lower.word < wordCount else { return true }
|
||||
let w = _Word(from: lower.bit, to: upper.bit)
|
||||
return _words[lower.word].intersection(w).isEmpty
|
||||
return unsafe _words[lower.word].intersection(w).isEmpty
|
||||
}
|
||||
|
||||
let lw = _Word(upTo: lower.bit).complement()
|
||||
guard _words[lower.word].intersection(lw).isEmpty else { return false }
|
||||
guard unsafe _words[lower.word].intersection(lw).isEmpty else { return false }
|
||||
|
||||
for i in lower.word + 1 ..< upper.word {
|
||||
guard _words[i].isEmpty else { return false }
|
||||
guard unsafe _words[i].isEmpty else { return false }
|
||||
}
|
||||
if upper.word < wordCount {
|
||||
let uw = _Word(upTo: upper.bit)
|
||||
guard _words[upper.word].intersection(uw).isEmpty else { return false }
|
||||
guard unsafe _words[upper.word].intersection(uw).isEmpty else { return false }
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
@_effects(releasenone)
|
||||
internal func isSubset(of range: Range<UInt>) -> Bool {
|
||||
guard !range.isEmpty else { return isEmpty }
|
||||
guard !_words.isEmpty else { return true }
|
||||
guard !range.isEmpty else { return unsafe isEmpty }
|
||||
guard unsafe !_words.isEmpty else { return true }
|
||||
let r = range.clamped(to: 0 ..< UInt(capacity))
|
||||
|
||||
let lower = Index(r.lowerBound)
|
||||
let upper = Index(r.upperBound)
|
||||
|
||||
for w in 0 ..< lower.word {
|
||||
guard _words[w].isEmpty else { return false }
|
||||
guard unsafe _words[w].isEmpty else { return false }
|
||||
}
|
||||
|
||||
guard lower.word < wordCount else { return true }
|
||||
|
||||
let lw = _Word(upTo: lower.bit)
|
||||
guard _words[lower.word].intersection(lw).isEmpty else { return false }
|
||||
guard unsafe _words[lower.word].intersection(lw).isEmpty else { return false }
|
||||
|
||||
guard upper.word < wordCount else { return true }
|
||||
|
||||
let hw = _Word(upTo: upper.bit).complement()
|
||||
guard _words[upper.word].intersection(hw).isEmpty else { return false }
|
||||
guard unsafe _words[upper.word].intersection(hw).isEmpty else { return false }
|
||||
|
||||
for w in upper.word + 1 ..< wordCount {
|
||||
guard _words[w].isEmpty else { return false }
|
||||
guard unsafe _words[w].isEmpty else { return false }
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -208,23 +208,23 @@ extension _UnsafeBitSet {
|
||||
|
||||
if lower.word == upper.word {
|
||||
let w = _Word(from: lower.bit, to: upper.bit)
|
||||
return _words[lower.word].intersection(w) == w
|
||||
return unsafe _words[lower.word].intersection(w) == w
|
||||
}
|
||||
let lw = _Word(upTo: lower.bit).complement()
|
||||
guard _words[lower.word].intersection(lw) == lw else { return false }
|
||||
guard unsafe _words[lower.word].intersection(lw) == lw else { return false }
|
||||
|
||||
for w in lower.word + 1 ..< upper.word {
|
||||
guard _words[w].isFull else { return false }
|
||||
guard unsafe _words[w].isFull else { return false }
|
||||
}
|
||||
|
||||
guard upper.word < wordCount else { return true }
|
||||
let uw = _Word(upTo: upper.bit)
|
||||
return _words[upper.word].intersection(uw) == uw
|
||||
return unsafe _words[upper.word].intersection(uw) == uw
|
||||
}
|
||||
|
||||
@_effects(releasenone)
|
||||
internal func isEqualSet(to range: Range<UInt>) -> Bool {
|
||||
if range.isEmpty { return self.isEmpty }
|
||||
if range.isEmpty { return unsafe self.isEmpty }
|
||||
let r = range.clamped(to: 0 ..< UInt(capacity))
|
||||
guard r == range else { return false }
|
||||
|
||||
@@ -234,22 +234,22 @@ extension _UnsafeBitSet {
|
||||
guard upper.word == wordCount &- 1 else { return false }
|
||||
|
||||
for w in 0 ..< lower.word {
|
||||
guard _words[w].isEmpty else { return false }
|
||||
guard unsafe _words[w].isEmpty else { return false }
|
||||
}
|
||||
|
||||
if lower.word == upper.word {
|
||||
let w = _Word(from: lower.bit, to: upper.bit)
|
||||
return _words[lower.word] == w
|
||||
return unsafe _words[lower.word] == w
|
||||
}
|
||||
let lw = _Word(upTo: lower.bit).complement()
|
||||
guard _words[lower.word] == lw else { return false }
|
||||
guard unsafe _words[lower.word] == lw else { return false }
|
||||
|
||||
for w in lower.word + 1 ..< upper.word {
|
||||
guard _words[w].isFull else { return false }
|
||||
guard unsafe _words[w].isFull else { return false }
|
||||
}
|
||||
|
||||
let uw = _Word(upTo: upper.bit)
|
||||
return _words[upper.word] == uw
|
||||
return unsafe _words[upper.word] == uw
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ import InternalCollectionsUtilities
|
||||
/// See `BitArray` for an alternative form of the same underlying data
|
||||
/// structure, treating it as a mutable random-access collection of `Bool`
|
||||
/// values.
|
||||
@safe
|
||||
public struct BitSet {
|
||||
@usableFromInline
|
||||
internal var _storage: [_Word]
|
||||
@@ -43,8 +44,8 @@ extension BitSet {
|
||||
_ body: (_UnsafeHandle) throws -> R
|
||||
) rethrows -> R {
|
||||
try _storage.withUnsafeBufferPointer { words in
|
||||
let handle = _UnsafeHandle(words: words, mutable: false)
|
||||
return try body(handle)
|
||||
let handle = unsafe _UnsafeHandle(words: words, mutable: false)
|
||||
return unsafe try body(handle)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,7 +70,7 @@ extension BitSet {
|
||||
}
|
||||
|
||||
internal mutating func _shrink() {
|
||||
let suffix = _read { $0._emptySuffix() }
|
||||
let suffix = unsafe _read { unsafe $0._emptySuffix() }
|
||||
if suffix > 0 { _storage.removeLast(suffix) }
|
||||
}
|
||||
|
||||
@@ -81,8 +82,8 @@ extension BitSet {
|
||||
_checkInvariants()
|
||||
}
|
||||
return try _storage.withUnsafeMutableBufferPointer { words in
|
||||
var handle = _UnsafeHandle(words: words, mutable: true)
|
||||
return try body(&handle)
|
||||
var handle = unsafe _UnsafeHandle(words: words, mutable: true)
|
||||
return unsafe try body(&handle)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,8 +97,8 @@ extension BitSet {
|
||||
_checkInvariants()
|
||||
}
|
||||
return try _storage.withUnsafeMutableBufferPointer { words in
|
||||
var handle = _UnsafeHandle(words: words, mutable: true)
|
||||
return try body(&handle, &shrink)
|
||||
var handle = unsafe _UnsafeHandle(words: words, mutable: true)
|
||||
return unsafe try body(&handle, &shrink)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,14 +15,14 @@ extension Range where Bound: FixedWidthInteger {
|
||||
@inlinable
|
||||
internal func _clampedToUInt() -> Range<UInt> {
|
||||
if upperBound <= 0 {
|
||||
return Range<UInt>(uncheckedBounds: (0, 0))
|
||||
return unsafe Range<UInt>(uncheckedBounds: (0, 0))
|
||||
}
|
||||
if lowerBound >= UInt.max {
|
||||
return Range<UInt>(uncheckedBounds: (UInt.max, UInt.max))
|
||||
return unsafe Range<UInt>(uncheckedBounds: (UInt.max, UInt.max))
|
||||
}
|
||||
let lower = lowerBound < 0 ? 0 : UInt(lowerBound)
|
||||
let upper = upperBound > UInt.max ? UInt.max : UInt(upperBound)
|
||||
return Range<UInt>(uncheckedBounds: (lower, upper))
|
||||
return unsafe Range<UInt>(uncheckedBounds: (lower, upper))
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@@ -33,6 +33,6 @@ extension Range where Bound: FixedWidthInteger {
|
||||
else {
|
||||
return nil
|
||||
}
|
||||
return Range<UInt>(uncheckedBounds: (lower: lower, upper: upper))
|
||||
return unsafe Range<UInt>(uncheckedBounds: (lower: lower, upper: upper))
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,6 @@
|
||||
|
||||
extension Slice {
|
||||
internal var _bounds: Range<Index> {
|
||||
Range(uncheckedBounds: (startIndex, endIndex))
|
||||
unsafe Range(uncheckedBounds: (startIndex, endIndex))
|
||||
}
|
||||
}
|
||||
Loaded 100 of 405 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user