Merge branch 'release/1.1' to ‘main’

This commit is contained in:
Karoy Lorentey committed 2022-10-28 18:21:18 -07:00
commit a32048d44e
142 files changed
+8380 -1733

No files matched your search

+1
View File
@@ -7,3 +7,4 @@ xcuserdata/
.*.sw?
/Benchmarks/.swiftpm
/Benchmarks/.build
.docc-build
@@ -1,6 +1,6 @@
{
"kind": "group",
"title": "PersistentCollections Benchmarks",
"title": "PersistentDictionary Benchmarks",
"directory": "Results",
"contents": [
{
@@ -41,11 +41,6 @@
}
]
},
{
"kind": "group",
"title": "HashSet Operations",
"contents": []
},
{
"kind": "group",
"title": "Comparisons against reference implementations",
+748
View File
@@ -0,0 +1,748 @@
{
"kind": "group",
"title": "PersistentSet Benchmarks",
"directory": "Results",
"contents": [
{
"kind": "chart",
"title": "operations",
"tasks": [
"PersistentSet<Int> init from range",
"PersistentSet<Int> init from unsafe buffer",
"PersistentSet<Int> sequential iteration",
"PersistentSet<Int> successful contains",
"PersistentSet<Int> unsuccessful contains",
"PersistentSet<Int> insert",
"PersistentSet<Int> remove"
]
},
{
"kind": "chart",
"title": "initializers",
"tasks": [
"PersistentSet<Int> init from range",
"PersistentSet<Int> init from unsafe buffer",
]
},
{
"kind": "variants",
"charts": [
{
"kind": "chart",
"title": "union with Self",
"tasks": [
"PersistentSet<Int> union with Self (0% overlap)",
"PersistentSet<Int> union with Self (25% overlap)",
"PersistentSet<Int> union with Self (50% overlap)",
"PersistentSet<Int> union with Self (75% overlap)",
"PersistentSet<Int> union with Self (100% overlap)",
]
},
{
"kind": "chart",
"title": "union with Array",
"tasks": [
"PersistentSet<Int> union with Array (0% overlap)",
"PersistentSet<Int> union with Array (25% overlap)",
"PersistentSet<Int> union with Array (50% overlap)",
"PersistentSet<Int> union with Array (75% overlap)",
"PersistentSet<Int> union with Array (100% overlap)",
]
},
{
"kind": "chart",
"title": "formUnion with Self",
"tasks": [
"PersistentSet<Int> formUnion with Self (0% overlap)",
"PersistentSet<Int> formUnion with Self (25% overlap)",
"PersistentSet<Int> formUnion with Self (50% overlap)",
"PersistentSet<Int> formUnion with Self (75% overlap)",
"PersistentSet<Int> formUnion with Self (100% overlap)",
]
},
{
"kind": "chart",
"title": "formUnion with Array",
"tasks": [
"PersistentSet<Int> formUnion with Array (0% overlap)",
"PersistentSet<Int> formUnion with Array (25% overlap)",
"PersistentSet<Int> formUnion with Array (50% overlap)",
"PersistentSet<Int> formUnion with Array (75% overlap)",
"PersistentSet<Int> formUnion with Array (100% overlap)",
]
},
]
},
{
"kind": "variants",
"charts": [
{
"kind": "chart",
"title": "intersection with Self",
"tasks": [
"PersistentSet<Int> intersection with Self (0% overlap)",
"PersistentSet<Int> intersection with Self (25% overlap)",
"PersistentSet<Int> intersection with Self (50% overlap)",
"PersistentSet<Int> intersection with Self (75% overlap)",
"PersistentSet<Int> intersection with Self (100% overlap)",
]
},
{
"kind": "chart",
"title": "intersection with Array",
"tasks": [
"PersistentSet<Int> intersection with Array (0% overlap)",
"PersistentSet<Int> intersection with Array (25% overlap)",
"PersistentSet<Int> intersection with Array (50% overlap)",
"PersistentSet<Int> intersection with Array (75% overlap)",
"PersistentSet<Int> intersection with Array (100% overlap)",
]
},
{
"kind": "chart",
"title": "formIntersection with Self",
"tasks": [
"PersistentSet<Int> formIntersection with Self (0% overlap)",
"PersistentSet<Int> formIntersection with Self (25% overlap)",
"PersistentSet<Int> formIntersection with Self (50% overlap)",
"PersistentSet<Int> formIntersection with Self (75% overlap)",
"PersistentSet<Int> formIntersection with Self (100% overlap)",
]
},
{
"kind": "chart",
"title": "formIntersection with Array",
"tasks": [
"PersistentSet<Int> formIntersection with Array (0% overlap)",
"PersistentSet<Int> formIntersection with Array (25% overlap)",
"PersistentSet<Int> formIntersection with Array (50% overlap)",
"PersistentSet<Int> formIntersection with Array (75% overlap)",
"PersistentSet<Int> formIntersection with Array (100% overlap)",
]
},
]
},
{
"kind": "variants",
"charts": [
{
"kind": "chart",
"title": "symmetricDifference with Self",
"tasks": [
"PersistentSet<Int> symmetricDifference with Self (0% overlap)",
"PersistentSet<Int> symmetricDifference with Self (25% overlap)",
"PersistentSet<Int> symmetricDifference with Self (50% overlap)",
"PersistentSet<Int> symmetricDifference with Self (75% overlap)",
"PersistentSet<Int> symmetricDifference with Self (100% overlap)",
]
},
{
"kind": "chart",
"title": "symmetricDifference with Array",
"tasks": [
"PersistentSet<Int> symmetricDifference with Array (0% overlap)",
"PersistentSet<Int> symmetricDifference with Array (25% overlap)",
"PersistentSet<Int> symmetricDifference with Array (50% overlap)",
"PersistentSet<Int> symmetricDifference with Array (75% overlap)",
"PersistentSet<Int> symmetricDifference with Array (100% overlap)",
]
},
{
"kind": "chart",
"title": "formSymmetricDifference with Self",
"tasks": [
"PersistentSet<Int> formSymmetricDifference with Self (0% overlap)",
"PersistentSet<Int> formSymmetricDifference with Self (25% overlap)",
"PersistentSet<Int> formSymmetricDifference with Self (50% overlap)",
"PersistentSet<Int> formSymmetricDifference with Self (75% overlap)",
"PersistentSet<Int> formSymmetricDifference with Self (100% overlap)",
]
},
{
"kind": "chart",
"title": "formSymmetricDifference with Array",
"tasks": [
"PersistentSet<Int> formSymmetricDifference with Array (0% overlap)",
"PersistentSet<Int> formSymmetricDifference with Array (25% overlap)",
"PersistentSet<Int> formSymmetricDifference with Array (50% overlap)",
"PersistentSet<Int> formSymmetricDifference with Array (75% overlap)",
"PersistentSet<Int> formSymmetricDifference with Array (100% overlap)",
]
},
]
},
{
"kind": "variants",
"charts": [
{
"kind": "chart",
"title": "subtracting Self",
"tasks": [
"PersistentSet<Int> subtracting Self (0% overlap)",
"PersistentSet<Int> subtracting Self (25% overlap)",
"PersistentSet<Int> subtracting Self (50% overlap)",
"PersistentSet<Int> subtracting Self (75% overlap)",
"PersistentSet<Int> subtracting Self (100% overlap)",
]
},
{
"kind": "chart",
"title": "subtracting Array",
"tasks": [
"PersistentSet<Int> subtracting Array (0% overlap)",
"PersistentSet<Int> subtracting Array (25% overlap)",
"PersistentSet<Int> subtracting Array (50% overlap)",
"PersistentSet<Int> subtracting Array (75% overlap)",
"PersistentSet<Int> subtracting Array (100% overlap)",
]
},
{
"kind": "chart",
"title": "subtract Self",
"tasks": [
"PersistentSet<Int> subtract Self (0% overlap)",
"PersistentSet<Int> subtract Self (25% overlap)",
"PersistentSet<Int> subtract Self (50% overlap)",
"PersistentSet<Int> subtract Self (75% overlap)",
"PersistentSet<Int> subtract Self (100% overlap)",
]
},
{
"kind": "chart",
"title": "subtract with Array",
"tasks": [
"PersistentSet<Int> subtract Array (0% overlap)",
"PersistentSet<Int> subtract Array (25% overlap)",
"PersistentSet<Int> subtract Array (50% overlap)",
"PersistentSet<Int> subtract Array (75% overlap)",
"PersistentSet<Int> subtract Array (100% overlap)",
]
},
]
},
{
"kind": "group",
"title": "Reference comparisons",
"directory": "versus",
"contents": [
{
"kind": "chart",
"title": "init from buffer of integers",
"tasks": [
"PersistentSet<Int> init from unsafe buffer",
"Set<Int> init from unsafe buffer",
]
},
{
"kind": "chart",
"title": "init from range of integers",
"tasks": [
"PersistentSet<Int> init from range",
"Set<Int> init from range",
]
},
{
"kind": "chart",
"title": "sequential iteration",
"tasks": [
"PersistentSet<Int> sequential iteration",
"Set<Int> sequential iteration",
]
},
{
"kind": "chart",
"title": "sequential iteration using indices",
"tasks": [
"PersistentSet<Int> sequential iteration, indices",
"Set<Int> sequential iteration, indices",
]
},
{
"kind": "chart",
"title": "successful random lookups",
"tasks": [
"PersistentSet<Int> successful contains",
"Set<Int> successful contains",
]
},
{
"kind": "chart",
"title": "unsuccessful random lookups",
"tasks": [
"PersistentSet<Int> unsuccessful contains",
"Set<Int> unsuccessful contains",
]
},
{
"kind": "chart",
"title": "insert",
"tasks": [
"PersistentSet<Int> insert",
"PersistentSet<Int> insert, shared",
"Set<Int> insert",
"Set<Int> insert, reserving capacity",
"Set<Int> insert, shared",
]
},
{
"kind": "chart",
"title": "diffing",
"tasks": [
"PersistentSet<Int> insert one + subtract, shared",
"Set<Int> insert one + subtract, shared",
]
},
{
"kind": "chart",
"title": "remove",
"tasks": [
"PersistentSet<Int> remove",
"PersistentSet<Int> remove, shared",
"Set<Int> remove",
"Set<Int> remove, shared",
]
},
{
"kind": "variants",
"charts": [
{
"kind": "chart",
"title": "union (0% overlap)",
"tasks": [
"OrderedSet<Int> union with Self (0% overlap)",
"OrderedSet<Int> union with Array (0% overlap)",
"Set<Int> union with Self (0% overlap)",
"Set<Int> union with Array (0% overlap)",
]
},
{
"kind": "chart",
"title": "union (25% overlap)",
"tasks": [
"OrderedSet<Int> union with Self (25% overlap)",
"OrderedSet<Int> union with Array (25% overlap)",
"Set<Int> union with Self (25% overlap)",
"Set<Int> union with Array (25% overlap)",
]
},
{
"kind": "chart",
"title": "union (50% overlap)",
"tasks": [
"OrderedSet<Int> union with Self (50% overlap)",
"OrderedSet<Int> union with Array (50% overlap)",
"Set<Int> union with Self (50% overlap)",
"Set<Int> union with Array (50% overlap)",
]
},
{
"kind": "chart",
"title": "union (75% overlap)",
"tasks": [
"OrderedSet<Int> union with Self (75% overlap)",
"OrderedSet<Int> union with Array (75% overlap)",
"Set<Int> union with Self (75% overlap)",
"Set<Int> union with Array (75% overlap)",
]
},
{
"kind": "chart",
"title": "union (100% overlap)",
"tasks": [
"OrderedSet<Int> union with Self (100% overlap)",
"OrderedSet<Int> union with Array (100% overlap)",
"Set<Int> union with Self (100% overlap)",
"Set<Int> union with Array (100% overlap)",
]
},
]
},
{
"kind": "variants",
"charts": [
{
"kind": "chart",
"title": "formUnion (0% overlap)",
"tasks": [
"OrderedSet<Int> formUnion with Self (0% overlap)",
"OrderedSet<Int> formUnion with Array (0% overlap)",
"Set<Int> formUnion with Self (0% overlap)",
"Set<Int> formUnion with Array (0% overlap)",
]
},
{
"kind": "chart",
"title": "formUnion (25% overlap)",
"tasks": [
"OrderedSet<Int> formUnion with Self (25% overlap)",
"OrderedSet<Int> formUnion with Array (25% overlap)",
"Set<Int> formUnion with Self (25% overlap)",
"Set<Int> formUnion with Array (25% overlap)",
]
},
{
"kind": "chart",
"title": "formUnion (50% overlap)",
"tasks": [
"OrderedSet<Int> formUnion with Self (50% overlap)",
"OrderedSet<Int> formUnion with Array (50% overlap)",
"Set<Int> formUnion with Self (50% overlap)",
"Set<Int> formUnion with Array (50% overlap)",
]
},
{
"kind": "chart",
"title": "formUnion (75% overlap)",
"tasks": [
"OrderedSet<Int> formUnion with Self (75% overlap)",
"OrderedSet<Int> formUnion with Array (75% overlap)",
"Set<Int> formUnion with Self (75% overlap)",
"Set<Int> formUnion with Array (75% overlap)",
]
},
{
"kind": "chart",
"title": "formUnion (100% overlap)",
"tasks": [
"OrderedSet<Int> formUnion with Self (100% overlap)",
"OrderedSet<Int> formUnion with Array (100% overlap)",
"Set<Int> formUnion with Self (100% overlap)",
"Set<Int> formUnion with Array (100% overlap)",
]
},
]
},
{
"kind": "variants",
"charts": [
{
"kind": "chart",
"title": "intersection (0% overlap)",
"tasks": [
"OrderedSet<Int> intersection with Self (0% overlap)",
"OrderedSet<Int> intersection with Array (0% overlap)",
"Set<Int> intersection with Self (0% overlap)",
"Set<Int> intersection with Array (0% overlap)",
]
},
{
"kind": "chart",
"title": "intersection (25% overlap)",
"tasks": [
"OrderedSet<Int> intersection with Self (25% overlap)",
"OrderedSet<Int> intersection with Array (25% overlap)",
"Set<Int> intersection with Self (25% overlap)",
"Set<Int> intersection with Array (25% overlap)",
]
},
{
"kind": "chart",
"title": "intersection (50% overlap)",
"tasks": [
"OrderedSet<Int> intersection with Self (50% overlap)",
"OrderedSet<Int> intersection with Array (50% overlap)",
"Set<Int> intersection with Self (50% overlap)",
"Set<Int> intersection with Array (50% overlap)",
]
},
{
"kind": "chart",
"title": "intersection (75% overlap)",
"tasks": [
"OrderedSet<Int> intersection with Self (75% overlap)",
"OrderedSet<Int> intersection with Array (75% overlap)",
"Set<Int> intersection with Self (75% overlap)",
"Set<Int> intersection with Array (75% overlap)",
]
},
{
"kind": "chart",
"title": "intersection (100% overlap)",
"tasks": [
"OrderedSet<Int> intersection with Self (100% overlap)",
"OrderedSet<Int> intersection with Array (100% overlap)",
"Set<Int> intersection with Self (100% overlap)",
"Set<Int> intersection with Array (100% overlap)",
]
},
]
},
{
"kind": "variants",
"charts": [
{
"kind": "chart",
"title": "formIntersection (0% overlap)",
"tasks": [
"OrderedSet<Int> formIntersection with Self (0% overlap)",
"OrderedSet<Int> formIntersection with Array (0% overlap)",
"Set<Int> formIntersection with Self (0% overlap)",
"Set<Int> formIntersection with Array (0% overlap)",
]
},
{
"kind": "chart",
"title": "formIntersection (25% overlap)",
"tasks": [
"OrderedSet<Int> formIntersection with Self (25% overlap)",
"OrderedSet<Int> formIntersection with Array (25% overlap)",
"Set<Int> formIntersection with Self (25% overlap)",
"Set<Int> formIntersection with Array (25% overlap)",
]
},
{
"kind": "chart",
"title": "formIntersection (50% overlap)",
"tasks": [
"OrderedSet<Int> formIntersection with Self (50% overlap)",
"OrderedSet<Int> formIntersection with Array (50% overlap)",
"Set<Int> formIntersection with Self (50% overlap)",
"Set<Int> formIntersection with Array (50% overlap)",
]
},
{
"kind": "chart",
"title": "formIntersection (75% overlap)",
"tasks": [
"OrderedSet<Int> formIntersection with Self (75% overlap)",
"OrderedSet<Int> formIntersection with Array (75% overlap)",
"Set<Int> formIntersection with Self (75% overlap)",
"Set<Int> formIntersection with Array (75% overlap)",
]
},
{
"kind": "chart",
"title": "formIntersection (100% overlap)",
"tasks": [
"OrderedSet<Int> formIntersection with Self (100% overlap)",
"OrderedSet<Int> formIntersection with Array (100% overlap)",
"Set<Int> formIntersection with Self (100% overlap)",
"Set<Int> formIntersection with Array (100% overlap)",
]
},
]
},
{
"kind": "variants",
"charts": [
{
"kind": "chart",
"title": "symmetricDifference (0% overlap)",
"tasks": [
"OrderedSet<Int> symmetricDifference with Self (0% overlap)",
"OrderedSet<Int> symmetricDifference with Array (0% overlap)",
"Set<Int> symmetricDifference with Self (0% overlap)",
"Set<Int> symmetricDifference with Array (0% overlap)",
]
},
{
"kind": "chart",
"title": "symmetricDifference (25% overlap)",
"tasks": [
"OrderedSet<Int> symmetricDifference with Self (25% overlap)",
"OrderedSet<Int> symmetricDifference with Array (25% overlap)",
"Set<Int> symmetricDifference with Self (25% overlap)",
"Set<Int> symmetricDifference with Array (25% overlap)",
]
},
{
"kind": "chart",
"title": "symmetricDifference (50% overlap)",
"tasks": [
"OrderedSet<Int> symmetricDifference with Self (50% overlap)",
"OrderedSet<Int> symmetricDifference with Array (50% overlap)",
"Set<Int> symmetricDifference with Self (50% overlap)",
"Set<Int> symmetricDifference with Array (50% overlap)",
]
},
{
"kind": "chart",
"title": "symmetricDifference (75% overlap)",
"tasks": [
"OrderedSet<Int> symmetricDifference with Self (75% overlap)",
"OrderedSet<Int> symmetricDifference with Array (75% overlap)",
"Set<Int> symmetricDifference with Self (75% overlap)",
"Set<Int> symmetricDifference with Array (75% overlap)",
]
},
{
"kind": "chart",
"title": "symmetricDifference (100% overlap)",
"tasks": [
"OrderedSet<Int> symmetricDifference with Self (100% overlap)",
"OrderedSet<Int> symmetricDifference with Array (100% overlap)",
"Set<Int> symmetricDifference with Self (100% overlap)",
"Set<Int> symmetricDifference with Array (100% overlap)",
]
},
]
},
{
"kind": "variants",
"charts": [
{
"kind": "chart",
"title": "formSymmetricDifference (0% overlap)",
"tasks": [
"OrderedSet<Int> formSymmetricDifference with Self (0% overlap)",
"OrderedSet<Int> formSymmetricDifference with Array (0% overlap)",
"Set<Int> formSymmetricDifference with Self (0% overlap)",
"Set<Int> formSymmetricDifference with Array (0% overlap)",
]
},
{
"kind": "chart",
"title": "formSymmetricDifference (25% overlap)",
"tasks": [
"OrderedSet<Int> formSymmetricDifference with Self (25% overlap)",
"OrderedSet<Int> formSymmetricDifference with Array (25% overlap)",
"Set<Int> formSymmetricDifference with Self (25% overlap)",
"Set<Int> formSymmetricDifference with Array (25% overlap)",
]
},
{
"kind": "chart",
"title": "formSymmetricDifference (50% overlap)",
"tasks": [
"OrderedSet<Int> formSymmetricDifference with Self (50% overlap)",
"OrderedSet<Int> formSymmetricDifference with Array (50% overlap)",
"Set<Int> formSymmetricDifference with Self (50% overlap)",
"Set<Int> formSymmetricDifference with Array (50% overlap)",
]
},
{
"kind": "chart",
"title": "formSymmetricDifference (75% overlap)",
"tasks": [
"OrderedSet<Int> formSymmetricDifference with Self (75% overlap)",
"OrderedSet<Int> formSymmetricDifference with Array (75% overlap)",
"Set<Int> formSymmetricDifference with Self (75% overlap)",
"Set<Int> formSymmetricDifference with Array (75% overlap)",
]
},
{
"kind": "chart",
"title": "formSymmetricDifference (100% overlap)",
"tasks": [
"OrderedSet<Int> formSymmetricDifference with Self (100% overlap)",
"OrderedSet<Int> formSymmetricDifference with Array (100% overlap)",
"Set<Int> formSymmetricDifference with Self (100% overlap)",
"Set<Int> formSymmetricDifference with Array (100% overlap)",
]
},
]
},
{
"kind": "variants",
"charts": [
{
"kind": "chart",
"title": "subtracting (0% overlap)",
"tasks": [
"OrderedSet<Int> subtracting Self (0% overlap)",
"OrderedSet<Int> subtracting Array (0% overlap)",
"Set<Int> subtracting Self (0% overlap)",
"Set<Int> subtracting Array (0% overlap)",
]
},
{
"kind": "chart",
"title": "subtracting (25% overlap)",
"tasks": [
"OrderedSet<Int> subtracting Self (25% overlap)",
"OrderedSet<Int> subtracting Array (25% overlap)",
"Set<Int> subtracting Self (25% overlap)",
"Set<Int> subtracting Array (25% overlap)",
]
},
{
"kind": "chart",
"title": "subtracting (50% overlap)",
"tasks": [
"OrderedSet<Int> subtracting Self (50% overlap)",
"OrderedSet<Int> subtracting Array (50% overlap)",
"Set<Int> subtracting Self (50% overlap)",
"Set<Int> subtracting Array (50% overlap)",
]
},
{
"kind": "chart",
"title": "subtracting (75% overlap)",
"tasks": [
"OrderedSet<Int> subtracting Self (75% overlap)",
"OrderedSet<Int> subtracting Array (75% overlap)",
"Set<Int> subtracting Self (75% overlap)",
"Set<Int> subtracting Array (75% overlap)",
]
},
{
"kind": "chart",
"title": "subtracting (100% overlap)",
"tasks": [
"OrderedSet<Int> subtracting Self (100% overlap)",
"OrderedSet<Int> subtracting Array (100% overlap)",
"Set<Int> subtracting Self (100% overlap)",
"Set<Int> subtracting Array (100% overlap)",
]
},
]
},
{
"kind": "variants",
"charts": [
{
"kind": "chart",
"title": "subtract (0% overlap)",
"tasks": [
"OrderedSet<Int> subtract Self (0% overlap)",
"OrderedSet<Int> subtract Array (0% overlap)",
"Set<Int> subtract Self (0% overlap)",
"Set<Int> subtract Array (0% overlap)",
]
},
{
"kind": "chart",
"title": "subtract (25% overlap)",
"tasks": [
"OrderedSet<Int> subtract Self (25% overlap)",
"OrderedSet<Int> subtract Array (25% overlap)",
"Set<Int> subtract Self (25% overlap)",
"Set<Int> subtract Array (25% overlap)",
]
},
{
"kind": "chart",
"title": "subtract (50% overlap)",
"tasks": [
"OrderedSet<Int> subtract Self (50% overlap)",
"OrderedSet<Int> subtract Array (50% overlap)",
"Set<Int> subtract Self (50% overlap)",
"Set<Int> subtract Array (50% overlap)",
]
},
{
"kind": "chart",
"title": "subtract (75% overlap)",
"tasks": [
"OrderedSet<Int> subtract Self (75% overlap)",
"OrderedSet<Int> subtract Array (75% overlap)",
"Set<Int> subtract Self (75% overlap)",
"Set<Int> subtract Array (75% overlap)",
]
},
{
"kind": "chart",
"title": "subtract (100% overlap)",
"tasks": [
"OrderedSet<Int> subtract Self (100% overlap)",
"OrderedSet<Int> subtract Array (100% overlap)",
"Set<Int> subtract Self (100% overlap)",
"Set<Int> subtract Array (100% overlap)",
]
},
]
},
]
},
]
}
@@ -0,0 +1,436 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import CollectionsBenchmark
import PersistentCollections
extension Benchmark {
public mutating func addPersistentSetBenchmarks() {
self.addSimple(
title: "PersistentSet<Int> init from range",
input: Int.self
) { size in
blackHole(PersistentSet(0 ..< size))
}
self.addSimple(
title: "PersistentSet<Int> init from unsafe buffer",
input: [Int].self
) { input in
input.withUnsafeBufferPointer { buffer in
blackHole(PersistentSet(buffer))
}
}
self.add(
title: "PersistentSet<Int> sequential iteration",
input: Int.self
) { size in
let set = PersistentSet(0 ..< size)
return { timer in
for i in set {
blackHole(i)
}
}
}
self.add(
title: "PersistentSet<Int> sequential iteration, indices",
input: Int.self
) { size in
let set = PersistentSet(0 ..< size)
return { timer in
for i in set.indices {
blackHole(set[i])
}
}
}
self.add(
title: "PersistentSet<Int> successful contains",
input: ([Int], [Int]).self
) { input, lookups in
let set = PersistentSet(input)
return { timer in
for i in lookups {
precondition(set.contains(i))
}
}
}
self.add(
title: "PersistentSet<Int> unsuccessful contains",
input: ([Int], [Int]).self
) { input, lookups in
let set = PersistentSet(input)
let lookups = lookups.map { $0 + input.count }
return { timer in
for i in lookups {
precondition(!set.contains(i))
}
}
}
self.addSimple(
title: "PersistentSet<Int> insert",
input: [Int].self
) { input in
var set: PersistentSet<Int> = []
for i in input {
set.insert(i)
}
precondition(set.count == input.count)
blackHole(set)
}
self.addSimple(
title: "PersistentSet<Int> insert, shared",
input: [Int].self
) { input in
var set: PersistentSet<Int> = []
for i in input {
let copy = set
set.insert(i)
blackHole(copy)
}
precondition(set.count == input.count)
blackHole(set)
}
self.add(
title: "PersistentSet<Int> insert one + subtract, shared",
input: [Int].self
) { input in
let original = PersistentSet(input)
let newMember = input.count
return { timer in
var copy = original
copy.insert(newMember)
let diff = copy.subtracting(original)
precondition(diff.count == 1 && diff.first == newMember)
blackHole(copy)
}
}
do {
var timer = Timer()
let input = 0 ..< 1_000
let newMember = input.count
let original = PersistentSet(input)
timer.measure {
var copy = original
copy.insert(newMember)
let diff = copy.subtracting(original)
precondition(diff.count == 1 && diff.first == newMember)
blackHole(copy)
}
}
self.add(
title: "PersistentSet<Int> remove",
input: ([Int], [Int]).self
) { input, removals in
return { timer in
var set = PersistentSet(input)
for i in removals {
set.remove(i)
}
precondition(set.isEmpty)
blackHole(set)
}
}
self.add(
title: "PersistentSet<Int> remove, shared",
input: ([Int], [Int]).self
) { input, removals in
return { timer in
var set = PersistentSet(input)
for i in removals {
let copy = set
set.remove(i)
blackHole(copy)
}
precondition(set.isEmpty)
blackHole(set)
}
}
let overlaps: [(String, (Int) -> Int)] = [
("0%", { c in c }),
("25%", { c in 3 * c / 4 }),
("50%", { c in c / 2 }),
("75%", { c in c / 4 }),
("100%", { c in 0 }),
]
// SetAlgebra operations with Self
do {
for (percentage, start) in overlaps {
self.add(
title: "PersistentSet<Int> union with Self (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let a = PersistentSet(input)
let b = PersistentSet(start ..< start + input.count)
return { timer in
blackHole(a.union(identity(b)))
}
}
}
for (percentage, start) in overlaps {
self.add(
title: "PersistentSet<Int> intersection with Self (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let a = PersistentSet(input)
let b = PersistentSet(start ..< start + input.count)
return { timer in
blackHole(a.intersection(identity(b)))
}
}
}
for (percentage, start) in overlaps {
self.add(
title: "PersistentSet<Int> symmetricDifference with Self (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let a = PersistentSet(input)
let b = PersistentSet(start ..< start + input.count)
return { timer in
blackHole(a.symmetricDifference(identity(b)))
}
}
}
for (percentage, start) in overlaps {
self.add(
title: "PersistentSet<Int> subtracting Self (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let a = PersistentSet(input)
let b = PersistentSet(start ..< start + input.count)
return { timer in
blackHole(a.subtracting(identity(b)))
}
}
}
}
// SetAlgebra operations with Array
do {
for (percentage, start) in overlaps {
self.add(
title: "PersistentSet<Int> union with Array (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let a = PersistentSet(input)
let b = Array(start ..< start + input.count)
return { timer in
blackHole(a.union(identity(b)))
}
}
}
for (percentage, start) in overlaps {
self.add(
title: "PersistentSet<Int> intersection with Array (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let a = PersistentSet(input)
let b = Array(start ..< start + input.count)
return { timer in
blackHole(a.intersection(identity(b)))
}
}
}
for (percentage, start) in overlaps {
self.add(
title: "PersistentSet<Int> symmetricDifference with Array (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let a = PersistentSet(input)
let b = Array(start ..< start + input.count)
return { timer in
blackHole(a.symmetricDifference(identity(b)))
}
}
}
for (percentage, start) in overlaps {
self.add(
title: "PersistentSet<Int> subtracting Array (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let a = PersistentSet(input)
let b = Array(start ..< start + input.count)
return { timer in
blackHole(a.subtracting(identity(b)))
}
}
}
}
// SetAlgebra mutations with Self
do {
for (percentage, start) in overlaps {
self.add(
title: "PersistentSet<Int> formUnion with Self (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let b = PersistentSet(start ..< start + input.count)
return { timer in
var a = PersistentSet(input)
timer.measure {
a.formUnion(identity(b))
}
blackHole(a)
}
}
}
for (percentage, start) in overlaps {
self.add(
title: "PersistentSet<Int> formIntersection with Self (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let b = PersistentSet(start ..< start + input.count)
return { timer in
var a = PersistentSet(input)
timer.measure {
a.formIntersection(identity(b))
}
blackHole(a)
}
}
}
for (percentage, start) in overlaps {
self.add(
title: "PersistentSet<Int> formSymmetricDifference with Self (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let b = PersistentSet(start ..< start + input.count)
return { timer in
var a = PersistentSet(input)
timer.measure {
a.formSymmetricDifference(identity(b))
}
blackHole(a)
}
}
}
for (percentage, start) in overlaps {
self.add(
title: "PersistentSet<Int> subtract Self (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let b = PersistentSet(start ..< start + input.count)
return { timer in
var a = PersistentSet(input)
timer.measure {
a.subtract(identity(b))
}
blackHole(a)
}
}
}
}
// SetAlgebra mutations with Array
do {
for (percentage, start) in overlaps {
self.add(
title: "PersistentSet<Int> formUnion with Array (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let b = Array(start ..< start + input.count)
return { timer in
var a = PersistentSet(input)
timer.measure {
a.formUnion(identity(b))
}
blackHole(a)
}
}
}
for (percentage, start) in overlaps {
self.add(
title: "PersistentSet<Int> formIntersection with Array (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let b = Array(start ..< start + input.count)
return { timer in
var a = PersistentSet(input)
timer.measure {
a.formIntersection(identity(b))
}
blackHole(a)
}
}
}
for (percentage, start) in overlaps {
self.add(
title: "PersistentSet<Int> formSymmetricDifference with Array (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let b = Array(start ..< start + input.count)
return { timer in
var a = PersistentSet(input)
timer.measure {
a.formSymmetricDifference(identity(b))
}
blackHole(a)
}
}
}
for (percentage, start) in overlaps {
self.add(
title: "PersistentSet<Int> subtract Array (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let b = Array(start ..< start + input.count)
return { timer in
var a = PersistentSet(input)
timer.measure {
a.subtract(identity(b))
}
blackHole(a)
}
}
}
}
}
}
@@ -61,6 +61,18 @@ extension Benchmark {
}
}
self.add(
title: "Set<Int> sequential iteration, indices",
input: Int.self
) { size in
let set = Set(0 ..< size)
return { timer in
for i in set.indices {
blackHole(set[i])
}
}
}
self.add(
title: "Set<Int> successful contains",
input: ([Int], [Int]).self
@@ -111,6 +123,35 @@ extension Benchmark {
blackHole(set)
}
self.addSimple(
title: "Set<Int> insert, shared",
input: [Int].self
) { input in
var set: Set<Int> = []
for i in input {
let copy = set
set.insert(i)
blackHole(copy)
}
precondition(set.count == input.count)
blackHole(set)
}
self.add(
title: "Set<Int> insert one + subtract, shared",
input: [Int].self
) { input in
let original = Set(input)
let newMember = input.count
return { timer in
var copy = original
copy.insert(newMember)
let diff = copy.subtracting(original)
precondition(diff.count == 1 && diff.first == newMember)
blackHole(copy)
}
}
self.add(
title: "Set<Int> remove",
input: ([Int], [Int]).self
@@ -125,6 +166,22 @@ extension Benchmark {
}
}
self.add(
title: "Set<Int> remove, shared",
input: ([Int], [Int]).self
) { input, removals in
return { timer in
var set = Set(input)
for i in removals {
let copy = set
set.remove(i)
blackHole(copy)
}
precondition(set.isEmpty)
blackHole(set)
}
}
let overlaps: [(String, (Int) -> Int)] = [
("0%", { c in c }),
("25%", { c in 3 * c / 4 }),
@@ -392,6 +449,5 @@ extension Benchmark {
}
}
}
}
}
@@ -37,6 +37,7 @@ benchmark.addSortedSetBenchmarks()
benchmark.addSortedDictionaryBenchmarks()
benchmark.addHeapBenchmarks()
benchmark.addBitSetBenchmarks()
benchmark.addPersistentSetBenchmarks()
benchmark.addCppBenchmarks()
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
benchmark.addFoundationBenchmarks()
@@ -0,0 +1,20 @@
# ``BitCollections``
**Swift Collections** is an open-source package of data structure implementations for the Swift programming language.
## Overview
#### Additional Resources
- [`Swift Collections` on GitHub](https://github.com/apple/swift-collections/)
- [`Swift Collections` on the Swift Forums](https://forums.swift.org/c/related-projects/collections/72)
## Topics
### Structures
- ``BitSet``
- ``BitArray``
@@ -0,0 +1,70 @@
# ``BitCollections/BitArray``
<!-- Summary -->
<!-- ## Overview -->
## Topics
### Creating a Bit Array
- ``init()``
- ``init(_:)-2y0wv``
- ``init(repeating:count:)-4j5yd``
- ``init(_:)-6ldyw``
- ``init(_:)-4tksd``
- ``init(_:)-765d2``
- ``init(bitPattern:)``
- ``random(count:)``
- ``random(count:using:)``
### Accessing Elements
- ``subscript(_:)-51ccj``
- ``subscript(_:)-944vg``
- ``first``
- ``last``
### Adding Elements
- ``append(_:)``
- ``append(contentsOf:)-18dwf``
- ``append(contentsOf:)-576q4``
- ``append(contentsOf:)-8xkr8``
- ``insert(_:at:)``
- ``insert(contentsOf:at:)-7e1xn``
- ``insert(contentsOf:at:)-35dp3``
- ``insert(contentsOf:at:)-1wsgw``
- ``truncateOrExtend(toCount:with:)``
### Removing Elements
- ``remove(at:)-7ij12``
- ``removeAll(keepingCapacity:)-5tkge``
- ``removeAll(where:)-7tv7z``
- ``removeSubrange(_:)-86ou8``
- ``removeSubrange(_:)-18qe7``
- ``removeLast()``
- ``removeLast(_:)``
- ``removeFirst()``
- ``removeFirst(_:)``
- ``popLast()``
### Replacing Elements
- ``fill(in:with:)``
- ``fill(with:)``
- ``replaceSubrange(_:with:)-163u2``
- ``replaceSubrange(_:with:)-875d8``
- ``replaceSubrange(_:with:)-2i7lu``
- ``replaceSubrange(_:with:)-b5ou``
### Bitwise Operators
- ``&(_:_:)``
- ``_(_:_:)-1rhw``
- ``_(_:_:)-56s54``
- ``~(_:)``
- ``&=(_:_:)``
- ``_=(_:_:)-69yf0``
- ``_=(_:_:)-icef``
@@ -0,0 +1,125 @@
# ``BitCollections/BitSet/Counted-swift.struct``
<!-- Summary -->
<!-- ## Overview -->
## Topics
### Collection Views
- ``uncounted``
### Creating a Set
- ``init()``
- ``init(reservingCapacity:)``
- ``init(_:)-15cws``
- ``init(_:)-38hho``
- ``init(_:)-2of3i``
- ``init(_:)-5fhls``
- ``init(bitPattern:)``
- ``init(words:)``
- ``random(upTo:)``
- ``random(upTo:using:)``
### Finding Elements
- ``contains(_:)``
- ``firstIndex(of:)``
- ``lastIndex(of:)``
### Adding and Updating Elements
- ``insert(_:)``
- ``update(with:)``
### Removing Elements
- ``filter(_:)``
- ``remove(_:)``
- ``remove(at:)``
### Sorted Set Operations
- ``subscript(member:)``
- ``subscript(members:)-5nkxk``
- ``subscript(members:)-5xfq5``
- ``min()``
- ``max()``
- ``sorted()``
### Binary Set Operations
- ``intersection(_:)-1wfb5``
- ``intersection(_:)-4evdp``
- ``intersection(_:)-9rtcc``
- ``intersection(_:)-13us``
- ``union(_:)-2okwt``
- ``union(_:)-pwqf``
- ``union(_:)-18u31``
- ``union(_:)-8ysz9``
- ``subtracting(_:)-7u4tf``
- ``subtracting(_:)-5vgml``
- ``subtracting(_:)-6scy1``
- ``subtracting(_:)-82loi``
- ``symmetricDifference(_:)-84e40``
- ``symmetricDifference(_:)-3suo3``
- ``symmetricDifference(_:)-7zx5q``
- ``symmetricDifference(_:)-46ni1``
- ``formIntersection(_:)-49and``
- ``formIntersection(_:)-49a0x``
- ``formIntersection(_:)-79anv``
- ``formIntersection(_:)-3zoc4``
- ``formUnion(_:)-c6a3``
- ``formUnion(_:)-c5kv``
- ``formUnion(_:)-2f05x``
- ``formUnion(_:)-8kilf``
- ``subtract(_:)-2hzty``
- ``subtract(_:)-2i1qq``
- ``subtract(_:)-32jtb``
- ``subtract(_:)-75xgt``
- ``formSymmetricDifference(_:)-6vskl``
- ``formSymmetricDifference(_:)-6vs05``
- ``formSymmetricDifference(_:)-d2kd``
- ``formSymmetricDifference(_:)-54ghn``
### Binary Set Predicates
- ``==(_:_:)``
- ``isEqual(to:)-5bw9h``
- ``isEqual(to:)-8jxq5``
- ``isEqual(to:)-7w9qy``
- ``isEqual(to:)-9tnfo``
- ``isSubset(of:)-8iy8c``
- ``isSubset(of:)-1r41b``
- ``isSubset(of:)-1dz0p``
- ``isSubset(of:)-3bq5m``
- ``isSuperset(of:)-48i5c``
- ``isSuperset(of:)-10gu8``
- ``isSuperset(of:)-8b7lq``
- ``isSuperset(of:)-6slai``
- ``isStrictSubset(of:)-5ry1b``
- ``isStrictSubset(of:)-2ndu3``
- ``isStrictSubset(of:)-9iul0``
- ``isStrictSubset(of:)-2pq1j``
- ``isStrictSuperset(of:)-9mgmd``
- ``isStrictSuperset(of:)-6hw4t``
- ``isStrictSuperset(of:)-1ya0j``
- ``isStrictSuperset(of:)-4qt1e``
- ``isDisjoint(with:)-9wyku``
- ``isDisjoint(with:)-5fww0``
- ``isDisjoint(with:)-6p0t7``
- ``isDisjoint(with:)-eujj``
@@ -0,0 +1,130 @@
# ``BitCollections/BitSet``
<!-- Summary -->
<!-- ## Overview -->
## Topics
### Collection Views
- ``Counted-swift.struct``
- ``counted-swift.property``
### Creating a Set
- ``init()``
- ``init(reservingCapacity:)``
- ``init(_:)-15cws``
- ``init(_:)-38hho``
- ``init(_:)-2of3i``
- ``init(_:)-5fhls``
- ``init(bitPattern:)``
- ``init(words:)``
- ``random(upTo:)``
- ``random(upTo:using:)``
### Finding Elements
- ``contains(_:)``
- ``firstIndex(of:)``
- ``lastIndex(of:)``
### Adding and Updating Elements
- ``insert(_:)``
- ``update(with:)``
### Removing Elements
- ``filter(_:)``
- ``remove(_:)``
- ``remove(at:)``
### Sorted Set Operations
- ``subscript(member:)``
- ``subscript(members:)-5nkxk``
- ``subscript(members:)-5xfq5``
- ``min()``
- ``max()``
- ``sorted()``
### Combining Sets
- ``intersection(_:)-84q4u``
- ``intersection(_:)-8hcl9``
- ``intersection(_:)-7l8p3``
- ``intersection(_:)-7kgi``
- ``union(_:)-5kqmx``
- ``union(_:)-6mj8``
- ``union(_:)-50wc4``
- ``union(_:)-10had``
- ``subtracting(_:)-79e0o``
- ``subtracting(_:)-7re82``
- ``subtracting(_:)-7rn26``
- ``subtracting(_:)-42s7d``
- ``symmetricDifference(_:)-55kqn``
- ``symmetricDifference(_:)-5xt65``
- ``symmetricDifference(_:)-91kh8``
- ``symmetricDifference(_:)-79wfx``
- ``formIntersection(_:)-u07v``
- ``formIntersection(_:)-87gjl``
- ``formIntersection(_:)-9gffv``
- ``formIntersection(_:)-8t2je``
- ``formUnion(_:)-72o7q``
- ``formUnion(_:)-370hb``
- ``formUnion(_:)-7tw8j``
- ``formUnion(_:)-12ll3``
- ``subtract(_:)-9aabm``
- ``subtract(_:)-1o083``
- ``subtract(_:)-6kijg``
- ``subtract(_:)-3pynh``
- ``formSymmetricDifference(_:)-2le2k``
- ``formSymmetricDifference(_:)-5edyr``
- ``formSymmetricDifference(_:)-7wole``
- ``formSymmetricDifference(_:)-8vcnf``
### Comparing Sets
- ``==(_:_:)``
- ``isEqual(to:)-5zfpo``
- ``isEqual(to:)-93d52``
- ``isEqual(to:)-542zl``
- ``isEqual(to:)-1d66i``
- ``isSubset(of:)-73apg``
- ``isSubset(of:)-14xt1``
- ``isSubset(of:)-4mj71``
- ``isSubset(of:)-20wxs``
- ``isSuperset(of:)-1mfg2``
- ``isSuperset(of:)-5adir``
- ``isSuperset(of:)-4y68t``
- ``isSuperset(of:)-2m7mj``
- ``isStrictSubset(of:)-8m1z6``
- ``isStrictSubset(of:)-3y2l1``
- ``isStrictSubset(of:)-97rky``
- ``isStrictSubset(of:)-p3zj``
- ``isStrictSuperset(of:)-6e5gm``
- ``isStrictSuperset(of:)-735zn``
- ``isStrictSuperset(of:)-26acy``
- ``isStrictSuperset(of:)-5jmxx``
- ``isDisjoint(with:)-2cdg6``
- ``isDisjoint(with:)-3klxy``
- ``isDisjoint(with:)-4uidy``
- ``isDisjoint(with:)-78a8w``
### Memory Management
- ``reserveCapacity(_:)``
@@ -12,6 +12,6 @@
extension BitSet: CustomReflectable {
/// The custom mirror for this instance.
public var customMirror: Mirror {
Mirror(self, unlabeledChildren: self, displayStyle: .collection)
Mirror(self, unlabeledChildren: self, displayStyle: .set)
}
}
@@ -91,12 +91,25 @@ extension BitSet {
self = (elements as! BitSet)
return
}
if S.self == BitSet.Counted.self {
self = (elements as! BitSet.Counted)._bits
return
}
self.init()
for value in elements {
self.insert(value)
}
}
/// Create a new bit set containing all the nonnegative elements of a
/// sequence of integers.
///
/// Items in `elements` that are negative are silently ignored.
///
/// - Parameters:
/// - elements: The sequence of elements to turn into a bit set.
///
/// - Complexity: O(*n*), where *n* is the number of elements in the sequence.
@inlinable
internal init<S: Sequence>(
_validMembersOf elements: __owned S
@@ -105,6 +118,10 @@ extension BitSet {
self = (elements as! BitSet)
return
}
if S.self == BitSet.Counted.self {
self = (elements as! BitSet.Counted)._bits
return
}
if S.self == Range<Int>.self {
let r = (elements as! Range<Int>)
self.init(_range: r._clampedToUInt())
@@ -32,26 +32,18 @@ extension BitSet {
}
}
/// Removes the elements of this set that aren't also in the given sequence.
/// Removes the elements of this set that aren't also in the given one.
///
/// var set: BitSet = [1, 2, 3, 4]
/// let other: Set<Int> = [6, 4, 2, 0]
/// let other: BitSet.Counted = [0, 2, 4, 6]
/// set.formIntersection(other)
/// // set is now [2, 4]
///
/// - Parameter other: A sequence of integers.
/// - Parameter other: A bit set.
///
/// - Complexity: O(*max*) + *k*, where *max* is the largest item in `self`,
/// and *k* is the complexity of iterating over all elements in `other`.
@inlinable
public mutating func formIntersection<S: Sequence>(
_ other: __owned S
) where S.Element == Int {
if S.self == Range<Int>.self {
formIntersection(other as! Range<Int>)
return
}
formIntersection(BitSet(_validMembersOf: other))
/// - Complexity: O(*max*), where *max* is the largest item in either set.
public mutating func formIntersection(_ other: BitSet.Counted) {
formIntersection(other._bits)
}
/// Removes the elements of this set that aren't also in the given range.
@@ -77,4 +69,27 @@ extension BitSet {
handle.formIntersection(other)
}
}
/// Removes the elements of this set that aren't also in the given sequence.
///
/// var set: BitSet = [1, 2, 3, 4]
/// let other: Set<Int> = [6, 4, 2, 0]
/// set.formIntersection(other)
/// // set is now [2, 4]
///
/// - Parameter other: A sequence of integers.
///
/// - Complexity: O(*max*) + *k*, where *max* is the largest item in `self`,
/// and *k* is the complexity of iterating over all elements in `other`.
@inlinable
public mutating func formIntersection<S: Sequence>(
_ other: __owned S
) where S.Element == Int {
if S.self == Range<Int>.self {
formIntersection(other as! Range<Int>)
return
}
// Note: BitSet & BitSet.Counted are handled in the BitSet initializer below
formIntersection(BitSet(_validMembersOf: other))
}
}
@@ -21,7 +21,7 @@ extension BitSet {
/// - Parameter other: Another set.
///
/// - Complexity: O(*max*), where *max* is the largest item in either set.
public mutating func formSymmetricDifference(_ other: __owned Self) {
public mutating func formSymmetricDifference(_ other: Self) {
_ensureCapacity(limit: other._capacity)
_updateThenShrink { target, shrink in
other._read { source in
@@ -31,6 +31,42 @@ extension BitSet {
}
}
/// Replace this set with the elements contained in this set or the given
/// set, but not both.
///
/// var set: BitSet = [1, 2, 3, 4]
/// let other: BitSet.Counted = [0, 2, 4, 6]
/// set.formSymmetricDifference(other)
/// // set is now [0, 1, 3, 6]
///
/// - Parameter other: Another set.
///
/// - Complexity: O(*max*), where *max* is the largest item in either set.
public mutating func formSymmetricDifference(_ other: BitSet.Counted) {
formSymmetricDifference(other._bits)
}
/// Replace this set with the elements contained in this set or the given
/// range of integers, but not both.
///
/// var set: BitSet = [1, 2, 3, 4]
/// set.formSymmetricDifference(3 ..< 7)
/// // set is now [1, 2, 5, 6]
///
/// - Parameter other: A range of nonnegative integers.
///
/// - Complexity: O(*max*), where *max* is the largest item in either input.
public mutating func formSymmetricDifference(_ other: Range<Int>) {
guard let other = other._toUInt() else {
preconditionFailure("Invalid range")
}
guard !other.isEmpty else { return }
_ensureCapacity(limit: other.upperBound)
_updateThenShrink { handle, shrink in
handle.formSymmetricDifference(other)
}
}
/// Replace this set with the elements contained in this set or the given
/// sequence, but not both.
///
@@ -52,29 +88,7 @@ extension BitSet {
formSymmetricDifference(other as! Range<Int>)
return
}
// Note: BitSet & BitSet.Counted are handled in the BitSet initializer below
formSymmetricDifference(BitSet(other))
}
}
extension BitSet {
/// Replace this set with the elements contained in this set or the given
/// range of integers, but not both.
///
/// var set: BitSet = [1, 2, 3, 4]
/// set.formSymmetricDifference(3 ..< 7)
/// // set is now [1, 2, 5, 6]
///
/// - Parameter other: A range of nonnegative integers.
///
/// - Complexity: O(*max*), where *max* is the largest item in either input.
public mutating func formSymmetricDifference(_ other: Range<Int>) {
guard let other = other._toUInt() else {
preconditionFailure("Invalid range")
}
guard !other.isEmpty else { return }
_ensureCapacity(limit: other.upperBound)
_updateThenShrink { handle, shrink in
handle.formSymmetricDifference(other)
}
}
}
@@ -20,7 +20,7 @@ extension BitSet {
/// - Parameter other: The set of elements to insert.
///
/// - Complexity: O(*max*), where *max* is the largest item in either input.
public mutating func formUnion(_ other: __owned Self) {
public mutating func formUnion(_ other: Self) {
_ensureCapacity(limit: other._capacity)
_update { target in
other._read { source in
@@ -29,6 +29,40 @@ extension BitSet {
}
}
/// Adds the elements of the given set to this set.
///
/// var set: BitSet = [1, 2, 3, 4]
/// let other: BitSet.Counted = [0, 2, 4, 6]
/// set.formUnion(other)
/// // `set` is now `[0, 1, 2, 3, 4, 6]`
///
/// - Parameter other: The set of elements to insert.
///
/// - Complexity: O(*max*), where *max* is the largest item in either input.
public mutating func formUnion(_ other: BitSet.Counted) {
formUnion(other._bits)
}
/// Adds the elements of the given range of integers to this set.
///
/// var set: BitSet = [1, 2, 3, 4]
/// set.formUnion(3 ..< 7)
/// // `set` is now `[1, 2, 3, 4, 5, 6]`
///
/// - Parameter other: A range of nonnegative integers.
///
/// - Complexity: O(*max*), where *max* is the largest item in either input.
public mutating func formUnion(_ other: Range<Int>) {
guard let other = other._toUInt() else {
preconditionFailure("Invalid range")
}
guard !other.isEmpty else { return }
_ensureCapacity(limit: other.upperBound)
_update { handle in
handle.formUnion(other)
}
}
/// Adds the elements of the given sequence to this set.
///
/// var set: BitSet = [1, 2, 3, 4]
@@ -61,29 +95,4 @@ extension BitSet {
self.insert(value)
}
}
public mutating func formUnion(_ other: __owned BitSet.Counted) {
formUnion(other._bits)
}
/// Adds the elements of the given range of integers to this set.
///
/// var set: BitSet = [1, 2, 3, 4]
/// set.formUnion(3 ..< 7)
/// // `set` is now `[1, 2, 3, 4, 5, 6]`
///
/// - Parameter other: A range of nonnegative integers.
///
/// - Complexity: O(*max*), where *max* is the largest item in either input.
public mutating func formUnion(_ other: Range<Int>) {
guard let other = other._toUInt() else {
preconditionFailure("Invalid range")
}
guard !other.isEmpty else { return }
_ensureCapacity(limit: other.upperBound)
_update { handle in
handle.formUnion(other)
}
}
}
@@ -21,7 +21,7 @@ extension BitSet {
/// - Parameter other: A bit set.
///
/// - Complexity: O(*max*), where *max* is the largest item in either set.
public __consuming func intersection(_ other: Self) -> Self {
public func intersection(_ other: Self) -> Self {
self._read { first in
other._read { second in
Self(
@@ -32,6 +32,38 @@ extension BitSet {
}
}
/// Returns a new bit set with the elements that are common to both this set
/// and the given set.
///
/// let a: BitSet = [1, 2, 3, 4]
/// let b: BitSet.Counted = [6, 4, 2, 0]
/// let c = a.intersection(b)
/// // c is now [2, 4]
///
/// - Parameter other: A bit set.
///
/// - Complexity: O(*max*), where *max* is the largest item in either set.
public func intersection(_ other: BitSet.Counted) -> Self {
self.intersection(other._bits)
}
/// Returns a new bit set with the elements that are common to both this set
/// and the given range of integers.
///
/// let a: BitSet = [1, 2, 3, 4]
/// let c = a.intersection(-10 ..< 3)
/// // c is now [3, 4]
///
/// - Parameter other: A range of integers.
///
/// - Complexity: O(*max*) + *k*, where *max* is the largest item in `self`,
/// and *k* is the complexity of iterating over all elements in `other`.
public func intersection(_ other: Range<Int>) -> Self {
var result = self
result.formIntersection(other)
return result
}
/// Returns a new bit set with the elements that are common to both this set
/// and the given sequence.
///
@@ -45,34 +77,15 @@ extension BitSet {
/// - Complexity: O(*max*) + *k*, where *max* is the largest item in `self`,
/// and *k* is the complexity of iterating over all elements in `other`.
@inlinable
public __consuming func intersection<S: Sequence>(
public func intersection<S: Sequence>(
_ other: __owned S
) -> Self
where S.Element == Int
{
if S.self == Self.self {
return intersection(other as! BitSet)
}
if S.self == Range<Int>.self {
return intersection(other as! Range<Int>)
}
// Note: BitSet & BitSet.Counted are handled in the BitSet initializer below
return intersection(BitSet(_validMembersOf: other))
}
/// Returns a new bit set with the elements that are common to both this set
/// and the given range of integers.
///
/// let a: BitSet = [1, 2, 3, 4]
/// let c = a.intersection(-10 ..< 3)
/// // c is now [3, 4]
///
/// - Parameter other: A range of integers.
///
/// - Complexity: O(*max*) + *k*, where *max* is the largest item in `self`,
/// and *k* is the complexity of iterating over all elements in `other`.
public __consuming func intersection(_ other: Range<Int>) -> Self {
var result = self
result.formIntersection(other)
return result
}
}
@@ -22,6 +22,15 @@ extension BitSet {
self._storage == other._storage
}
/// Returns a Boolean value indicating whether a bit set is equal to a counted
/// bit set, i.e., whether they contain the same values.
///
/// - Complexity: O(*max*), where *max* is value of the largest member of
/// either set.
public func isEqual(to other: BitSet.Counted) -> Bool {
self.isEqual(to: other._bits)
}
/// Returns a Boolean value indicating whether a bit set is equal to a range
/// of integers, i.e., whether they contain the same values.
///
@@ -32,14 +41,6 @@ extension BitSet {
return _read { $0.isEqual(to: other) }
}
/// Returns a Boolean value indicating whether a bit set is equal to a counted
/// bit set, i.e., whether they contain the same values.
///
/// - Complexity: O(*max*), where *max* is
public func isEqual(to other: BitSet.Counted) -> Bool {
self.isEqual(to: other._bits)
}
/// Returns a Boolean value indicating whether this bit set contains the same
/// elements as the given `other` sequence.
///
@@ -31,12 +31,40 @@ extension BitSet {
}
}
/// Removes the elements of the given bit set from this set.
///
/// var set: BitSet = [1, 2, 3, 4]
/// let other: BitSet.Counted = [0, 2, 4, 6]
/// set.subtract(other)
/// // set is now [1, 3]
///
/// - Parameter other: Another bit set.
///
/// - Complexity: O(*max*), where *max* is the largest item in either input.
public mutating func subtract(_ other: BitSet.Counted) {
subtract(other._bits)
}
/// Removes the elements of the given range of integers from this set.
///
/// var set: BitSet = [1, 2, 3, 4]
/// set.subtract(-10 ..< 3)
/// // set is now [3, 4]
///
/// - Parameter other: A range of arbitrary integers.
///
/// - Returns: A new set.
///
/// - Complexity: O(*max*), where *max* is the largest item in self.
public mutating func subtract(_ other: Range<Int>) {
_subtract(other._clampedToUInt())
}
@usableFromInline
internal mutating func _subtract(_ next: () -> UInt?) {
internal mutating func _subtract(_ other: Range<UInt>) {
guard !other.isEmpty else { return }
_updateThenShrink { handle, shrink in
while let value = next() {
handle.remove(value)
}
handle.subtract(other)
}
}
@@ -53,7 +81,7 @@ extension BitSet {
/// and *k* is the complexity of iterating over all elements in `other`.
@inlinable
public mutating func subtract<S: Sequence>(
_ other: __owned S
_ other: S
) where S.Element == Int {
if S.self == BitSet.self {
self.subtract(other as! BitSet)
@@ -78,30 +106,12 @@ extension BitSet {
}
}
public mutating func subtract(_ other: BitSet.Counted) {
subtract(other._bits)
}
@usableFromInline
internal mutating func _subtract(_ other: Range<UInt>) {
guard !other.isEmpty else { return }
internal mutating func _subtract(_ next: () -> UInt?) {
_updateThenShrink { handle, shrink in
handle.subtract(other)
while let value = next() {
handle.remove(value)
}
}
}
/// Removes the elements of the given range of integers from this set.
///
/// var set: BitSet = [1, 2, 3, 4]
/// set.subtract(-10 ..< 3)
/// // set is now [3, 4]
///
/// - Parameter other: A range of arbitrary integers.
///
/// - Returns: A new set.
///
/// - Complexity: O(*max*), where *max* is the largest item in self.
public mutating func subtract(_ other: Range<Int>) {
_subtract(other._clampedToUInt())
}
}
@@ -22,7 +22,7 @@ extension BitSet {
/// - Returns: A new set.
///
/// - Complexity: O(*max*), where *max* is the largest item in either input.
public __consuming func subtracting(_ other: Self) -> Self {
public func subtracting(_ other: Self) -> Self {
self._read { first in
other._read { second in
Self(
@@ -33,6 +33,39 @@ extension BitSet {
}
}
/// Returns a new set containing the elements of this set that do not occur
/// in the given other set.
///
/// let set: BitSet = [1, 2, 3, 4]
/// let other: BitSet.Counted = [0, 2, 4, 6]
/// set.subtracting(other) // [1, 3]
///
/// - Parameter other: Another bit set.
///
/// - Returns: A new set.
///
/// - Complexity: O(*max*), where *max* is the largest item in either input.
public func subtracting(_ other: BitSet.Counted) -> Self {
subtracting(other._bits)
}
/// Returns a new set containing the elements of this set that do not occur
/// in the given range of integers.
///
/// let set: BitSet = [1, 2, 3, 4]
/// set.subtracting(-10 ..< 3) // [3, 4]
///
/// - Parameter other: A range of arbitrary integers.
///
/// - Returns: A new set.
///
/// - Complexity: O(*max*), where *max* is the largest item in self.
public func subtracting(_ other: Range<Int>) -> Self {
var result = self
result.subtract(other)
return result
}
/// Returns a new set containing the elements of this set that do not occur
/// in the given sequence of integers.
///
@@ -47,7 +80,7 @@ extension BitSet {
/// - Complexity: O(*max*) + *k*, where *max* is the largest item in `self`,
/// and *k* is the complexity of iterating over all elements in `other`.
@inlinable
public __consuming func subtracting<S: Sequence>(
public func subtracting<S: Sequence>(
_ other: __owned S
) -> Self
where S.Element == Int
@@ -56,25 +89,4 @@ extension BitSet {
result.subtract(other)
return result
}
public __consuming func subtracting(_ other: BitSet.Counted) -> Self {
subtracting(other._bits)
}
/// Returns a new set containing the elements of this set that do not occur
/// in the given range of integers.
///
/// let set: BitSet = [1, 2, 3, 4]
/// set.subtracting(-10 ..< 3) // [3, 4]
///
/// - Parameter other: A range of arbitrary integers.
///
/// - Returns: A new set.
///
/// - Complexity: O(*max*), where *max* is the largest item in self.
public __consuming func subtracting(_ other: Range<Int>) -> Self {
var result = self
result.subtract(other)
return result
}
}
@@ -22,7 +22,7 @@ extension BitSet {
/// - Returns: A new set.
///
/// - Complexity: O(*max*), where *max* is the largest item in either set.
public __consuming func symmetricDifference(_ other: __owned Self) -> Self {
public func symmetricDifference(_ other: Self) -> Self {
self._read { first in
other._read { second in
Self(
@@ -33,6 +33,39 @@ extension BitSet {
}
}
/// Returns a new bit set with the elements that are either in this set or in
/// `other`, but not in both.
///
/// let set: BitSet = [1, 2, 3, 4]
/// let other: BitSet.Counted = [6, 4, 2, 0]
/// set.symmetricDifference(other) // [0, 1, 3, 6]
///
/// - Parameter other: Another set.
///
/// - Returns: A new set.
///
/// - Complexity: O(*max*), where *max* is the largest item in either set.
public func symmetricDifference(_ other: Counted) -> Self {
symmetricDifference(other._bits)
}
/// Returns a new bit set with the elements that are either in this set or in
/// `other`, but not in both.
///
/// let set: BitSet = [1, 2, 3, 4]
/// set.formSymmetricDifference(3 ..< 7) // [1, 2, 5, 6]
///
/// - Parameter other: A range of nonnegative integers.
///
/// - Returns: A new set.
///
/// - Complexity: O(*max*), where *max* is the largest item in either input.
public func symmetricDifference(_ other: Range<Int>) -> Self {
var result = self
result.formSymmetricDifference(other)
return result
}
/// Returns a new bit set with the elements that are either in this set or in
/// `other`, but not in both.
///
@@ -46,7 +79,7 @@ extension BitSet {
/// input, and *k* is the complexity of iterating over all elements in
/// `other`.
@inlinable
public __consuming func symmetricDifference<S: Sequence>(
public func symmetricDifference<S: Sequence>(
_ other: __owned S
) -> Self
where S.Element == Int
@@ -54,23 +87,7 @@ extension BitSet {
if S.self == Range<Int>.self {
return symmetricDifference(other as! Range<Int>)
}
// Note: BitSet & BitSet.Counted are handled in the BitSet initializer below
return symmetricDifference(BitSet(other))
}
/// Returns a new bit set with the elements that are either in this set or in
/// `other`, but not in both.
///
/// let set: BitSet = [1, 2, 3, 4]
/// set.formSymmetricDifference(3 ..< 7) // [1, 2, 5, 6]
///
/// - Parameter other: A range of nonnegative integers.
///
/// - Returns: A new set.
///
/// - Complexity: O(*max*), where *max* is the largest item in either input.
public __consuming func symmetricDifference(_ other: Range<Int>) -> Self {
var result = self
result.formSymmetricDifference(other)
return result
}
}
@@ -19,7 +19,7 @@ extension BitSet {
/// - Parameter other: The set of elements to insert.
///
/// - Complexity: O(*max*), where *max* is the largest item in either input.
public __consuming func union(_ other: __owned Self) -> Self {
public func union(_ other: Self) -> Self {
self._read { first in
other._read { second in
Self(
@@ -30,6 +30,34 @@ extension BitSet {
}
}
/// Returns a new set with the elements of both this and the given set.
///
/// let set: BitSet = [1, 2, 3, 4]
/// let other: BitSet = [0, 2, 4, 6]
/// set.union(other) // [0, 1, 2, 3, 4, 6]
///
/// - Parameter other: The set of elements to insert.
///
/// - Complexity: O(*max*), where *max* is the largest item in either input.
public func union(_ other: BitSet.Counted) -> Self {
union(other._bits)
}
/// Returns a new set with the elements of both this set and the given
/// range of integers.
///
/// let set: BitSet = [1, 2, 3, 4]
/// set.union(3 ..< 7) // [1, 2, 3, 4, 5, 6]
///
/// - Parameter other: A range of nonnegative integers.
///
/// - Complexity: O(*max*), where *max* is the largest item in either input.
public func union(_ other: Range<Int>) -> Self {
var result = self
result.formUnion(other)
return result
}
/// Returns a new set with the elements of both this set and the given
/// sequence of integers.
///
@@ -43,7 +71,7 @@ extension BitSet {
/// input, and *k* is the complexity of iterating over all elements in
/// `other`.
@inlinable
public __consuming func union<S: Sequence>(
public func union<S: Sequence>(
_ other: __owned S
) -> Self
where S.Element == Int
@@ -61,23 +89,4 @@ extension BitSet {
result.formUnion(other)
return result
}
public __consuming func union(_ other: __owned BitSet.Counted) -> Self {
union(other._bits)
}
/// Returns a new set with the elements of both this set and the given
/// range of integers.
///
/// let set: BitSet = [1, 2, 3, 4]
/// set.union(3 ..< 7) // [1, 2, 3, 4, 5, 6]
///
/// - Parameter other: A range of nonnegative integers.
///
/// - Complexity: O(*max*), where *max* is the largest item in either input.
public __consuming func union(_ other: Range<Int>) -> Self {
var result = self
result.formUnion(other)
return result
}
}
File diff suppressed because it is too large. Load diff
@@ -50,6 +50,13 @@ extension BitSet.Index: CustomStringConvertible {
}
}
extension BitSet.Index: CustomDebugStringConvertible {
// A textual representation of this instance, suitable for debugging.
public var debugDescription: String {
"BitSet.Index(\(_value))"
}
}
extension BitSet.Index: Equatable {
/// Returns a Boolean value indicating whether two values are equal.
///
+1
View File
@@ -56,6 +56,7 @@ add_library(BitCollections
"BitSet/BitSet+SetAlgebra subtracting.swift"
"BitSet/BitSet+SetAlgebra symmetricDifference.swift"
"BitSet/BitSet+SetAlgebra union.swift"
"BitSet/BitSet+Sorted Collection APIs.swift"
"BitSet/BitSet.Counted.swift"
"BitSet/BitSet.Index.swift"
"BitSet/BitSet._UnsafeHandle.swift"
+1 -1
View File
@@ -7,8 +7,8 @@ Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
#]]
add_subdirectory(Collections)
add_subdirectory(BitCollections)
add_subdirectory(Collections)
add_subdirectory(DequeModule)
add_subdirectory(HeapModule)
add_subdirectory(OrderedCollections)
+1 -1
View File
@@ -8,7 +8,7 @@ See https://swift.org/LICENSE.txt for license information
#]]
add_library(Collections
Collections.swift)
"Collections.swift")
target_link_libraries(Collections PRIVATE
BitCollections
DequeModule
@@ -0,0 +1,38 @@
# ``Collections``
**Swift Collections** is an open-source package of data structure implementations for the Swift programming language.
## Overview
#### Additional Resources
- [`Swift Collections` on GitHub](https://github.com/apple/swift-collections/)
- [`Swift Collections` on the Swift Forums](https://forums.swift.org/c/related-projects/collections/72)
## Topics
### Bit Collections
- ``BitSet``
- ``BitArray``
### Deque Module
- ``Deque``
### Heap Module
- ``Heap``
### Ordered Collections
- ``OrderedSet``
- ``OrderedDictionary``
### Persistent Collections
- ``PersistentSet``
- ``PersistentDictionary``
@@ -0,0 +1,73 @@
# ``Collections/BitArray``
<!-- DO NOT EDIT THIS FILE; IT'S AUTOMATICALLY GENERATED -->
<!-- Summary -->
<!-- ## Overview -->
## Topics
### Creating a Bit Array
- ``init()``
- ``init(_:)-2y0wv``
- ``init(repeating:count:)-4j5yd``
- ``init(_:)-6ldyw``
- ``init(_:)-4tksd``
- ``init(_:)-765d2``
- ``init(bitPattern:)``
- ``random(count:)``
- ``random(count:using:)``
### Accessing Elements
- ``subscript(_:)-51ccj``
- ``subscript(_:)-944vg``
- ``first``
- ``last``
### Adding Elements
- ``append(_:)``
- ``append(contentsOf:)-18dwf``
- ``append(contentsOf:)-576q4``
- ``append(contentsOf:)-8xkr8``
- ``insert(_:at:)``
- ``insert(contentsOf:at:)-7e1xn``
- ``insert(contentsOf:at:)-35dp3``
- ``insert(contentsOf:at:)-1wsgw``
- ``truncateOrExtend(toCount:with:)``
### Removing Elements
- ``remove(at:)-7ij12``
- ``removeAll(keepingCapacity:)-5tkge``
- ``removeAll(where:)-7tv7z``
- ``removeSubrange(_:)-86ou8``
- ``removeSubrange(_:)-18qe7``
- ``removeLast()``
- ``removeLast(_:)``
- ``removeFirst()``
- ``removeFirst(_:)``
- ``popLast()``
### Replacing Elements
- ``fill(in:with:)``
- ``fill(with:)``
- ``replaceSubrange(_:with:)-163u2``
- ``replaceSubrange(_:with:)-875d8``
- ``replaceSubrange(_:with:)-2i7lu``
- ``replaceSubrange(_:with:)-b5ou``
### Bitwise Operators
- ``&(_:_:)``
- ``_(_:_:)-1rhw``
- ``_(_:_:)-56s54``
- ``~(_:)``
- ``&=(_:_:)``
- ``_=(_:_:)-69yf0``
- ``_=(_:_:)-icef``
@@ -0,0 +1,128 @@
# ``Collections/BitSet/Counted-swift.struct``
<!-- DO NOT EDIT THIS FILE; IT'S AUTOMATICALLY GENERATED -->
<!-- Summary -->
<!-- ## Overview -->
## Topics
### Collection Views
- ``uncounted``
### Creating a Set
- ``init()``
- ``init(reservingCapacity:)``
- ``init(_:)-15cws``
- ``init(_:)-38hho``
- ``init(_:)-2of3i``
- ``init(_:)-5fhls``
- ``init(bitPattern:)``
- ``init(words:)``
- ``random(upTo:)``
- ``random(upTo:using:)``
### Finding Elements
- ``contains(_:)``
- ``firstIndex(of:)``
- ``lastIndex(of:)``
### Adding and Updating Elements
- ``insert(_:)``
- ``update(with:)``
### Removing Elements
- ``filter(_:)``
- ``remove(_:)``
- ``remove(at:)``
### Sorted Set Operations
- ``subscript(member:)``
- ``subscript(members:)-5nkxk``
- ``subscript(members:)-5xfq5``
- ``min()``
- ``max()``
- ``sorted()``
### Binary Set Operations
- ``intersection(_:)-1wfb5``
- ``intersection(_:)-4evdp``
- ``intersection(_:)-9rtcc``
- ``intersection(_:)-13us``
- ``union(_:)-2okwt``
- ``union(_:)-pwqf``
- ``union(_:)-18u31``
- ``union(_:)-8ysz9``
- ``subtracting(_:)-7u4tf``
- ``subtracting(_:)-5vgml``
- ``subtracting(_:)-6scy1``
- ``subtracting(_:)-82loi``
- ``symmetricDifference(_:)-84e40``
- ``symmetricDifference(_:)-3suo3``
- ``symmetricDifference(_:)-7zx5q``
- ``symmetricDifference(_:)-46ni1``
- ``formIntersection(_:)-49and``
- ``formIntersection(_:)-49a0x``
- ``formIntersection(_:)-79anv``
- ``formIntersection(_:)-3zoc4``
- ``formUnion(_:)-c6a3``
- ``formUnion(_:)-c5kv``
- ``formUnion(_:)-2f05x``
- ``formUnion(_:)-8kilf``
- ``subtract(_:)-2hzty``
- ``subtract(_:)-2i1qq``
- ``subtract(_:)-32jtb``
- ``subtract(_:)-75xgt``
- ``formSymmetricDifference(_:)-6vskl``
- ``formSymmetricDifference(_:)-6vs05``
- ``formSymmetricDifference(_:)-d2kd``
- ``formSymmetricDifference(_:)-54ghn``
### Binary Set Predicates
- ``==(_:_:)``
- ``isEqual(to:)-5bw9h``
- ``isEqual(to:)-8jxq5``
- ``isEqual(to:)-7w9qy``
- ``isEqual(to:)-9tnfo``
- ``isSubset(of:)-8iy8c``
- ``isSubset(of:)-1r41b``
- ``isSubset(of:)-1dz0p``
- ``isSubset(of:)-3bq5m``
- ``isSuperset(of:)-48i5c``
- ``isSuperset(of:)-10gu8``
- ``isSuperset(of:)-8b7lq``
- ``isSuperset(of:)-6slai``
- ``isStrictSubset(of:)-5ry1b``
- ``isStrictSubset(of:)-2ndu3``
- ``isStrictSubset(of:)-9iul0``
- ``isStrictSubset(of:)-2pq1j``
- ``isStrictSuperset(of:)-9mgmd``
- ``isStrictSuperset(of:)-6hw4t``
- ``isStrictSuperset(of:)-1ya0j``
- ``isStrictSuperset(of:)-4qt1e``
- ``isDisjoint(with:)-9wyku``
- ``isDisjoint(with:)-5fww0``
- ``isDisjoint(with:)-6p0t7``
- ``isDisjoint(with:)-eujj``
@@ -0,0 +1,133 @@
# ``Collections/BitSet``
<!-- DO NOT EDIT THIS FILE; IT'S AUTOMATICALLY GENERATED -->
<!-- Summary -->
<!-- ## Overview -->
## Topics
### Collection Views
- ``Counted-swift.struct``
- ``counted-swift.property``
### Creating a Set
- ``init()``
- ``init(reservingCapacity:)``
- ``init(_:)-15cws``
- ``init(_:)-38hho``
- ``init(_:)-2of3i``
- ``init(_:)-5fhls``
- ``init(bitPattern:)``
- ``init(words:)``
- ``random(upTo:)``
- ``random(upTo:using:)``
### Finding Elements
- ``contains(_:)``
- ``firstIndex(of:)``
- ``lastIndex(of:)``
### Adding and Updating Elements
- ``insert(_:)``
- ``update(with:)``
### Removing Elements
- ``filter(_:)``
- ``remove(_:)``
- ``remove(at:)``
### Sorted Set Operations
- ``subscript(member:)``
- ``subscript(members:)-5nkxk``
- ``subscript(members:)-5xfq5``
- ``min()``
- ``max()``
- ``sorted()``
### Combining Sets
- ``intersection(_:)-84q4u``
- ``intersection(_:)-8hcl9``
- ``intersection(_:)-7l8p3``
- ``intersection(_:)-7kgi``
- ``union(_:)-5kqmx``
- ``union(_:)-6mj8``
- ``union(_:)-50wc4``
- ``union(_:)-10had``
- ``subtracting(_:)-79e0o``
- ``subtracting(_:)-7re82``
- ``subtracting(_:)-7rn26``
- ``subtracting(_:)-42s7d``
- ``symmetricDifference(_:)-55kqn``
- ``symmetricDifference(_:)-5xt65``
- ``symmetricDifference(_:)-91kh8``
- ``symmetricDifference(_:)-79wfx``
- ``formIntersection(_:)-u07v``
- ``formIntersection(_:)-87gjl``
- ``formIntersection(_:)-9gffv``
- ``formIntersection(_:)-8t2je``
- ``formUnion(_:)-72o7q``
- ``formUnion(_:)-370hb``
- ``formUnion(_:)-7tw8j``
- ``formUnion(_:)-12ll3``
- ``subtract(_:)-9aabm``
- ``subtract(_:)-1o083``
- ``subtract(_:)-6kijg``
- ``subtract(_:)-3pynh``
- ``formSymmetricDifference(_:)-2le2k``
- ``formSymmetricDifference(_:)-5edyr``
- ``formSymmetricDifference(_:)-7wole``
- ``formSymmetricDifference(_:)-8vcnf``
### Comparing Sets
- ``==(_:_:)``
- ``isEqual(to:)-5zfpo``
- ``isEqual(to:)-93d52``
- ``isEqual(to:)-542zl``
- ``isEqual(to:)-1d66i``
- ``isSubset(of:)-73apg``
- ``isSubset(of:)-14xt1``
- ``isSubset(of:)-4mj71``
- ``isSubset(of:)-20wxs``
- ``isSuperset(of:)-1mfg2``
- ``isSuperset(of:)-5adir``
- ``isSuperset(of:)-4y68t``
- ``isSuperset(of:)-2m7mj``
- ``isStrictSubset(of:)-8m1z6``
- ``isStrictSubset(of:)-3y2l1``
- ``isStrictSubset(of:)-97rky``
- ``isStrictSubset(of:)-p3zj``
- ``isStrictSuperset(of:)-6e5gm``
- ``isStrictSuperset(of:)-735zn``
- ``isStrictSuperset(of:)-26acy``
- ``isStrictSuperset(of:)-5jmxx``
- ``isDisjoint(with:)-2cdg6``
- ``isDisjoint(with:)-3klxy``
- ``isDisjoint(with:)-4uidy``
- ``isDisjoint(with:)-78a8w``
### Memory Management
- ``reserveCapacity(_:)``
@@ -0,0 +1,10 @@
# ``Collections/Deque``
<!-- DO NOT EDIT THIS FILE; IT'S AUTOMATICALLY GENERATED -->
<!-- Summary -->
<!-- ## Overview -->
## Topics
@@ -0,0 +1,10 @@
# ``Collections/Heap``
<!-- DO NOT EDIT THIS FILE; IT'S AUTOMATICALLY GENERATED -->
<!-- Summary -->
<!-- ## Overview -->
## Topics
@@ -0,0 +1,65 @@
# ``Collections/OrderedSet/UnorderedView``
<!-- DO NOT EDIT THIS FILE; IT'S AUTOMATICALLY GENERATED -->
<!-- Summary -->
<!-- ## Overview -->
## Topics
### Binary Set Operations
- ``intersection(_:)-3q45l``
- ``intersection(_:)-6ee3o``
- ``union(_:)-79uk3``
- ``union(_:)-23dm1``
- ``subtracting(_:)-3ct1b``
- ``subtracting(_:)-8e6mw``
- ``symmetricDifference(_:)-6aed7``
- ``symmetricDifference(_:)-7r79p``
- ``formIntersection(_:)-4ow38``
- ``formIntersection(_:)-80iht``
- ``formUnion(_:)-6ijb``
- ``formUnion(_:)-8tuol``
- ``subtract(_:)-627eq``
- ``subtract(_:)-4pjhu``
- ``formSymmetricDifference(_:)-8pkt5``
- ``formSymmetricDifference(_:)-75z52``
### Binary Set Predicates
- ``==(_:_:)``
- ``isSubset(of:)-n4t7``
- ``isSubset(of:)-2dx31``
- ``isSubset(of:)-801lo``
- ``isSubset(of:)-952h5``
- ``isSuperset(of:)-4ea6h``
- ``isSuperset(of:)-9t33p``
- ``isSuperset(of:)-2vtig``
- ``isSuperset(of:)-9krpz``
- ``isStrictSubset(of:)-33z0l``
- ``isStrictSubset(of:)-9o6mg``
- ``isStrictSubset(of:)-91par``
- ``isStrictSubset(of:)-7n66e``
- ``isStrictSuperset(of:)-8pbce``
- ``isStrictSuperset(of:)-89ig3``
- ``isStrictSuperset(of:)-1e0xt``
- ``isStrictSuperset(of:)-5dsfd``
- ``isDisjoint(with:)-7sbsg``
- ``isDisjoint(with:)-3wuso``
- ``isDisjoint(with:)-25vmx``
- ``isDisjoint(with:)-8nfqs``
@@ -0,0 +1,143 @@
# ``Collections/OrderedSet``
<!-- DO NOT EDIT THIS FILE; IT'S AUTOMATICALLY GENERATED -->
<!-- Summary -->
<!-- ## Overview -->
## Topics
### Creating a Set
- ``init()``
- ``init(_:)-5zktd``
- ``init(_:)-3d7qr``
- ``init(_:)-68j7``
- ``init(_:)-8zm9d``
- ``init(_:)-7rt2h``
- ``init(_:)-8tli8``
- ``init(_:)-2d3a9``
- ``init(uncheckedUniqueElements:)``
- ``init(minimumCapacity:persistent:)``
### Collection Views
- ``UnorderedView``
- ``unordered``
- ``elements``
### Finding Elements
- ``contains(_:)``
- ``firstIndex(of:)``
- ``lastIndex(of:)``
### Adding and Updating Elements
- ``append(_:)``
- ``append(contentsOf:)``
- ``insert(_:at:)``
- ``updateOrAppend(_:)``
- ``updateOrInsert(_:at:)``
- ``update(_:at:)``
### Removing Elements
- ``filter(_:)``
- ``removeAll(where:)``
- ``remove(_:)``
- ``remove(at:)``
- ``removeAll(keepingCapacity:)``
- ``removeFirst()``
- ``removeLast()``
- ``removeFirst(_:)``
- ``removeLast(_:)``
- ``removeSubrange(_:)-62u6a``
- ``removeSubrange(_:)-2fqke``
### Combining Sets
- ``intersection(_:)-4o09a``
- ``intersection(_:)-9yzg3``
- ``intersection(_:)-80md4``
- ``union(_:)-67y2h``
- ``union(_:)-3lt5i``
- ``union(_:)-2939h``
- ``subtracting(_:)-5graf``
- ``subtracting(_:)-7kl8r``
- ``subtracting(_:)-1gl4y``
- ``symmetricDifference(_:)-1810l``
- ``symmetricDifference(_:)-8dvm6``
- ``symmetricDifference(_:)-9huk7``
- ``formIntersection(_:)-43o1u``
- ``formIntersection(_:)-2a4y4``
- ``formIntersection(_:)-7odn2``
- ``formUnion(_:)-6pksr``
- ``formUnion(_:)-3dkzw``
- ``formUnion(_:)-59end``
- ``subtract(_:)-3b6nj``
- ``subtract(_:)-9rtmd``
- ``subtract(_:)-9wmg8``
- ``formSymmetricDifference(_:)-96csi``
- ``formSymmetricDifference(_:)-2ll2z``
- ``formSymmetricDifference(_:)-391sm``
### Comparing Sets
- ``==(_:_:)``
- ``isEqual(to:)-69p52``
- ``isEqual(to:)-1xzfo``
- ``isEqual(to:)-3ab2q``
- ``isSubset(of:)-ptij``
- ``isSubset(of:)-3mw6r``
- ``isSubset(of:)-8yb29``
- ``isSubset(of:)-9hxl4``
- ``isSuperset(of:)-4rrsh``
- ``isSuperset(of:)-2bbv8``
- ``isSuperset(of:)-7xvog``
- ``isSuperset(of:)-7oow7``
- ``isStrictSubset(of:)-8m21h``
- ``isStrictSubset(of:)-9lv3x``
- ``isStrictSubset(of:)-4efhn``
- ``isStrictSubset(of:)-10abw``
- ``isStrictSuperset(of:)-7u97x``
- ``isStrictSuperset(of:)-3kfwa``
- ``isStrictSuperset(of:)-98d9s``
- ``isStrictSuperset(of:)-5e6d5``
- ``isDisjoint(with:)-6vmoh``
- ``isDisjoint(with:)-4tsmx``
- ``isDisjoint(with:)-54iy6``
- ``isDisjoint(with:)-7nqur``
### Reordering Elements
- ``swapAt(_:_:)``
- ``sort()``
- ``sort(by:)``
- ``reverse()``
- ``shuffle()``
- ``shuffle(using:)``
- ``partition(by:)``
### Creating and Applying Differences
- ``difference(from:)``
- ``applying(_:)``
### Memory Management
- ``reserveCapacity(_:)``
@@ -0,0 +1,75 @@
# ``Collections/PersistentDictionary``
<!-- DO NOT EDIT THIS FILE; IT'S AUTOMATICALLY GENERATED -->
<!-- Summary -->
<!-- ## Overview -->
## Topics
### Collection Views
- ``Keys-swift.struct``
- ``Values-swift.struct``
- ``keys-swift.property``
- ``values-swift.property``
### Creating a Dictionary
- ``init()``
- ``init(_:)-7jshe``
- ``init(_:)-8ls8p``
- ``init(uniqueKeysWithValues:)-65ax0``
- ``init(uniqueKeysWithValues:)-5ok18``
- ``init(_:uniquingKeysWith:)-7fuzu``
- ``init(_:uniquingKeysWith:)-4jee3``
- ``init(grouping:by:)-8ntzv``
- ``init(grouping:by:)-7cu86``
- ``init(keys:valueGenerator:)``
### Inspecting a Dictionary
- ``isEmpty-65s43``
- ``count-9cdqd``
### Accessing Keys and Values
- ``subscript(_:)-g0oi``
- ``subscript(_:default:)``
- ``index(forKey:)``
### Adding or Updating Keys and Values
- ``updateValue(_:forKey:)``
- ``updateValue(forKey:with:)``
- ``updateValue(forKey:default:with:)``
- ``merge(_:uniquingKeysWith:)-853bf``
- ``merge(_:uniquingKeysWith:)-19xxn``
- ``merge(_:uniquingKeysWith:)-2osh``
- ``merging(_:uniquingKeysWith:)-2a7cl``
- ``merging(_:uniquingKeysWith:)-1tq3e``
- ``merging(_:uniquingKeysWith:)-2kjqq``
### Removing Keys and Values
- ``removeValue(forKey:)``
- ``remove(at:)``
### Non-mutating Dictionary Operations
- ``updatingValue(_:forKey:)``
- ``removingValue(forKey:)``
### Comparing Dictionaries
- ``==(_:_:)``
### Transforming a Dictionary
- ``filter(_:)``
- ``mapValues(_:)``
- ``compactMapValues(_:)``
@@ -0,0 +1,166 @@
# ``Collections/PersistentSet``
<!-- DO NOT EDIT THIS FILE; IT'S AUTOMATICALLY GENERATED -->
### Implementation Details
`PersistentSet` and `PersistentDictionary` are based on a Swift adaptation
of the *Compressed Hash-Array Mapped Prefix Tree* (CHAMP) data structure.
- Michael J Steindorfer and Jurgen J Vinju. Optimizing Hash-Array Mapped
Tries for Fast and Lean Immutable JVM Collections. In *Proc.
International Conference on Object-Oriented Programming, Systems,
Languages, and Applications,* pp. 783-800, 2015.
https://doi.org/10.1145/2814270.2814312
In this setup, the members of such a collection are organized into a tree
data structure based on their hash values. For example, assuming 16 bit hash
values sliced into 4-bit chunks, each node in the prefix tree would have
sixteen slots (one for each digit), each of which may contain a member, a
child node reference, or it may be empty. A `PersistentSet` containing the
tree items `Maximo`, `Julia` and `Don Pablo` (with hash values of `0x2B65`,
`0xA69F` and `0xADA1`, respectively) may be organized into a prefix tree of
two nodes:
```
┌0┬1┬2───────┬3┬4┬5┬6┬7┬8┬9┬A──┬B┬C┬D┬E┬F┐
│ │ │ Maximo │ │ │ │ │ │ │ │ • │ │ │ │ │ │
└─┴─┴────────┴─┴─┴─┴─┴─┴─┴─┴─┼─┴─┴─┴─┴─┴─┘
╎
╎
┌0┬1┬2┬3┬4┬5┬6───┴──┬7┬8┬9┬A┬B┬C┬D──────────┬E┬F┐
│ │ │ │ │ │ │ Julia │ │ │ │ │ │ │ Don Pablo │ │ │
└─┴─┴─┴─┴─┴─┴───────┴─┴─┴─┴─┴─┴─┴───────────┴─┴─┘
```
The root node directly contains `Maximo`, because it is the only set member
whose hash value starts with `8`. However, the first digits of the hashes of
`Julia` and `Don Pablo` are both `A`, so these items reside in a separate
node, one level below the root.
(To save space, nodes are actually stored in a more compact form, with just
enough space allocated to store their contents: empty slots do not take up
any room. Hence the term "compressed" in "Compressed Hash-Array Mapped
Prefix Tree".)
The resulting tree structure lends itself well to sharing nodes across
multiple collection values. Inserting or removing an item in a completely
shared tree requires copying at most log(n) nodes -- every node along the
path to the item needs to be uniqued, but all other nodes can remain shared.
While the cost of copying this many nodes isn't trivial, it is dramatically
lower than the cost of having to copy the entire data structure, like the
standard `Set` has to do.
When looking up a particular member, we descend from the root node,
following along the path specified by successive digits of the member's hash
value. As long as hash values are unique, we will either find the member
we're looking for, or we will know for sure that it does not exist in the
set.
In practice, hash values aren't guaranteed to be unique though. Members with
conflicting hash values need to be collected in special collision nodes that
are able to grow as large as necessary to contain all colliding members that
share the same hash. Looking up a member in one of these nodes requires a
linear search, so it is crucial that such collisions do not happen often.
As long as `Element` properly implements `Hashable`, lookup operations in a
`PersistentSet` are expected to be able to decide whether the set contains a
particular item by looking at no more than a constant number of items on
average -- typically they will need to compare against just one member.
<!-- ## Overview -->
## Topics
### Creating a Set
- ``init()``
- ``init(_:)-6nn9e``
- ``init(_:)-6qbps``
- ``init(_:)-30nei``
### Finding Elements
- ``contains(_:)``
- ``firstIndex(of:)``
- ``lastIndex(of:)``
### Adding and Updating Elements
- ``insert(_:)``
- ``update(with:)``
- ``update(_:at:)``
### Removing Elements
- ``filter(_:)``
- ``remove(_:)``
- ``remove(at:)``
### Non-mutating Set Operations
- ``inserting(_:)``
- ``updating(with:)``
- ``removing(_:)``
### Combining Sets
- ``intersection(_:)-9dx2a``
- ``intersection(_:)-5z4my``
- ``intersection(_:)-1d4e0``
- ``union(_:)-1nk1t``
- ``union(_:)-8otnp``
- ``union(_:)-6eysm``
- ``subtracting(_:)-8sczx``
- ``subtracting(_:)-2iv0a``
- ``subtracting(_:)-63bfb``
- ``symmetricDifference(_:)-76bw``
- ``symmetricDifference(_:)-92ha9``
- ``symmetricDifference(_:)-1n89g``
- ``formIntersection(_:)-4s0od``
- ``formIntersection(_:)-7dqfx``
- ``formIntersection(_:)-8i59p``
- ``formUnion(_:)-68pog``
- ``formUnion(_:)-82rrc``
- ``formUnion(_:)-4r7qz``
- ``subtract(_:)-7rmd3``
- ``subtract(_:)-47r93``
- ``subtract(_:)-3v8ms``
- ``formSymmetricDifference(_:)-499uq``
- ``formSymmetricDifference(_:)-8wue8``
- ``formSymmetricDifference(_:)-4t8jr``
### Comparing Sets
- ``==(_:_:)``
- ``isEqual(to:)-3m3in``
- ``isEqual(to:)-7mkn1``
- ``isEqual(to:)-5px5r``
- ``isSubset(of:)-9mp7l``
- ``isSubset(of:)-2jlh``
- ``isSubset(of:)-8vn0j``
- ``isSuperset(of:)-5af8o``
- ``isSuperset(of:)-6mvxj``
- ``isSuperset(of:)-864jy``
- ``isStrictSubset(of:)-48nx2``
- ``isStrictSubset(of:)-2j680``
- ``isStrictSubset(of:)-1s6n9``
- ``isStrictSuperset(of:)-nd5j``
- ``isStrictSuperset(of:)-5z263``
- ``isStrictSuperset(of:)-ivbh``
- ``isDisjoint(with:)-12irx``
- ``isDisjoint(with:)-1hhyf``
- ``isDisjoint(with:)-61lde``
@@ -0,0 +1,8 @@
# ``DequeModule``
<!--@START_MENU_TOKEN@-->Summary<!--@END_MENU_TOKEN@-->
## Overview
<!--@START_MENU_TOKEN@-->Text<!--@END_MENU_TOKEN@-->
@@ -0,0 +1,7 @@
# ``DequeModule/Deque``
<!-- Summary -->
<!-- ## Overview -->
## Topics
+6 -5
View File
@@ -8,11 +8,12 @@ See https://swift.org/LICENSE.txt for license information
#]]
add_library(HeapModule
_Node.swift
Heap.swift
Heap+ExpressibleByArrayLiteral.swift
Heap+Invariants.swift
Heap+UnsafeHandle.swift)
"_Node.swift"
"Heap.swift"
"Heap+Descriptions.swift"
"Heap+ExpressibleByArrayLiteral.swift"
"Heap+Invariants.swift"
"Heap+UnsafeHandle.swift")
target_link_libraries(HeapModule PRIVATE
_CollectionsUtilities)
set_target_properties(HeapModule PROPERTIES
@@ -0,0 +1,25 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension Heap: CustomStringConvertible {
/// A textual representation of this instance.
public var description: String {
"Heap<\(Element.self)>(count: \(count))"
}
}
extension Heap: CustomDebugStringConvertible {
/// A textual representation of this instance, suitable for debugging.
public var debugDescription: String {
description
}
}
@@ -0,0 +1,7 @@
# ``HeapModule/Heap``
<!-- Summary -->
<!-- ## Overview -->
## Topics
@@ -0,0 +1,13 @@
# ``HeapModule``
<!--@START_MENU_TOKEN@-->Summary<!--@END_MENU_TOKEN@-->
## Overview
<!--@START_MENU_TOKEN@-->Text<!--@END_MENU_TOKEN@-->
## Topics
### Structures
- ``Heap``
+11 -4
View File
@@ -16,13 +16,13 @@ add_library(OrderedCollections
"HashTable/_Hashtable+Header.swift"
"HashTable/_HashTable+Testing.swift"
"HashTable/_HashTable+UnsafeHandle.swift"
"OrderedDictionary/OrderedDictionary.Elements.swift"
"OrderedDictionary/OrderedDictionary.swift"
"OrderedDictionary/OrderedDictionary+Codable.swift"
"OrderedDictionary/OrderedDictionary+CustomReflectable.swift"
"OrderedDictionary/OrderedDictionary+Deprecations.swift"
"OrderedDictionary/OrderedDictionary+Descriptions.swift"
"OrderedDictionary/OrderedDictionary+Elements+SubSequence.swift"
"OrderedDictionary/OrderedDictionary+Elements.SubSequence.swift"
"OrderedDictionary/OrderedDictionary+Elements.swift"
"OrderedDictionary/OrderedDictionary+Equatable.swift"
"OrderedDictionary/OrderedDictionary+ExpressibleByDictionaryLiteral.swift"
"OrderedDictionary/OrderedDictionary+Hashable.swift"
@@ -33,7 +33,6 @@ add_library(OrderedCollections
"OrderedDictionary/OrderedDictionary+Sendable.swift"
"OrderedDictionary/OrderedDictionary+Sequence.swift"
"OrderedDictionary/OrderedDictionary+Values.swift"
"OrderedSet/OrderedSet.swift"
"OrderedSet/OrderedSet+Codable.swift"
"OrderedSet/OrderedSet+CustomReflectable.swift"
"OrderedSet/OrderedSet+Descriptions.swift"
@@ -46,14 +45,21 @@ add_library(OrderedCollections
"OrderedSet/OrderedSet+Invariants.swift"
"OrderedSet/OrderedSet+Partial MutableCollection.swift"
"OrderedSet/OrderedSet+Partial RangeReplaceableCollection.swift"
"OrderedSet/OrderedSet+Partial SetAlgebra formIntersection.swift"
"OrderedSet/OrderedSet+Partial SetAlgebra formSymmetricDifference.swift"
"OrderedSet/OrderedSet+Partial SetAlgebra formUnion.swift"
"OrderedSet/OrderedSet+Partial SetAlgebra intersection.swift"
"OrderedSet/OrderedSet+Partial SetAlgebra isDisjoint.swift"
"OrderedSet/OrderedSet+Partial SetAlgebra isEqual.swift"
"OrderedSet/OrderedSet+Partial SetAlgebra isStrictSubset.swift"
"OrderedSet/OrderedSet+Partial SetAlgebra isStrictSuperset.swift"
"OrderedSet/OrderedSet+Partial SetAlgebra isSubset.swift"
"OrderedSet/OrderedSet+Partial SetAlgebra isSuperset.swift"
"OrderedSet/OrderedSet+Partial SetAlgebra subtract.swift"
"OrderedSet/OrderedSet+Partial SetAlgebra subtracting.swift"
"OrderedSet/OrderedSet+Partial SetAlgebra symmetricDifference.swift"
"OrderedSet/OrderedSet+Partial SetAlgebra union.swift"
"OrderedSet/OrderedSet+Partial SetAlgebra+Basics.swift"
"OrderedSet/OrderedSet+Partial SetAlgebra+Operations.swift"
"OrderedSet/OrderedSet+RandomAccessCollection.swift"
"OrderedSet/OrderedSet+ReserveCapacity.swift"
"OrderedSet/OrderedSet+Sendable.swift"
@@ -61,6 +67,7 @@ add_library(OrderedCollections
"OrderedSet/OrderedSet+Testing.swift"
"OrderedSet/OrderedSet+UnorderedView.swift"
"OrderedSet/OrderedSet+UnstableInternals.swift"
"OrderedSet/OrderedSet.swift"
"Utilities/_UnsafeBitset.swift"
)
target_link_libraries(OrderedCollections PRIVATE
@@ -10,6 +10,7 @@
//===----------------------------------------------------------------------===//
extension _HashTable.Bucket: CustomStringConvertible {
// A textual representation of this instance.
public var description: String { "Bucket(@\(offset))"}
}
@@ -0,0 +1,62 @@
# ``OrderedCollections/OrderedSet/UnorderedView``
<!-- Summary -->
<!-- ## Overview -->
## Topics
### Binary Set Operations
- ``intersection(_:)-3q45l``
- ``intersection(_:)-6ee3o``
- ``union(_:)-79uk3``
- ``union(_:)-23dm1``
- ``subtracting(_:)-3ct1b``
- ``subtracting(_:)-8e6mw``
- ``symmetricDifference(_:)-6aed7``
- ``symmetricDifference(_:)-7r79p``
- ``formIntersection(_:)-4ow38``
- ``formIntersection(_:)-80iht``
- ``formUnion(_:)-6ijb``
- ``formUnion(_:)-8tuol``
- ``subtract(_:)-627eq``
- ``subtract(_:)-4pjhu``
- ``formSymmetricDifference(_:)-8pkt5``
- ``formSymmetricDifference(_:)-75z52``
### Binary Set Predicates
- ``==(_:_:)``
- ``isSubset(of:)-n4t7``
- ``isSubset(of:)-2dx31``
- ``isSubset(of:)-801lo``
- ``isSubset(of:)-952h5``
- ``isSuperset(of:)-4ea6h``
- ``isSuperset(of:)-9t33p``
- ``isSuperset(of:)-2vtig``
- ``isSuperset(of:)-9krpz``
- ``isStrictSubset(of:)-33z0l``
- ``isStrictSubset(of:)-9o6mg``
- ``isStrictSubset(of:)-91par``
- ``isStrictSubset(of:)-7n66e``
- ``isStrictSuperset(of:)-8pbce``
- ``isStrictSuperset(of:)-89ig3``
- ``isStrictSuperset(of:)-1e0xt``
- ``isStrictSuperset(of:)-5dsfd``
- ``isDisjoint(with:)-7sbsg``
- ``isDisjoint(with:)-3wuso``
- ``isDisjoint(with:)-25vmx``
- ``isDisjoint(with:)-8nfqs``
@@ -0,0 +1,140 @@
# ``OrderedCollections/OrderedSet``
<!-- Summary -->
<!-- ## Overview -->
## Topics
### Creating a Set
- ``init()``
- ``init(_:)-5zktd``
- ``init(_:)-3d7qr``
- ``init(_:)-68j7``
- ``init(_:)-8zm9d``
- ``init(_:)-7rt2h``
- ``init(_:)-8tli8``
- ``init(_:)-2d3a9``
- ``init(uncheckedUniqueElements:)``
- ``init(minimumCapacity:persistent:)``
### Collection Views
- ``UnorderedView``
- ``unordered``
- ``elements``
### Finding Elements
- ``contains(_:)``
- ``firstIndex(of:)``
- ``lastIndex(of:)``
### Adding and Updating Elements
- ``append(_:)``
- ``append(contentsOf:)``
- ``insert(_:at:)``
- ``updateOrAppend(_:)``
- ``updateOrInsert(_:at:)``
- ``update(_:at:)``
### Removing Elements
- ``filter(_:)``
- ``removeAll(where:)``
- ``remove(_:)``
- ``remove(at:)``
- ``removeAll(keepingCapacity:)``
- ``removeFirst()``
- ``removeLast()``
- ``removeFirst(_:)``
- ``removeLast(_:)``
- ``removeSubrange(_:)-62u6a``
- ``removeSubrange(_:)-2fqke``
### Combining Sets
- ``intersection(_:)-4o09a``
- ``intersection(_:)-9yzg3``
- ``intersection(_:)-80md4``
- ``union(_:)-67y2h``
- ``union(_:)-3lt5i``
- ``union(_:)-2939h``
- ``subtracting(_:)-5graf``
- ``subtracting(_:)-7kl8r``
- ``subtracting(_:)-1gl4y``
- ``symmetricDifference(_:)-1810l``
- ``symmetricDifference(_:)-8dvm6``
- ``symmetricDifference(_:)-9huk7``
- ``formIntersection(_:)-43o1u``
- ``formIntersection(_:)-2a4y4``
- ``formIntersection(_:)-7odn2``
- ``formUnion(_:)-6pksr``
- ``formUnion(_:)-3dkzw``
- ``formUnion(_:)-59end``
- ``subtract(_:)-3b6nj``
- ``subtract(_:)-9rtmd``
- ``subtract(_:)-9wmg8``
- ``formSymmetricDifference(_:)-96csi``
- ``formSymmetricDifference(_:)-2ll2z``
- ``formSymmetricDifference(_:)-391sm``
### Comparing Sets
- ``==(_:_:)``
- ``isEqual(to:)-69p52``
- ``isEqual(to:)-1xzfo``
- ``isEqual(to:)-3ab2q``
- ``isSubset(of:)-ptij``
- ``isSubset(of:)-3mw6r``
- ``isSubset(of:)-8yb29``
- ``isSubset(of:)-9hxl4``
- ``isSuperset(of:)-4rrsh``
- ``isSuperset(of:)-2bbv8``
- ``isSuperset(of:)-7xvog``
- ``isSuperset(of:)-7oow7``
- ``isStrictSubset(of:)-8m21h``
- ``isStrictSubset(of:)-9lv3x``
- ``isStrictSubset(of:)-4efhn``
- ``isStrictSubset(of:)-10abw``
- ``isStrictSuperset(of:)-7u97x``
- ``isStrictSuperset(of:)-3kfwa``
- ``isStrictSuperset(of:)-98d9s``
- ``isStrictSuperset(of:)-5e6d5``
- ``isDisjoint(with:)-6vmoh``
- ``isDisjoint(with:)-4tsmx``
- ``isDisjoint(with:)-54iy6``
- ``isDisjoint(with:)-7nqur``
### Reordering Elements
- ``swapAt(_:_:)``
- ``sort()``
- ``sort(by:)``
- ``reverse()``
- ``shuffle()``
- ``shuffle(using:)``
- ``partition(by:)``
### Creating and Applying Differences
- ``difference(from:)``
- ``applying(_:)``
### Memory Management
- ``reserveCapacity(_:)``
@@ -0,0 +1,20 @@
# ``OrderedCollections``
**Swift Collections** is an open-source package of data structure implementations for the Swift programming language.
## Overview
#### Additional Resources
- [`Swift Collections` on GitHub](https://github.com/apple/swift-collections/)
- [`Swift Collections` on the Swift Forums](https://forums.swift.org/c/related-projects/collections/72)
## Topics
### Structures
- ``OrderedSet``
- ``OrderedDictionary``
@@ -22,10 +22,10 @@ extension OrderedDictionary: CustomDebugStringConvertible {
/// A textual representation of this instance, suitable for debugging.
public var debugDescription: String {
_dictionaryDescription(
for: self.elements, debug: true, typeName: _debugTypeName())
for: self.elements, debug: true, typeName: Self._debugTypeName())
}
internal func _debugTypeName() -> String {
internal static func _debugTypeName() -> String {
"OrderedDictionary<\(Key.self), \(Value.self)>"
}
}
@@ -9,6 +9,8 @@
//
//===----------------------------------------------------------------------===//
import _CollectionsUtilities
extension OrderedDictionary.Elements {
/// A collection that represents a contiguous slice of an ordered dictionary.
///
@@ -35,6 +37,24 @@ extension OrderedDictionary.Elements.SubSequence: Sendable
where Key: Sendable, Value: Sendable {}
#endif
extension OrderedDictionary.Elements.SubSequence: CustomStringConvertible {
// A textual representation of this instance.
public var description: String {
_dictionaryDescription(for: self)
}
}
extension OrderedDictionary.Elements.SubSequence: CustomDebugStringConvertible {
/// A textual representation of this instance, suitable for debugging.
public var debugDescription: String {
_dictionaryDescription(
for: self,
debug: true,
typeName: "\(OrderedDictionary._debugTypeName()).Elements.SubSequence"
)
}
}
extension OrderedDictionary.Elements.SubSequence {
/// A read-only collection view containing the keys in this slice.
///
@@ -333,12 +333,14 @@ extension OrderedDictionary.Elements: RandomAccessCollection {
}
extension OrderedDictionary.Elements: CustomStringConvertible {
// A textual representation of this instance.
public var description: String {
_base.description
}
}
extension OrderedDictionary.Elements: CustomDebugStringConvertible {
/// A textual representation of this instance, suitable for debugging.
public var debugDescription: String {
_dictionaryDescription(
for: self,
@@ -48,7 +48,7 @@ extension OrderedDictionary {
_values.removeAll(keepingCapacity: keepCapacity)
}
/// Removes and returns the element at the specified position.
/// Removes and returns the key-value pair at the specified index.
///
/// All the elements following the specified position are moved to close the
/// resulting gap.
@@ -9,6 +9,8 @@
//
//===----------------------------------------------------------------------===//
import _CollectionsUtilities
extension OrderedDictionary {
/// A view of an ordered dictionary's values as a standalone collection.
@frozen
@@ -29,6 +31,23 @@ extension OrderedDictionary.Values: Sendable
where Key: Sendable, Value: Sendable {}
#endif
extension OrderedDictionary.Values: CustomStringConvertible {
// A textual representation of this instance.
public var description: String {
_arrayDescription(for: self)
}
}
extension OrderedDictionary.Values: CustomDebugStringConvertible {
/// A textual representation of this instance, suitable for debugging.
public var debugDescription: String {
_arrayDescription(
for: self,
debug: true,
typeName: "OrderedDictionary<\(Key.self), \(Value.self)>.Keys")
}
}
extension OrderedDictionary.Values {
/// A read-only view of the contents of this collection as an array value.
///
@@ -79,7 +79,7 @@
///
/// If the `Value` type implements reference semantics, or when you need to
/// perform a series of individual mutations on the values, the closure-based
/// `updateValue(forKey:default:_:)` method provides an easier-to-use
/// ``updateValue(forKey:default:with:)`` method provides an easier-to-use
/// alternative to the defaulted key-based subscript.
///
/// let text = "short string"
@@ -93,13 +93,14 @@
///
/// (This isn't currently available on the regular `Dictionary`.)
///
/// The `Dictionary` type's original `updateValue(_:forKey:)` method is also
/// available, and so is `index(forKey:)`, grouping/uniquing initializers
/// (`init(uniqueKeysWithValues:)`, `init(_:uniquingKeysWith:)`,
/// `init(grouping:by:)`), methods for merging one dictionary with another
/// (`merge`, `merging`), filtering dictionary entries (`filter(_:)`),
/// transforming values (`mapValues(_:)`), and a combination of these two
/// (`compactMapValues(_:)`).
/// The `Dictionary` type's original ``updateValue(_:forKey:)`` method is also
/// available, and so is ``index(forKey:)``, grouping/uniquing initializers
/// (``init(uniqueKeysWithValues:)-5ux9r``, ``init(_:uniquingKeysWith:)-2y39b``,
/// ``init(grouping:by:)-6mahw``), methods for merging one dictionary with
/// another (``merge(_:uniquingKeysWith:)-6ka2i``,
/// ``merging(_:uniquingKeysWith:)-4z49c``), filtering dictionary entries
/// (``filter(_:)``), transforming values (``mapValues(_:)``), and a combination
/// of these two (``compactMapValues(_:)``).
///
/// ### Sequence and Collection Operations
///
@@ -114,53 +115,51 @@
///
/// Because ordered dictionaries need to maintain unique keys, neither
/// `OrderedDictionary` nor its `elements` view can conform to the full
/// `MutableCollection` or `RangeReplaceableCollection` protocols. However, they
/// are able to partially implement requirements: they support mutations
/// that merely change the order of elements, or just remove a subset of
/// existing members:
/// `MutableCollection` or `RangeReplaceableCollection` protocols.
///
/// // Permutation operations from MutableCollection:
/// func swapAt(_ i: Int, _ j: Int)
/// func partition(by predicate: (Element) throws -> Bool) -> rethrows Int
/// func sort() where Element: Comparable
/// func sort(by predicate: (Element, Element) throws -> Bool) rethrows
/// func shuffle()
/// func shuffle<T: RandomNumberGenerator>(using generator: inout T)
/// However, `OrderedDictioanr` is still able to implement some of the
/// requirements of these protocols. In particular, it supports permutation
/// operations from `MutableCollection`:
///
/// // Removal operations from RangeReplaceableCollection:
/// func removeAll(keepingCapacity: Bool = false)
/// func remove(at index: Int) -> Element
/// func removeSubrange(_ bounds: Range<Int>)
/// func removeLast() -> Element
/// func removeLast(_ n: Int)
/// func removeFirst() -> Element
/// func removeFirst(_ n: Int)
/// func removeAll(where shouldBeRemoved: (Element) throws -> Bool) rethrows
/// - ``swapAt(_:_:)``
/// - ``partition(by:)``
/// - ``sort()``, ``sort(by:)``
/// - ``shuffle()``, ``shuffle(using:)``
/// - ``reverse()``
///
/// `OrderedDictionary` also implements `reserveCapacity(_)` from
/// It also supports removal operations from `RangeReplaceableCollection`:
///
/// - ``removeAll(keepingCapacity:)``
/// - ``remove(at:)``
/// - ``removeSubrange(_:)-512n3``, ``removeSubrange(_:)-8rmzx``
/// - ``removeLast()``, ``removeLast(_:)``
/// - ``removeFirst()``, ``removeFirst(_:)``
/// - ``removeAll(where:)``
///
/// `OrderedDictionary` also implements ``reserveCapacity(_:)`` from
/// `RangeReplaceableCollection`, to allow for efficient insertion of a known
/// number of elements. (However, unlike `Array` and `Dictionary`,
/// `OrderedDictionary` does not provide a `capacity` property.)
///
/// ### Keys and Values Views
///
/// Like the standard `Dictionary`, `OrderedDictionary` provides `keys` and
/// `values` properties that provide lightweight views into the corresponding
/// parts of the dictionary.
/// Like the standard `Dictionary`, `OrderedDictionary` provides ``keys`` and
/// ``values-swift.property`` properties that provide lightweight views into
/// the corresponding parts of the dictionary.
///
/// The `keys` collection is of type `OrderedSet<Key>`, containing all the keys
/// The ``keys`` collection is of type ``OrderedSet``, containing all the keys
/// in the original dictionary.
///
/// let d: OrderedDictionary = [2: "two", 1: "one", 0: "zero"]
/// d.keys // [2, 1, 0] as OrderedSet<Int>
///
/// The `keys` property is read-only, so you cannot mutate the dictionary
/// The ``keys`` property is read-only, so you cannot mutate the dictionary
/// through it. However, it returns an ordinary ordered set value, which can be
/// copied out and then mutated if desired. (Such mutations won't affect the
/// original dictionary value.)
///
/// The `values` collection is a mutable random-access collection of the values
/// in the dictionary:
/// The ``values-swift.property`` collection is a mutable random-access
/// collection of the values in the dictionary:
///
/// d.values // "two", "one", "zero"
/// d.values[2] = "nada"
@@ -169,40 +168,37 @@
/// // `d` is now [2: "nada", 1: "one", 0: "two"]
///
/// Both views store their contents in regular `Array` values, accessible
/// through their `elements` property.
/// through their ``elements-swift.property`` property.
///
/// ## Performance
///
/// Like the standard `Dictionary` type, the performance of hashing operations
/// in `OrderedDictionary` is highly sensitive to the quality of hashing
/// implemented by the `Key` type. Failing to correctly implement hashing can
/// easily lead to unacceptable performance, with the severity of the effect
/// increasing with the size of the hash table.
///
/// In particular, if a certain set of keys all produce the same hash value,
/// then hash table lookups regress to searching an element in an unsorted
/// array, i.e., a linear operation. To ensure hashed collection types exhibit
/// their target performance, it is important to ensure that such collisions
/// cannot be induced merely by adding a particular list of keys to the
/// dictionary.
///
/// The easiest way to achieve this is to make sure `Key` implements hashing
/// following `Hashable`'s documented best practices. The conformance must
/// implement the `hash(into:)` requirement, and every bit of information that
/// is compared in `==` needs to be combined into the supplied `Hasher` value.
/// When used correctly, `Hasher` produces high-quality, randomly seeded hash
/// values that prevent repeatable hash collisions.
///
/// When `Key` correctly conforms to `Hashable`, key-based lookups in an ordered
/// dictionary is expected to take O(1) equality checks on average. Hash
/// collisions can still occur organically, so the worst-case lookup performance
/// is technically still O(*n*) (where *n* is the size of the dictionary);
/// however, long lookup chains are unlikely to occur in practice.
///
/// ## Implementation Details
///
/// An ordered dictionary consists of an ordered set of keys, alongside a
/// An ordered dictionary consists of an ``OrderedSet`` of keys, alongside a
/// regular `Array` value that contains their associated values.
/// The performance characteristics of `OrderedDictionary` are mostly dictated
/// by this setup.
///
/// - Looking up a member in an ordered dictionary is expected to execute
/// a constant number of hashing and equality check operations, just like
/// the standard `Dictionary`.
/// - `OrderedDictionary` is also able to append new items at the end of the
/// dictionary with an expected amortized complexity of O(1), similar to
/// inserting new items into `Dictionary`.
/// - Unfortunately, removing or inserting items at the start or middle of an
/// `OrderedDictionary` has linear complexity, making these significantly
/// slower than `Dictionary`.
/// - Storing keys and values outside of the hash table makes
/// `OrderedDictionary` more memory efficient than most alternative
/// ordered dictionary representations. It can sometimes also be more memory
/// efficient than the standard `Dictionary`, despote the additional
/// functionality of preserving element ordering.
///
/// Like all hashed data structures, ordered dictionaries are extremely
/// sensitive to the quality of the `Key` type's `Hashable` conformance.
/// All complexity guarantees are null and void if `Key` implements `Hashable`
/// incorrectly.
///
/// See ``OrderedSet`` for a more detailed discussion of these performance
/// characteristics.
@frozen
public struct OrderedDictionary<Key: Hashable, Value> {
@usableFromInline
@@ -662,7 +658,7 @@ extension OrderedDictionary {
/// in a string:
///
/// let message = "Hello, Elle!"
/// var letterCounts: [Character: Int] = [:]
/// var letterCounts: OrderedDictionary<Character, Int> = [:]
/// for letter in message {
/// letterCounts.updateValue(forKey: letter, default: 0) { count in
/// count += 1
@@ -12,6 +12,6 @@
extension OrderedSet: CustomReflectable {
/// The custom mirror for this instance.
public var customMirror: Mirror {
Mirror(self, unlabeledChildren: _elements, displayStyle: .collection)
Mirror(self, unlabeledChildren: _elements, displayStyle: .set)
}
}
@@ -22,10 +22,10 @@ extension OrderedSet: CustomDebugStringConvertible {
/// A textual representation of this instance, suitable for debugging.
public var debugDescription: String {
_arrayDescription(
for: self, debug: true, typeName: _debugTypeName())
for: self, debug: true, typeName: Self._debugTypeName())
}
internal func _debugTypeName() -> String {
internal static func _debugTypeName() -> String {
"OrderedSet<\(Element.self)>"
}
}
@@ -9,6 +9,8 @@
//
//===----------------------------------------------------------------------===//
import _CollectionsUtilities
extension OrderedSet {
/// Creates a set with the contents of the given sequence, which
/// must not include duplicate elements.
@@ -63,12 +65,12 @@ extension OrderedSet {
return
}
// Fast paths for when we know elements are all unique
if S.self == Set<Element>.self || S.self == SubSequence.self {
if elements is _UniqueCollection {
self.init(uncheckedUniqueElements: elements)
return
}
self.init()
self.init(minimumCapacity: elements.underestimatedCount)
append(contentsOf: elements)
}
@@ -0,0 +1,85 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
// `OrderedSet` does not directly conform to `SetAlgebra` because its definition
// of equality conflicts with `SetAlgebra` requirements. However, it still
// implements most `SetAlgebra` requirements (except `insert`, which is replaced
// by `append`).
//
// `OrderedSet` also provides an `unordered` view that explicitly conforms to
// `SetAlgebra`. That view implements `Equatable` by ignoring element order,
// so it can satisfy `SetAlgebra` requirements.
extension OrderedSet {
/// Removes the elements of this set that aren't also in the given one.
///
/// var set: OrderedSet = [1, 2, 3, 4]
/// let other: OrderedSet = [6, 4, 2, 0]
/// set.formIntersection(other)
/// // set is now [2, 4]
///
/// The result will only contain instances that were originally in `self`.
/// (This matters if equal members can be distinguished by comparing their
/// identities, or by some other means.)
///
/// - Parameter other: A set of elements.
///
/// - Complexity: Expected to be O(`self.count`) on average, if `Element`
/// implements high-quality hashing.
@inlinable
public mutating func formIntersection(_ other: Self) {
self = self.intersection(other)
}
// Generalizations
/// Removes the elements of this set that aren't also in the given one.
///
/// var set: OrderedSet = [1, 2, 3, 4]
/// let other: OrderedSet = [6, 4, 2, 0]
/// set.formIntersection(other)
/// // set is now [2, 4]
///
/// The result will only contain instances that were originally in `self`.
/// (This matters if equal members can be distinguished by comparing their
/// identities, or by some other means.)
///
/// - Parameter other: A set of elements.
///
/// - Complexity: Expected to be O(`self.count`) on average, if `Element`
/// implements high-quality hashing.
@inlinable
@inline(__always)
public mutating func formIntersection(_ other: UnorderedView) {
formIntersection(other._base)
}
/// Removes the elements of this set that aren't also in the given sequence.
///
/// var set: OrderedSet = [1, 2, 3, 4]
/// set.formIntersection([6, 4, 2, 0] as Array)
/// // set is now [2, 4]
///
/// The result will only contain instances that were originally in `self`.
/// (This matters if equal members can be distinguished by comparing their
/// identities, or by some other means.)
///
/// - Parameter other: A finite sequence of elements.
///
/// - Complexity: Expected to be O(*n*) on average where *n* is the number of
/// elements in `other`, if `Element` implements high-quality hashing.
@inlinable
public mutating func formIntersection<S: Sequence>(
_ other: S
) where S.Element == Element {
self = self.intersection(other)
}
}
@@ -0,0 +1,87 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
// `OrderedSet` does not directly conform to `SetAlgebra` because its definition
// of equality conflicts with `SetAlgebra` requirements. However, it still
// implements most `SetAlgebra` requirements (except `insert`, which is replaced
// by `append`).
//
// `OrderedSet` also provides an `unordered` view that explicitly conforms to
// `SetAlgebra`. That view implements `Equatable` by ignoring element order,
// so it can satisfy `SetAlgebra` requirements.
extension OrderedSet {
/// Replace this set with the elements contained in this set or the given
/// set, but not both.
///
/// On return, `self` contains elements originally from `self` followed by
/// elements in `other`, in the same order they appeared in the input values.
///
/// var set: OrderedSet = [1, 2, 3, 4]
/// let other: OrderedSet = [6, 4, 2, 0]
/// set.formSymmetricDifference(other)
/// // set is now [1, 3, 6, 0]
///
/// - Parameter other: Another set.
///
/// - Complexity: Expected to be O(`self.count + other.count`) on average, if
/// `Element` implements high-quality hashing.
@inlinable
public mutating func formSymmetricDifference(_ other: __owned Self) {
self = self.symmetricDifference(other)
}
// Generalizations
/// Replace this set with the elements contained in this set or the given
/// set, but not both.
///
/// On return, `self` contains elements originally from `self` followed by
/// elements in `other`, in the same order they appeared in the input values.
///
/// var set: OrderedSet = [1, 2, 3, 4]
/// let other: OrderedSet = [6, 4, 2, 0]
/// set.formSymmetricDifference(other.unordered)
/// // set is now [1, 3, 6, 0]
///
/// - Parameter other: Another set.
///
/// - Complexity: Expected to be O(`self.count + other.count`) on average, if
/// `Element` implements high-quality hashing.
@inlinable
@inline(__always)
public mutating func formSymmetricDifference(_ other: __owned UnorderedView) {
formSymmetricDifference(other._base)
}
/// Replace this set with the elements contained in this set or the given
/// sequence, but not both.
///
/// On return, `self` contains elements originally from `self` followed by
/// elements in `other`, in the same order they first appeared in the input
/// values.
///
/// var set: OrderedSet = [1, 2, 3, 4]
/// set.formSymmetricDifference([6, 4, 2, 0] as Array)
/// // set is now [1, 3, 6, 0]
///
/// - Parameter other: A finite sequence of elements.
///
/// - Complexity: Expected to be O(`self.count` + *n*) on average where *n* is
/// the number of elements in `other`, if `Element` implements high-quality
/// hashing.
@inlinable
public mutating func formSymmetricDifference<S: Sequence>(
_ other: __owned S
) where S.Element == Element {
self = self.symmetricDifference(other)
}
}
@@ -0,0 +1,103 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
// `OrderedSet` does not directly conform to `SetAlgebra` because its definition
// of equality conflicts with `SetAlgebra` requirements. However, it still
// implements most `SetAlgebra` requirements (except `insert`, which is replaced
// by `append`).
//
// `OrderedSet` also provides an `unordered` view that explicitly conforms to
// `SetAlgebra`. That view implements `Equatable` by ignoring element order,
// so it can satisfy `SetAlgebra` requirements.
extension OrderedSet {
/// Adds the elements of the given set to this set.
///
/// Members of `other` that aren't already in `self` get appended to the end
/// of the set, in the order they appear in `other`.
///
/// var a: OrderedSet = [1, 2, 3, 4]
/// let b: OrderedSet = [0, 2, 4, 6]
/// a.formUnion(b)
/// // `a` is now `[1, 2, 3, 4, 0, 6]`
///
/// For values that are members of both sets, this operation preserves the
/// instances that were originally in `self`. (This matters if equal members
/// can be distinguished by comparing their identities, or by some other
/// means.)
///
/// - Parameter other: The set of elements to insert.
///
/// - Complexity: Expected to be O(`other.count`) on average, if `Element`
/// implements high-quality hashing.
@inlinable
public mutating func formUnion(_ other: __owned Self) {
append(contentsOf: other)
}
// Generalizations
/// Adds the elements of the given set to this set.
///
/// Members of `other` that aren't already in `self` get appended to the end
/// of the set, in the order they appear in `other`.
///
/// let a: OrderedSet = [1, 2, 3, 4]
/// let b: OrderedSet = [0, 2, 4, 6]
/// a.formUnion(b.unordered)
/// // a is now [1, 2, 3, 4, 0, 6]
///
/// For values that are members of both inputs, this operation preserves the
/// instances that were originally in `self`. (This matters if equal members
/// can be distinguished by comparing their identities, or by some other
/// means.)
///
/// - Parameter other: The set of elements to add.
///
/// - Complexity: Expected to be O(`self.count` + `other.count`) on average,
/// if `Element` implements high-quality hashing.
@inlinable
@inline(__always)
public mutating func formUnion(_ other: __owned UnorderedView) {
formUnion(other._base)
}
/// Adds the elements of the given sequence to this set.
///
/// Members of `other` that aren't already in `self` get appended to the end
/// of the set, in the order they appear in `other`.
///
/// let a: OrderedSet = [1, 2, 3, 4]
/// let b: Array = [0, 2, 4, 6]
/// a.formUnion(b)
/// // a is now [1, 2, 3, 4, 0, 6]
///
/// For values that are members of both inputs, this operation preserves the
/// instances that were originally in `self`. (This matters if equal members
/// can be distinguished by comparing their identities, or by some other
/// means.)
///
/// If some of the values that are missing from `self` have multiple copies
/// in `other`, then the result of this function always contains the first
/// instances in the sequence -- the second and subsequent copies are ignored.
///
/// - Parameter other: A finite sequence of elements.
///
/// - Complexity: Expected to be O(`self.count` + `other.count`) on average,
/// if `Element` implements high-quality hashing.
@inlinable
public mutating func formUnion<S: Sequence>(
_ other: __owned S
) where S.Element == Element {
append(contentsOf: other)
}
}
@@ -0,0 +1,108 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
// `OrderedSet` does not directly conform to `SetAlgebra` because its definition
// of equality conflicts with `SetAlgebra` requirements. However, it still
// implements most `SetAlgebra` requirements (except `insert`, which is replaced
// by `append`).
//
// `OrderedSet` also provides an `unordered` view that explicitly conforms to
// `SetAlgebra`. That view implements `Equatable` by ignoring element order,
// so it can satisfy `SetAlgebra` requirements.
extension OrderedSet {
/// Returns a new set with the elements that are common to both this set and
/// the provided other one, in the order they appear in `self`.
///
/// let set: OrderedSet = [1, 2, 3, 4]
/// let other: OrderedSet = [6, 4, 2, 0]
/// set.intersection(other) // [2, 4]
///
/// The result will only contain instances that were originally in `self`.
/// (This matters if equal members can be distinguished by comparing their
/// identities, or by some other means.)
///
/// - Parameter other: Another set.
///
/// - Returns: A new set.
///
/// - Complexity: Expected to be O(`self.count`) on average, if `Element`
/// implements high-quality hashing.
@inlinable
public __consuming func intersection(_ other: Self) -> Self {
var result = Self()
for item in self {
if other.contains(item) {
result._appendNew(item)
}
}
result._checkInvariants()
return result
}
// Generalizations
/// Returns a new set with the elements that are common to both this set and
/// the provided other one, in the order they appear in `self`.
///
/// let set: OrderedSet = [1, 2, 3, 4]
/// let other: OrderedSet = [6, 4, 2, 0]
/// set.intersection(other) // [2, 4]
///
/// The result will only contain instances that were originally in `self`.
/// (This matters if equal members can be distinguished by comparing their
/// identities, or by some other means.)
///
/// - Parameter other: Another set.
///
/// - Returns: A new set.
///
/// - Complexity: Expected to be O(`self.count`) on average, if `Element`
/// implements high-quality hashing.
@inlinable
@inline(__always)
public __consuming func intersection(_ other: UnorderedView) -> Self {
intersection(other._base)
}
/// Returns a new set with the elements that are common to both this set and
/// the provided sequence, in the order they appear in `self`.
///
/// let set: OrderedSet = [1, 2, 3, 4]
/// set.intersection([6, 4, 2, 0] as Array) // [2, 4]
///
/// The result will only contain instances that were originally in `self`.
/// (This matters if equal members can be distinguished by comparing their
/// identities, or by some other means.)
///
/// - Parameter other: A finite sequence of elements.
///
/// - Returns: A new set.
///
/// - Complexity: Expected to be O(*n*) on average where *n* is the number of
/// elements in `other`, if `Element` implements high-quality hashing.
@inlinable
public __consuming func intersection<S: Sequence>(
_ other: S
) -> Self where S.Element == Element {
_UnsafeBitset.withTemporaryBitset(capacity: self.count) { bitset in
for item in other {
if let index = self._find_inlined(item).index {
bitset.insert(index)
}
}
let result = self._extractSubset(using: bitset)
result._checkInvariants()
return result
}
}
}
@@ -0,0 +1,76 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
// `OrderedSet` does not directly conform to `SetAlgebra` because its definition
// of equality conflicts with `SetAlgebra` requirements. However, it still
// implements most `SetAlgebra` requirements (except `insert`, which is replaced
// by `append`).
//
// `OrderedSet` also provides an `unordered` view that explicitly conforms to
// `SetAlgebra`. That view implements `Equatable` by ignoring element order,
// so it can satisfy `SetAlgebra` requirements.
extension OrderedSet {
/// Removes the elements of the given set from this set.
///
/// var set: OrderedSet = [1, 2, 3, 4]
/// let other: OrderedSet = [6, 4, 2, 0]
/// set.subtract(other)
/// // set is now [1, 3]
///
/// - Parameter other: Another set.
///
/// - Complexity: Expected to be O(`self.count + other.count`) on average, if
/// `Element` implements high-quality hashing.
@inlinable
@inline(__always)
public mutating func subtract(_ other: Self) {
self = subtracting(other)
}
// Generalizations
/// Removes the elements of the given set from this set.
///
/// var set: OrderedSet = [1, 2, 3, 4]
/// let other: OrderedSet = [6, 4, 2, 0]
/// set.subtract(other.unordered)
/// // set is now [1, 3]
///
/// - Parameter other: Another set.
///
/// - Complexity: Expected to be O(`self.count + other.count`) on average, if
/// `Element` implements high-quality hashing.
@inlinable
@inline(__always)
public mutating func subtract(_ other: UnorderedView) {
subtract(other._base)
}
/// Removes the elements of the given sequence from this set.
///
/// var set: OrderedSet = [1, 2, 3, 4]
/// set.subtract([6, 4, 2, 0] as Array)
/// // set is now [1, 3]
///
/// - Parameter other: A finite sequence of elements.
///
/// - Complexity: Expected to be O(`self.count` + *n*) on average, where *n*
/// is the number of elements in `other`, if `Element` implements
/// high-quality hashing.
@inlinable
@inline(__always)
public mutating func subtract<S: Sequence>(
_ other: S
) where S.Element == Element {
self = _subtracting(other)
}
}
@@ -0,0 +1,108 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
// `OrderedSet` does not directly conform to `SetAlgebra` because its definition
// of equality conflicts with `SetAlgebra` requirements. However, it still
// implements most `SetAlgebra` requirements (except `insert`, which is replaced
// by `append`).
//
// `OrderedSet` also provides an `unordered` view that explicitly conforms to
// `SetAlgebra`. That view implements `Equatable` by ignoring element order,
// so it can satisfy `SetAlgebra` requirements.
extension OrderedSet {
/// Returns a new set containing the elements of this set that do not occur
/// in the given set.
///
/// The result contains elements in the same order they appear in `self`.
///
/// let set: OrderedSet = [1, 2, 3, 4]
/// let other: OrderedSet = [6, 4, 2, 0]
/// set.subtracting(other) // [1, 3]
///
/// - Parameter other: Another set.
///
/// - Returns: A new set.
///
/// - Complexity: Expected to be O(`self.count + other.count`) on average, if
/// `Element` implements high-quality hashing.
@inlinable
@inline(__always)
public __consuming func subtracting(_ other: Self) -> Self {
_subtracting(other)
}
// Generalizations
/// Returns a new set containing the elements of this set that do not occur
/// in the given set.
///
/// The result contains elements in the same order they appear in `self`.
///
/// let set: OrderedSet = [1, 2, 3, 4]
/// let other: OrderedSet = [6, 4, 2, 0]
/// set.subtracting(other.unordered) // [1, 3]
///
/// - Parameter other: Another set.
///
/// - Returns: A new set.
///
/// - Complexity: Expected to be O(`self.count + other.count`) on average, if
/// `Element` implements high-quality hashing.
@inlinable
@inline(__always)
public __consuming func subtracting(_ other: UnorderedView) -> Self {
subtracting(other._base)
}
/// Returns a new set containing the elements of this set that do not occur
/// in the given sequence.
///
/// The result contains elements in the same order they appear in `self`.
///
/// let set: OrderedSet = [1, 2, 3, 4]
/// set.subtracting([6, 4, 2, 0] as Array) // [1, 3]
///
/// - Parameter other: A finite sequence of elements.
///
/// - Returns: A new set.
///
/// - Complexity: Expected to be O(`self.count + other.count`) on average, if
/// `Element` implements high-quality hashing.
@inlinable
@inline(__always)
public __consuming func subtracting<S: Sequence>(
_ other: S
) -> Self where S.Element == Element {
_subtracting(other)
}
@inlinable
__consuming func _subtracting<S: Sequence>(
_ other: S
) -> Self where S.Element == Element {
guard count > 0 else { return Self() }
return _UnsafeBitset.withTemporaryBitset(capacity: count) { difference in
difference.insertAll(upTo: count)
for item in other {
if let index = self._find(item).index {
if difference.remove(index), difference.count == 0 {
return Self()
}
}
}
assert(difference.count > 0)
let result = _extractSubset(using: difference)
result._checkInvariants()
return result
}
}
}
@@ -0,0 +1,133 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
// `OrderedSet` does not directly conform to `SetAlgebra` because its definition
// of equality conflicts with `SetAlgebra` requirements. However, it still
// implements most `SetAlgebra` requirements (except `insert`, which is replaced
// by `append`).
//
// `OrderedSet` also provides an `unordered` view that explicitly conforms to
// `SetAlgebra`. That view implements `Equatable` by ignoring element order,
// so it can satisfy `SetAlgebra` requirements.
extension OrderedSet {
/// Returns a new set with the elements that are either in this set or in
/// `other`, but not in both.
///
/// The result contains elements from `self` followed by elements in `other`,
/// in the same order they appeared in the original sets.
///
/// let set: OrderedSet = [1, 2, 3, 4]
/// let other: OrderedSet = [6, 4, 2, 0]
/// set.symmetricDifference(other) // [1, 3, 6, 0]
///
/// - Parameter other: Another set.
///
/// - Returns: A new set.
///
/// - Complexity: Expected to be O(`self.count + other.count`) on average, if
/// `Element` implements high-quality hashing.
@inlinable
public __consuming func symmetricDifference(_ other: __owned Self) -> Self {
_UnsafeBitset.withTemporaryBitset(capacity: self.count) { bitset1 in
_UnsafeBitset.withTemporaryBitset(capacity: other.count) { bitset2 in
bitset1.insertAll(upTo: self.count)
for item in other {
if let index = self._find(item).index {
bitset1.remove(index)
}
}
bitset2.insertAll(upTo: other.count)
for item in self {
if let index = other._find(item).index {
bitset2.remove(index)
}
}
var result = self._extractSubset(using: bitset1,
extraCapacity: bitset2.count)
for offset in bitset2 {
result._appendNew(other._elements[offset])
}
result._checkInvariants()
return result
}
}
}
// Generalizations
/// Returns a new set with the elements that are either in this set or in
/// `other`, but not in both.
///
/// The result contains elements from `self` followed by elements in `other`,
/// in the same order they appeared in the original sets.
///
/// let set: OrderedSet = [1, 2, 3, 4]
/// let other: OrderedSet = [6, 4, 2, 0]
/// set.symmetricDifference(other.unordered) // [1, 3, 6, 0]
///
/// - Parameter other: Another set.
///
/// - Returns: A new set.
///
/// - Complexity: Expected to be O(`self.count + other.count`) on average, if
/// `Element` implements high-quality hashing.
@inlinable
@inline(__always)
public __consuming func symmetricDifference(
_ other: __owned UnorderedView
) -> Self {
symmetricDifference(other._base)
}
/// Returns a new set with the elements that are either in this set or in
/// `other`, but not in both.
///
/// The result contains elements from `self` followed by elements in `other`,
/// in the same order they appeared in the original input values.
///
/// let set: OrderedSet = [1, 2, 3, 4]
/// let other: Array = [6, 4, 2, 0]
/// set.symmetricDifference(other) // [1, 3, 6, 0]
///
/// In case the sequence contains duplicate elements, only the first instance
/// matters -- the second and subsequent instances are ignored by this method.
///
/// - Parameter other: A finite sequence of elements.
///
/// - Returns: A new set.
///
/// - Complexity: Expected to be O(`self.count` + *n*) on average where *n* is
/// the number of elements in `other`, if `Element` implements high-quality
/// hashing.
@inlinable
public __consuming func symmetricDifference<S: Sequence>(
_ other: __owned S
) -> Self where S.Element == Element {
_UnsafeBitset.withTemporaryBitset(capacity: self.count) { bitset in
var new = Self()
bitset.insertAll(upTo: self.count)
for item in other {
if let index = self._find(item).index {
bitset.remove(index)
} else {
new.append(item)
}
}
var result = _extractSubset(using: bitset, extraCapacity: new.count)
for item in new._elements {
result._appendNew(item)
}
result._checkInvariants()
return result
}
}
}
@@ -0,0 +1,85 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
// `OrderedSet` does not directly conform to `SetAlgebra` because its definition
// of equality conflicts with `SetAlgebra` requirements. However, it still
// implements most `SetAlgebra` requirements (except `insert`, which is replaced
// by `append`).
//
// `OrderedSet` also provides an `unordered` view that explicitly conforms to
// `SetAlgebra`. That view implements `Equatable` by ignoring element order,
// so it can satisfy `SetAlgebra` requirements.
extension OrderedSet {
/// Returns a new set with the elements of both this and the given set.
///
/// Members of `other` that aren't already in `self` get appended to the end
/// of the result, in the order they appear in `other`.
///
/// let a: OrderedSet = [1, 2, 3, 4]
/// let b: OrderedSet = [0, 2, 4, 6]
/// a.union(b) // [1, 2, 3, 4, 0, 6]
///
/// - Parameter other: The set of elements to add.
///
/// - Complexity: Expected to be O(`self.count` + `other.count`) on average,
/// if `Element` implements high-quality hashing.
@inlinable
public __consuming func union(_ other: __owned Self) -> Self {
var result = self
result.formUnion(other)
return result
}
// Generalizations
/// Returns a new set with the elements of both this and the given set.
///
/// Members of `other` that aren't already in `self` get appended to the end
/// of the result, in the order they appear in `other`.
///
/// let a: OrderedSet = [1, 2, 3, 4]
/// let b: OrderedSet = [0, 2, 4, 6]
/// a.union(b.unordered) // [1, 2, 3, 4, 0, 6]
///
/// - Parameter other: The set of elements to add.
///
/// - Complexity: Expected to be O(`self.count` + `other.count`) on average,
/// if `Element` implements high-quality hashing.
@inlinable
@inline(__always)
public __consuming func union(_ other: __owned UnorderedView) -> Self {
union(other._base)
}
/// Returns a new set with the elements of both this and the given set.
///
/// Members of `other` that aren't already in `self` get appended to the end
/// of the result, in the order they appear in `other`.
///
/// let a: OrderedSet = [1, 2, 3, 4]
/// let b: Array = [0, 2, 4, 6]
/// a.union(b) // [1, 2, 3, 4, 0, 6]
///
/// - Parameter other: A finite sequence of elements.
///
/// - Complexity: Expected to be O(`self.count` + `other.count`) on average,
/// if `Element` implements high-quality hashing.
@inlinable
public __consuming func union<S: Sequence>(
_ other: __owned S
) -> Self where S.Element == Element {
var result = self
result.formUnion(other)
return result
}
}
@@ -1,589 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
// `OrderedSet` does not directly conform to `SetAlgebra` because its definition
// of equality conflicts with `SetAlgebra` requirements. However, it still
// implements most `SetAlgebra` requirements (except `insert`, which is replaced
// by `append`).
//
// `OrderedSet` also provides an `unordered` view that explicitly conforms to
// `SetAlgebra`. That view implements `Equatable` by ignoring element order,
// so it can satisfy `SetAlgebra` requirements.
extension OrderedSet {
/// Adds the elements of the given set to this set.
///
/// Members of `other` that aren't already in `self` get appended to the end
/// of the set, in the order they appear in `other`.
///
/// var a: OrderedSet = [1, 2, 3, 4]
/// let b: OrderedSet = [0, 2, 4, 6]
/// a.formUnion(b)
/// // `a` is now `[1, 2, 3, 4, 0, 6]`
///
/// - Parameter other: The set of elements to insert.
///
/// - Complexity: Expected to be O(`other.count`) on average, if `Element`
/// implements high-quality hashing.
@inlinable
public mutating func formUnion(_ other: __owned Self) {
append(contentsOf: other)
}
/// Returns a new set with the elements of both this and the given set.
///
/// Members of `other` that aren't already in `self` get appended to the end
/// of the result, in the order they appear in `other`.
///
/// let a: OrderedSet = [1, 2, 3, 4]
/// let b: OrderedSet = [0, 2, 4, 6]
/// a.union(b) // [1, 2, 3, 4, 0, 6]
///
/// - Parameter other: The set of elements to add.
///
/// - Complexity: Expected to be O(`self.count` + `other.count`) on average,
/// if `Element` implements high-quality hashing.
@inlinable
public __consuming func union(_ other: __owned Self) -> Self {
var result = self
result.formUnion(other)
return result
}
// Generalizations
/// Adds the elements of the given set to this set.
///
/// Members of `other` that aren't already in `self` get appended to the end
/// of the set, in the order they appear in `other`.
///
/// let a: OrderedSet = [1, 2, 3, 4]
/// let b: OrderedSet = [0, 2, 4, 6]
/// a.formUnion(b.unordered)
/// // a is now [1, 2, 3, 4, 0, 6]
///
/// - Parameter other: The set of elements to add.
///
/// - Complexity: Expected to be O(`self.count` + `other.count`) on average,
/// if `Element` implements high-quality hashing.
@inlinable
@inline(__always)
public mutating func formUnion(_ other: __owned UnorderedView) {
formUnion(other._base)
}
/// Returns a new set with the elements of both this and the given set.
///
/// Members of `other` that aren't already in `self` get appended to the end
/// of the result, in the order they appear in `other`.
///
/// let a: OrderedSet = [1, 2, 3, 4]
/// let b: OrderedSet = [0, 2, 4, 6]
/// a.union(b.unordered) // [1, 2, 3, 4, 0, 6]
///
/// - Parameter other: The set of elements to add.
///
/// - Complexity: Expected to be O(`self.count` + `other.count`) on average,
/// if `Element` implements high-quality hashing.
@inlinable
@inline(__always)
public __consuming func union(_ other: __owned UnorderedView) -> Self {
union(other._base)
}
/// Adds the elements of the given sequence to this set.
///
/// Members of `other` that aren't already in `self` get appended to the end
/// of the set, in the order they appear in `other`.
///
/// let a: OrderedSet = [1, 2, 3, 4]
/// let b: Array = [0, 2, 4, 6]
/// a.formUnion(b)
/// // a is now [1, 2, 3, 4, 0, 6]
///
/// - Parameter other: A finite sequence of elements.
///
/// - Complexity: Expected to be O(`self.count` + `other.count`) on average,
/// if `Element` implements high-quality hashing.
@inlinable
public mutating func formUnion<S: Sequence>(
_ other: __owned S
) where S.Element == Element {
append(contentsOf: other)
}
/// Returns a new set with the elements of both this and the given set.
///
/// Members of `other` that aren't already in `self` get appended to the end
/// of the result, in the order they appear in `other`.
///
/// let a: OrderedSet = [1, 2, 3, 4]
/// let b: Array = [0, 2, 4, 6]
/// a.union(b) // [1, 2, 3, 4, 0, 6]
///
/// - Parameter other: A finite sequence of elements.
///
/// - Complexity: Expected to be O(`self.count` + `other.count`) on average,
/// if `Element` implements high-quality hashing.
@inlinable
public __consuming func union<S: Sequence>(
_ other: __owned S
) -> Self where S.Element == Element {
var result = self
result.formUnion(other)
return result
}
}
extension OrderedSet {
/// Returns a new set with the elements that are common to both this set and
/// the provided other one, in the order they appear in `self`.
///
/// let set: OrderedSet = [1, 2, 3, 4]
/// let other: OrderedSet = [6, 4, 2, 0]
/// set.intersection(other) // [2, 4]
///
/// - Parameter other: Another set.
///
/// - Returns: A new set.
///
/// - Complexity: Expected to be O(`self.count`) on average, if `Element`
/// implements high-quality hashing.
@inlinable
public __consuming func intersection(_ other: Self) -> Self {
var result = Self()
for item in self {
if other.contains(item) {
result._appendNew(item)
}
}
result._checkInvariants()
return result
}
/// Removes the elements of this set that aren't also in the given one.
///
/// var set: OrderedSet = [1, 2, 3, 4]
/// let other: OrderedSet = [6, 4, 2, 0]
/// set.formIntersection(other)
/// // set is now [2, 4]
///
/// - Parameter other: A set of elements.
///
/// - Complexity: Expected to be O(`self.count`) on average, if `Element`
/// implements high-quality hashing.
@inlinable
public mutating func formIntersection(_ other: Self) {
self = self.intersection(other)
}
// Generalizations
/// Returns a new set with the elements that are common to both this set and
/// the provided other one, in the order they appear in `self`.
///
/// let set: OrderedSet = [1, 2, 3, 4]
/// let other: OrderedSet = [6, 4, 2, 0]
/// set.intersection(other) // [2, 4]
///
/// - Parameter other: Another set.
///
/// - Returns: A new set.
///
/// - Complexity: Expected to be O(`self.count`) on average, if `Element`
/// implements high-quality hashing.
@inlinable
@inline(__always)
public __consuming func intersection(_ other: UnorderedView) -> Self {
intersection(other._base)
}
/// Removes the elements of this set that aren't also in the given one.
///
/// var set: OrderedSet = [1, 2, 3, 4]
/// let other: OrderedSet = [6, 4, 2, 0]
/// set.formIntersection(other)
/// // set is now [2, 4]
///
/// - Parameter other: A set of elements.
///
/// - Complexity: Expected to be O(`self.count`) on average, if `Element`
/// implements high-quality hashing.
@inlinable
@inline(__always)
public mutating func formIntersection(_ other: UnorderedView) {
formIntersection(other._base)
}
/// Returns a new set with the elements that are common to both this set and
/// the provided sequence, in the order they appear in `self`.
///
/// let set: OrderedSet = [1, 2, 3, 4]
/// set.intersection([6, 4, 2, 0] as Array) // [2, 4]
///
/// - Parameter other: A finite sequence of elements.
///
/// - Returns: A new set.
///
/// - Complexity: Expected to be O(*n*) on average where *n* is the number of
/// elements in `other`, if `Element` implements high-quality hashing.
@inlinable
public __consuming func intersection<S: Sequence>(
_ other: S
) -> Self where S.Element == Element {
_UnsafeBitset.withTemporaryBitset(capacity: self.count) { bitset in
for item in other {
if let index = self._find_inlined(item).index {
bitset.insert(index)
}
}
let result = self._extractSubset(using: bitset)
result._checkInvariants()
return result
}
}
/// Removes the elements of this set that aren't also in the given sequence.
///
/// var set: OrderedSet = [1, 2, 3, 4]
/// set.formIntersection([6, 4, 2, 0] as Array)
/// // set is now [2, 4]
///
/// - Parameter other: A finite sequence of elements.
///
/// - Complexity: Expected to be O(*n*) on average where *n* is the number of
/// elements in `other`, if `Element` implements high-quality hashing.
@inlinable
public mutating func formIntersection<S: Sequence>(
_ other: S
) where S.Element == Element {
self = self.intersection(other)
}
}
extension OrderedSet {
/// Returns a new set with the elements that are either in this set or in
/// `other`, but not in both.
///
/// The result contains elements from `self` followed by elements in `other`,
/// in the same order they appeared in the original sets.
///
/// let set: OrderedSet = [1, 2, 3, 4]
/// let other: OrderedSet = [6, 4, 2, 0]
/// set.symmetricDifference(other) // [1, 3, 6, 0]
///
/// - Parameter other: Another set.
///
/// - Returns: A new set.
///
/// - Complexity: Expected to be O(`self.count + other.count`) on average, if
/// `Element` implements high-quality hashing.
@inlinable
public __consuming func symmetricDifference(_ other: __owned Self) -> Self {
_UnsafeBitset.withTemporaryBitset(capacity: self.count) { bitset1 in
_UnsafeBitset.withTemporaryBitset(capacity: other.count) { bitset2 in
bitset1.insertAll(upTo: self.count)
for item in other {
if let index = self._find(item).index {
bitset1.remove(index)
}
}
bitset2.insertAll(upTo: other.count)
for item in self {
if let index = other._find(item).index {
bitset2.remove(index)
}
}
var result = self._extractSubset(using: bitset1,
extraCapacity: bitset2.count)
for offset in bitset2 {
result._appendNew(other._elements[offset])
}
result._checkInvariants()
return result
}
}
}
/// Replace this set with the elements contained in this set or the given
/// set, but not both.
///
/// On return, `self` contains elements originally from `self` followed by
/// elements in `other`, in the same order they appeared in the input values.
///
/// var set: OrderedSet = [1, 2, 3, 4]
/// let other: OrderedSet = [6, 4, 2, 0]
/// set.formSymmetricDifference(other)
/// // set is now [1, 3, 6, 0]
///
/// - Parameter other: Another set.
///
/// - Complexity: Expected to be O(`self.count + other.count`) on average, if
/// `Element` implements high-quality hashing.
@inlinable
public mutating func formSymmetricDifference(_ other: __owned Self) {
self = self.symmetricDifference(other)
}
// Generalizations
/// Returns a new set with the elements that are either in this set or in
/// `other`, but not in both.
///
/// The result contains elements from `self` followed by elements in `other`,
/// in the same order they appeared in the original sets.
///
/// let set: OrderedSet = [1, 2, 3, 4]
/// let other: OrderedSet = [6, 4, 2, 0]
/// set.symmetricDifference(other.unordered) // [1, 3, 6, 0]
///
/// - Parameter other: Another set.
///
/// - Returns: A new set.
///
/// - Complexity: Expected to be O(`self.count + other.count`) on average, if
/// `Element` implements high-quality hashing.
@inlinable
@inline(__always)
public __consuming func symmetricDifference(
_ other: __owned UnorderedView
) -> Self {
symmetricDifference(other._base)
}
/// Replace this set with the elements contained in this set or the given
/// set, but not both.
///
/// On return, `self` contains elements originally from `self` followed by
/// elements in `other`, in the same order they appeared in the input values.
///
/// var set: OrderedSet = [1, 2, 3, 4]
/// let other: OrderedSet = [6, 4, 2, 0]
/// set.formSymmetricDifference(other.unordered)
/// // set is now [1, 3, 6, 0]
///
/// - Parameter other: Another set.
///
/// - Complexity: Expected to be O(`self.count + other.count`) on average, if
/// `Element` implements high-quality hashing.
@inlinable
@inline(__always)
public mutating func formSymmetricDifference(_ other: __owned UnorderedView) {
formSymmetricDifference(other._base)
}
/// Returns a new set with the elements that are either in this set or in
/// `other`, but not in both.
///
/// The result contains elements from `self` followed by elements in `other`,
/// in the same order they appeared in the original input values.
///
/// let set: OrderedSet = [1, 2, 3, 4]
/// let other: Array = [6, 4, 2, 0]
/// set.symmetricDifference(other) // [1, 3, 6, 0]
///
/// - Parameter other: A finite sequence of elements.
///
/// - Returns: A new set.
///
/// - Complexity: Expected to be O(`self.count` + *n*) on average where *n* is
/// the number of elements in `other`, if `Element` implements high-quality
/// hashing.
@inlinable
public __consuming func symmetricDifference<S: Sequence>(
_ other: __owned S
) -> Self where S.Element == Element {
_UnsafeBitset.withTemporaryBitset(capacity: self.count) { bitset in
var new = Self()
bitset.insertAll(upTo: self.count)
for item in other {
if let index = self._find(item).index {
bitset.remove(index)
} else {
new.append(item)
}
}
var result = _extractSubset(using: bitset, extraCapacity: new.count)
for item in new._elements {
result._appendNew(item)
}
result._checkInvariants()
return result
}
}
/// Replace this set with the elements contained in this set or the given
/// sequence, but not both.
///
/// On return, `self` contains elements originally from `self` followed by
/// elements in `other`, in the same order they first appeared in the input
/// values.
///
/// var set: OrderedSet = [1, 2, 3, 4]
/// set.formSymmetricDifference([6, 4, 2, 0] as Array)
/// // set is now [1, 3, 6, 0]
///
/// - Parameter other: A finite sequence of elements.
///
/// - Complexity: Expected to be O(`self.count` + *n*) on average where *n* is
/// the number of elements in `other`, if `Element` implements high-quality
/// hashing.
@inlinable
public mutating func formSymmetricDifference<S: Sequence>(
_ other: __owned S
) where S.Element == Element {
self = self.symmetricDifference(other)
}
}
extension OrderedSet {
/// Returns a new set containing the elements of this set that do not occur
/// in the given set.
///
/// The result contains elements in the same order they appear in `self`.
///
/// let set: OrderedSet = [1, 2, 3, 4]
/// let other: OrderedSet = [6, 4, 2, 0]
/// set.subtracting(other) // [1, 3]
///
/// - Parameter other: Another set.
///
/// - Returns: A new set.
///
/// - Complexity: Expected to be O(`self.count + other.count`) on average, if
/// `Element` implements high-quality hashing.
@inlinable
@inline(__always)
public __consuming func subtracting(_ other: Self) -> Self {
_subtracting(other)
}
/// Removes the elements of the given set from this set.
///
/// var set: OrderedSet = [1, 2, 3, 4]
/// let other: OrderedSet = [6, 4, 2, 0]
/// set.subtract(other)
/// // set is now [1, 3]
///
/// - Parameter other: Another set.
///
/// - Complexity: Expected to be O(`self.count + other.count`) on average, if
/// `Element` implements high-quality hashing.
@inlinable
@inline(__always)
public mutating func subtract(_ other: Self) {
self = subtracting(other)
}
// Generalizations
/// Returns a new set containing the elements of this set that do not occur
/// in the given set.
///
/// The result contains elements in the same order they appear in `self`.
///
/// let set: OrderedSet = [1, 2, 3, 4]
/// let other: OrderedSet = [6, 4, 2, 0]
/// set.subtracting(other.unordered) // [1, 3]
///
/// - Parameter other: Another set.
///
/// - Returns: A new set.
///
/// - Complexity: Expected to be O(`self.count + other.count`) on average, if
/// `Element` implements high-quality hashing.
@inlinable
@inline(__always)
public __consuming func subtracting(_ other: UnorderedView) -> Self {
subtracting(other._base)
}
/// Removes the elements of the given set from this set.
///
/// var set: OrderedSet = [1, 2, 3, 4]
/// let other: OrderedSet = [6, 4, 2, 0]
/// set.subtract(other.unordered)
/// // set is now [1, 3]
///
/// - Parameter other: Another set.
///
/// - Complexity: Expected to be O(`self.count + other.count`) on average, if
/// `Element` implements high-quality hashing.
@inlinable
@inline(__always)
public mutating func subtract(_ other: UnorderedView) {
subtract(other._base)
}
/// Returns a new set containing the elements of this set that do not occur
/// in the given sequence.
///
/// The result contains elements in the same order they appear in `self`.
///
/// let set: OrderedSet = [1, 2, 3, 4]
/// set.subtracting([6, 4, 2, 0] as Array) // [1, 3]
///
/// - Parameter other: A finite sequence of elements.
///
/// - Returns: A new set.
///
/// - Complexity: Expected to be O(`self.count + other.count`) on average, if
/// `Element` implements high-quality hashing.
@inlinable
@inline(__always)
public __consuming func subtracting<S: Sequence>(
_ other: S
) -> Self where S.Element == Element {
_subtracting(other)
}
/// Removes the elements of the given sequence from this set.
///
/// var set: OrderedSet = [1, 2, 3, 4]
/// set.subtract([6, 4, 2, 0] as Array)
/// // set is now [1, 3]
///
/// - Parameter other: A finite sequence of elements.
///
/// - Complexity: Expected to be O(`self.count` + *n*) on average, where *n*
/// is the number of elements in `other`, if `Element` implements
/// high-quality hashing.
@inlinable
@inline(__always)
public mutating func subtract<S: Sequence>(
_ other: S
) where S.Element == Element {
self = _subtracting(other)
}
@inlinable
__consuming func _subtracting<S: Sequence>(
_ other: S
) -> Self where S.Element == Element {
guard count > 0 else { return Self() }
return _UnsafeBitset.withTemporaryBitset(capacity: count) { difference in
difference.insertAll(upTo: count)
for item in other {
if let index = self._find(item).index {
if difference.remove(index), difference.count == 0 {
return Self()
}
}
}
assert(difference.count > 0)
let result = _extractSubset(using: difference)
result._checkInvariants()
return result
}
}
}
@@ -53,6 +53,24 @@ extension OrderedSet.SubSequence {
}
}
extension OrderedSet.SubSequence: CustomStringConvertible {
// A textual representation of this instance.
public var description: String {
_arrayDescription(for: self)
}
}
extension OrderedSet.SubSequence: CustomDebugStringConvertible {
/// A textual representation of this instance, suitable for debugging.
public var debugDescription: String {
_arrayDescription(
for: self,
debug: true,
typeName: "\(OrderedSet._debugTypeName()).SubSequence"
)
}
}
extension OrderedSet.SubSequence: Sequence {
// A type representing the collection’s elements.
public typealias Element = OrderedSet.Element
@@ -81,7 +81,7 @@ extension OrderedSet.UnorderedView: CustomDebugStringConvertible {
_arrayDescription(
for: _base,
debug: true,
typeName: "\(_base._debugTypeName()).UnorderedView")
typeName: "\(OrderedSet._debugTypeName()).UnorderedView")
}
}
@@ -132,28 +132,24 @@
///
/// However, `OrderedSet` is able to partially implement these two protocols;
/// namely, there is no issue with mutation operations that merely change the
/// order of elements, or just remove some subset of existing members:
/// order of elements, or just remove some subset of existing members.
///
/// // Permutation operations from MutableCollection:
/// func swapAt(_ i: Int, _ j: Int)
/// func partition(by predicate: (Element) throws -> Bool) -> rethrows Int
/// func sort() where Element: Comparable
/// func sort(by predicate: (Element, Element) throws -> Bool) rethrows
/// func shuffle()
/// func shuffle<T: RandomNumberGenerator>(using generator: inout T)
/// func reverse()
/// Accordingly, `OrderedSet` provides permutation operations from `MutableCollection`:
/// - ``swapAt(_:_:)``
/// - ``partition(by:)``
/// - ``sort()``, ``sort(by:)``
/// - ``shuffle()``, ``shuffle(using:)``
/// - ``reverse()``
///
/// // Removal operations from RangeReplaceableCollection:
/// func removeAll(keepingCapacity: Bool = false)
/// func remove(at index: Int) -> Element
/// func removeSubrange(_ bounds: Range<Int>)
/// func removeLast() -> Element
/// func removeLast(_ n: Int)
/// func removeFirst() -> Element
/// func removeFirst(_ n: Int)
/// func removeAll(where shouldBeRemoved: (Element) throws -> Bool) rethrows
/// It also supports removal operations from `RangeReplaceableCollection`:
/// - ``removeAll(keepingCapacity:)``
/// - ``remove(at:)``
/// - ``removeSubrange(_:)-2fqke``, ``removeSubrange(_:)-62u6a``
/// - ``removeLast()``, ``removeLast(_:)``
/// - ``removeFirst()``, ``removeFirst(_:)``
/// - ``removeAll(where:)``
///
/// `OrderedSet` also implements `reserveCapacity(_)` from
/// `OrderedSet` also implements ``reserveCapacity(_:)`` from
/// `RangeReplaceableCollection`, to allow for efficient insertion of a known
/// number of elements. (However, unlike `Array` and `Set`, `OrderedSet` does
/// not provide a `capacity` property.)
@@ -175,20 +171,77 @@
/// pickyFunction(set.elements) // OK
///
/// It is also possible to mutate the set by updating the value of the
/// `elements` property. This guarantees that direct mutations happen in place
/// ``elements`` property. This guarantees that direct mutations happen in place
/// when possible (i.e., without spurious copy-on-write copies).
///
/// However, the set needs to ensure the uniqueness of its members, so every
/// update to `elements` includes a postprocessing step to detect and remove
/// update to ``elements`` includes a postprocessing step to detect and remove
/// duplicates over the entire array. This can be slower than doing the
/// equivalent updates with direct `OrderedSet` operations, so updating
/// `elements` is best used in cases where direct implementations aren't
/// ``elements`` is best used in cases where direct implementations aren't
/// available -- for example, when you need to call a `MutableCollection`
/// algorithm that isn't directly implemented by `OrderedSet` itself.
///
/// # Performance
///
/// Like the standard `Set` type, the performance of hashing operations in
/// An `OrderedSet` stores its members in a standard `Array` value (exposed by
/// the ``elements`` property). It also maintains a separate hash table
/// containing array indices into this array; this hash table is used to ensure
/// member uniqueness and to implement fast membership tests.
///
/// ## Element Lookups
///
/// Like the standard `Set`, looking up a member is expected to execute
/// a constant number of hashing and equality check operations. To look up
/// an element, `OrderedSet` generates a hash value from it, and then finds a
/// set of array indices within the hash table that could potentially contain
/// the element we're looking for. By looking through these indices in the
/// storage array, `OrderedSet` is able to determine if the element is a member.
/// As long as `Element` properly implements hashing, the size of this set of
/// candidate indices is expected to have a constant upper bound, so looking up
/// an item will be a constant operation.
///
/// ## Appending New Items
///
/// Similarly, appending a new element to the end of an `OrderedSet` is expected
/// to require amortized O(1) hashing/comparison/copy operations on the
/// element type, just like inserting an item into a standard `Set`.
/// (If the ordered set value has multiple copies, then appending an item will
/// need to copy all its items into unique storage (again just like the standard
/// `Set`) -- but once the set has been uniqued, additional appends will only
/// perform a constant number of operations, so when averaged over many appends,
/// the overall complexity comes out as O(1).)
///
/// ## Removing Items and Inserting in Places Other Than the End
///
/// Unfortunately, `OrderedSet` does not emulate `Set`'s performance for all
/// operations. In particular, operations that insert or remove elements at the
/// front or in the middle of an ordered set are generally expected to be
/// significantly slower than with `Set`. To perform these operations, an
/// `OrderedSet` needs to perform the corresponding operation in the storage
/// array, and then it needs to renumber all subsequent members in the hash
/// table. Both of these phases take a number of steps that grows linearly with
/// the size of the ordered set, while the standard `Set` can do the
/// corresponding operations with O(1) expected complexity.
///
/// This generally makes `OrderedSet` a poor replacement to `Set` in use cases
/// that do not specifically require a particular element ordering.
///
/// ## Memory Utilization
///
/// The hash table in an ordered set never needs to store larger indices than
/// the current size of the storage array, and `OrderedSet` makes use of this
/// observation to reduce the number of bits it uses to encode these integer
/// vaues. Additionally, the actual hashed elements are stored in a flat array
/// value rather than the hash table itself, so they aren't subject to the hash
/// table's strict maximum load factor. These two observations combine to
/// optimize the memory utilization of `OrderedSet`, sometimes making it even
/// more efficient than the standard `Set` -- despite the additional
/// functionality of preserving element ordering.
///
/// ## Proper Hashing is Crucial
///
/// Similar to the standard `Set` type, the performance of hashing operations in
/// `OrderedSet` is highly sensitive to the quality of hashing implemented by
/// the `Element` type. Failing to correctly implement hashing can easily lead
/// to unacceptable performance, with the severity of the effect increasing with
@@ -201,37 +254,18 @@
/// cannot be induced merely by adding a particular list of members to the set.
///
/// The easiest way to achieve this is to make sure `Element` implements hashing
/// following `Hashable`'s documented best practices. The conformance must
/// implement the `hash(into:)` requirement, and every bit of information that
/// is compared in `==` needs to be combined into the supplied `Hasher` value.
/// When used correctly, `Hasher` produces high-quality, randomly seeded hash
/// values that prevent repeatable hash collisions.
/// following `Hashable`'s documented best practices. The `Element` type must
/// implement the `hash(into:)` requirement (not `hashValue`) in such a way that
/// every bit of information that is compared in `==` is fed into the supplied
/// `Hasher` value. When used correctly, `Hasher` produces high-quality,
/// randomly seeded hash values that prevent repeatable hash collisions and
/// therefore avoid (intentional or accidental) denial of service attacks.
///
/// When `Element` implements `Hashable` correctly, testing for membership in an
/// ordered set is expected to take O(1) equality checks on average. Hash
/// collisions can still occur organically, so the worst-case lookup performance
/// is technically still O(*n*) (where *n* is the size of the set); however,
/// long lookup chains are unlikely to occur in practice.
///
/// # Implementation Details
///
/// An `OrderedSet` stores its members in a regular `Array` value (exposed by
/// the `elements` property). It also maintains a standalone hash table
/// containing array indices alongside the array; this is used to implement fast
/// membership tests. The size of the array is limited by the capacity of the
/// corresponding hash table, so indices stored inside the hash table can be
/// encoded into fewer bits than a standard `Int` value, leading to a storage
/// representation that can often be more compact than that of `Set` itself.
///
/// Inserting or removing a single member (or a range of members) needs to
/// perform the corresponding operation in the storage array, in addition to
/// renumbering any subsequent members in the hash table. Therefore, these
/// operations are expected to have performance characteristics similar to an
/// `Array`: inserting or removing an element to the end of an ordered set is
/// expected to execute in O(1) operations, while they are expected to take
/// linear time at the front (or in the middle) of the set. (Note that this is
/// different to the standard `Set`, where insertions and removals are expected
/// to take amortized O(1) time.)
/// Like with all hashed collection types, all complexity guarantees are null
/// and void if `Element` implements `Hashable` incorrectly. In the worst case,
/// the hash table can regress into a particularly slow implementation of an
/// unsorted array, with even basic lookup operations taking complexity
/// proportional to the size of the set.
@frozen
public struct OrderedSet<Element> where Element: Hashable
{
@@ -497,7 +531,7 @@ extension OrderedSet {
}
extension OrderedSet {
/// Returns a new ordered set containing the values pairs of the ordered set
/// Returns a new ordered set containing all the members of this ordered set
/// that satisfy the given predicate.
///
/// - Parameter isIncluded: A closure that takes a value as its
@@ -55,6 +55,7 @@ add_library(PersistentCollections
"PersistentDictionary/PersistentDictionary+Equatable.swift"
"PersistentDictionary/PersistentDictionary+ExpressibleByDictionaryLiteral.swift"
"PersistentDictionary/PersistentDictionary+Filter.swift"
"PersistentDictionary/PersistentDictionary+Fluent Operations.swift"
"PersistentDictionary/PersistentDictionary+Hashable.swift"
"PersistentDictionary/PersistentDictionary+Initializers.swift"
"PersistentDictionary/PersistentDictionary+Keys.swift"
@@ -331,3 +331,30 @@ extension _Node.Builder {
}
}
}
extension _Node.Builder {
@inlinable
internal func mapValues<Value2>(
_ transform: (Element) -> Value2
) -> _Node<Key, Value2>.Builder {
switch kind {
case .empty:
return .empty(level)
case let .item(item, at: bucket):
let value = transform(item)
return .item(level, (item.key, value), at: bucket)
case let .node(node):
return .node(level, node.mapValues(transform))
case let .collisionNode(node):
return .collisionNode(level, node.mapValues(transform))
}
}
@inlinable
internal func mapValuesToVoid() -> _Node<Key, Void>.Builder {
if Value.self == Void.self {
return unsafeBitCast(self, to: _Node<Key, Void>.Builder.self)
}
return mapValues { _ in () }
}
}
@@ -121,7 +121,7 @@ extension _Node {
}
@inlinable
internal mutating func hasFreeSpace(_ bytes: Int) -> Bool {
internal func hasFreeSpace(_ bytes: Int) -> Bool {
bytes <= self.raw.storage.header.bytesFree
}
@@ -14,6 +14,19 @@ extension _Node {
internal func intersection<Value2>(
_ level: _Level,
_ other: _Node<Key, Value2>
) -> _Node? {
assert(level.isAtRoot)
let builder = _intersection(level, other)
guard let builder = builder else { return nil }
let root = builder.finalize(.top)
root._fullInvariantCheck()
return root
}
@inlinable
internal func _intersection<Value2>(
_ level: _Level,
_ other: _Node<Key, Value2>
) -> Builder? {
if self.raw.storage === other.raw.storage { return nil }
@@ -68,7 +81,7 @@ extension _Node {
else if r.childMap.contains(bucket) {
let rslot = r.childMap.slot(of: bucket)
let branch = l[child: lslot]
.intersection(level.descend(), r[child: rslot])
._intersection(level.descend(), r[child: rslot])
if let branch = branch {
assert(branch.count < self.count)
if !removing {
@@ -143,7 +156,7 @@ extension _Node {
}
if r.childMap.contains(bucket) {
let rslot = r.childMap.slot(of: bucket)
return intersection(level.descend(), r[child: rslot])
return _intersection(level.descend(), r[child: rslot])
.map { .childBranch(level, $0, at: bucket) }
}
return .empty(level)
@@ -166,7 +179,7 @@ extension _Node {
}
if l.childMap.contains(bucket) {
let lslot = l.childMap.slot(of: bucket)
let branch = l[child: lslot].intersection(level.descend(), other)
let branch = l[child: lslot]._intersection(level.descend(), other)
guard let branch = branch else {
assert(l[child: lslot].isCollisionNode)
assert(l[child: lslot].collisionHash == r.collisionHash)
@@ -71,4 +71,18 @@ extension _Node {
return result
}
}
@inlinable
internal func mapValuesToVoid(
copy: Bool = false, extraBytes: Int = 0
) -> _Node<Key, Void> {
if Value.self == Void.self {
let node = unsafeBitCast(self, to: _Node<Key, Void>.self)
guard copy || !node.hasFreeSpace(extraBytes) else { return node }
return node.copy(withFreeSpace: extraBytes)
}
let node = mapValues { _ in () }
guard !node.hasFreeSpace(extraBytes) else { return node }
return node.copy(withFreeSpace: extraBytes)
}
}
@@ -14,6 +14,19 @@ extension _Node {
internal func subtracting<Value2>(
_ level: _Level,
_ other: _Node<Key, Value2>
) -> _Node? {
assert(level.isAtRoot)
let builder = _subtracting(level, other)
guard let builder = builder else { return nil }
let root = builder.finalize(.top)
root._fullInvariantCheck()
return root
}
@inlinable
internal func _subtracting<Value2>(
_ level: _Level,
_ other: _Node<Key, Value2>
) -> Builder? {
if self.raw.storage === other.raw.storage { return .empty(level) }
@@ -73,7 +86,7 @@ extension _Node {
else if r.childMap.contains(bucket) {
let rslot = r.childMap.slot(of: bucket)
let child = l[child: lslot]
.subtracting(level.descend(), r[child: rslot])
._subtracting(level.descend(), r[child: rslot])
if let child = child {
assert(child.count < self.count)
if !removing {
@@ -149,7 +162,7 @@ extension _Node {
}
else if r.childMap.contains(bucket) {
let rslot = r.childMap.slot(of: bucket)
return subtracting(level.descend(), r[child: rslot])
return _subtracting(level.descend(), r[child: rslot])
.map { .childBranch(level, $0, at: bucket) }
}
return nil
@@ -173,7 +186,7 @@ extension _Node {
}
if l.childMap.contains(bucket) {
let lslot = l.childMap.slot(of: bucket)
let branch = l[child: lslot].subtracting(level.descend(), other)
let branch = l[child: lslot]._subtracting(level.descend(), other)
guard let branch = branch else { return nil }
var result = self._removingChild(level, at: bucket, lslot)
result.addNewChildBranch(level, branch, at: bucket)
@@ -11,20 +11,24 @@
extension _Node {
@inlinable
internal func symmetricDifference(
internal func symmetricDifference<Value2>(
_ level: _Level,
_ other: _Node
) -> Builder? {
guard self.count > 0 else { return Builder(level, other) }
_ other: _Node<Key, Value2>
) -> _Node<Key, Void>.Builder? {
guard self.count > 0 else {
return .init(level, other.mapValuesToVoid())
}
guard other.count > 0 else { return nil }
return _symmetricDifference(level, other)
}
@inlinable
internal func _symmetricDifference(
internal func _symmetricDifference<Value2>(
_ level: _Level,
_ other: _Node
) -> Builder {
_ other: _Node<Key, Value2>
) -> _Node<Key, Void>.Builder {
typealias VoidNode = _Node<Key, Void>
assert(self.count > 0 && other.count > 0)
if self.raw.storage === other.raw.storage {
@@ -36,7 +40,7 @@ extension _Node {
return self.read { l in
other.read { r in
var result: Builder = .empty(level)
var result: VoidNode.Builder = .empty(level)
for (bucket, lslot) in l.itemMap {
let lp = l.itemPtr(at: lslot)
@@ -46,10 +50,10 @@ extension _Node {
if lp.pointee.key != rp.pointee.key {
let h1 = _Hash(lp.pointee.key)
let h2 = _Hash(rp.pointee.key)
let child = _Node.build(
let child = VoidNode.build(
level: level.descend(),
item1: lp.pointee, h1,
item2: { $0.initialize(to: rp.pointee) }, h2)
item1: (lp.pointee.key, ()), h1,
item2: { $0.initialize(to: (rp.pointee.key, ())) }, h2)
result.addNewChildNode(level, child.top, at: bucket)
}
}
@@ -60,16 +64,20 @@ extension _Node {
let child = rp.pointee
.removing(level.descend(), lp.pointee.key, h)?.replacement
if let child = child {
let child = child.mapValuesToVoid()
result.addNewChildBranch(level, child, at: bucket)
}
else {
let child2 = rp.pointee.inserting(level.descend(), lp.pointee, h)
assert(child2.inserted)
result.addNewChildNode(level, child2.node, at: bucket)
var child2 = rp.pointee
.mapValuesToVoid(
copy: true, extraBytes: VoidNode.spaceForNewItem)
let r = child2.insert(level.descend(), (lp.pointee.key, ()), h)
assert(r.inserted)
result.addNewChildNode(level, child2, at: bucket)
}
}
else {
result.addNewItem(level, lp.pointee, at: bucket)
result.addNewItem(level, (lp.pointee.key, ()), at: bucket)
}
}
@@ -80,14 +88,17 @@ extension _Node {
let rp = r.itemPtr(at: rslot)
let h = _Hash(rp.pointee.key)
let child = lp.pointee
.mapValuesToVoid()
.removing(level.descend(), rp.pointee.key, h)?.replacement
if let child = child {
result.addNewChildBranch(level, child, at: bucket)
}
else {
let child2 = lp.pointee.inserting(level.descend(), rp.pointee, h)
assert(child2.inserted)
result.addNewChildNode(level, child2.node, at: bucket)
var child2 = lp.pointee.mapValuesToVoid(
copy: true, extraBytes: VoidNode.spaceForNewItem)
let r2 = child2.insert(level.descend(), (rp.pointee.key, ()), h)
assert(r2.inserted)
result.addNewChildNode(level, child2, at: bucket)
}
}
else if r.childMap.contains(bucket) {
@@ -97,18 +108,20 @@ extension _Node {
result.addNewChildBranch(level, b, at: bucket)
}
else {
result.addNewChildNode(level, lp.pointee, at: bucket)
result.addNewChildNode(
level, lp.pointee.mapValuesToVoid(), at: bucket)
}
}
let seen = l.itemMap.union(l.childMap)
for (bucket, rslot) in r.itemMap {
guard !seen.contains(bucket) else { continue }
result.addNewItem(level, r[item: rslot], at: bucket)
result.addNewItem(level, (r[item: rslot].key, ()), at: bucket)
}
for (bucket, rslot) in r.childMap {
guard !seen.contains(bucket) else { continue }
result.addNewChildNode(level, r[child: rslot], at: bucket)
result.addNewChildNode(
level, r[child: rslot].mapValuesToVoid(), at: bucket)
}
return result
}
@@ -116,10 +129,10 @@ extension _Node {
}
@inlinable @inline(never)
internal func _symmetricDifference_slow(
internal func _symmetricDifference_slow<Value2>(
_ level: _Level,
_ other: _Node
) -> Builder {
_ other: _Node<Key, Value2>
) -> _Node<Key, Void>.Builder {
switch (self.isCollisionNode, other.isCollisionNode) {
case (true, true):
return self._symmetricDifference_slow_both(level, other)
@@ -131,26 +144,27 @@ extension _Node {
}
@inlinable
internal func _symmetricDifference_slow_both(
internal func _symmetricDifference_slow_both<Value2>(
_ level: _Level,
_ other: _Node
) -> Builder {
read { l in
_ other: _Node<Key, Value2>
) -> _Node<Key, Void>.Builder {
typealias VoidNode = _Node<Key, Void>
return read { l in
other.read { r in
guard l.collisionHash == r.collisionHash else {
let node = _Node.build(
let node = VoidNode.build(
level: level,
child1: self, l.collisionHash,
child2: other, r.collisionHash)
child1: self.mapValuesToVoid(), l.collisionHash,
child2: other.mapValuesToVoid(), r.collisionHash)
return .node(level, node)
}
var result: Builder = .empty(level)
var result: VoidNode.Builder = .empty(level)
let ritems = r.reverseItems
for ls: _Slot in stride(from: .zero, to: l.itemsEndSlot, by: 1) {
let lp = l.itemPtr(at: ls)
let include = !ritems.contains(where: { $0.key == lp.pointee.key })
if include {
result.addNewCollision(level, lp.pointee, l.collisionHash)
result.addNewCollision(level, (lp.pointee.key, ()), l.collisionHash)
}
}
// FIXME: Consider remembering slots of shared items in r by
@@ -160,7 +174,7 @@ extension _Node {
let rp = r.itemPtr(at: rs)
let include = !litems.contains(where: { $0.key == rp.pointee.key })
if include {
result.addNewCollision(level, rp.pointee, r.collisionHash)
result.addNewCollision(level, (rp.pointee.key, ()), r.collisionHash)
}
}
return result
@@ -169,13 +183,14 @@ extension _Node {
}
@inlinable
internal func _symmetricDifference_slow_left(
internal func _symmetricDifference_slow_left<Value2>(
_ level: _Level,
_ other: _Node
) -> Builder {
_ other: _Node<Key, Value2>
) -> _Node<Key, Void>.Builder {
typealias VoidNode = _Node<Key, Void>
// `self` is a collision node on a compressed path. The other tree might
// have the same set of collisions, just expanded a bit deeper.
read { l in
return read { l in
other.read { r in
assert(l.isCollisionNode && !r.isCollisionNode)
let bucket = l.collisionHash[level]
@@ -184,57 +199,68 @@ extension _Node {
let rp = r.itemPtr(at: rslot)
let rh = _Hash(rp.pointee.key)
guard rh == l.collisionHash else {
var copy = other.copy(withFreeSpace: _Node.spaceForSpawningChild)
var copy = other.mapValuesToVoid(
copy: true, extraBytes: VoidNode.spaceForSpawningChild)
let item = copy.removeItem(at: bucket, rslot)
let child = _Node.build(
let child = VoidNode.build(
level: level.descend(),
item1: { $0.initialize(to: item) }, rh,
child2: self, l.collisionHash)
item1: { $0.initialize(to: (item.key, ())) }, rh,
child2: self.mapValuesToVoid(), l.collisionHash)
copy.insertChild(child.top, bucket)
return .node(level, copy)
}
let litems = l.reverseItems
if let li = litems.firstIndex(where: { $0.key == rp.pointee.key }) {
if l.itemCount == 2 {
var node = other.copy()
node.replaceItem(at: bucket, rslot, with: litems[1 &- li])
var node = other.mapValuesToVoid(copy: true)
node.replaceItem(
at: bucket, rslot,
with: (litems[1 &- li].key, ()))
return .node(level, node)
}
let lslot = _Slot(litems.count &- 1 &- li)
var child = self.copy()
var child = self.mapValuesToVoid(copy: true)
_ = child.removeItem(at: .invalid, lslot)
if other.hasSingletonItem {
// Compression
return .collisionNode(level, child)
}
var node = other.copy(withFreeSpace: _Node.spaceForSpawningChild)
var node = other.mapValuesToVoid(
copy: true, extraBytes: VoidNode.spaceForSpawningChild)
_ = node.removeItem(at: bucket, rslot)
node.insertChild(child, bucket)
return .node(level, node)
}
if other.hasSingletonItem {
// Compression
let copy = self.copyNodeAndAppendCollision {
$0.initialize(to: r[item: .zero])
}
return .collisionNode(level, copy.node)
var copy = self.mapValuesToVoid(
copy: true, extraBytes: VoidNode.spaceForNewItem)
_ = copy.ensureUniqueAndAppendCollision(
isUnique: true,
(r[item: .zero].key, ()))
return .collisionNode(level, copy)
}
var node = other.copy(withFreeSpace: _Node.spaceForSpawningChild)
var node = other.mapValuesToVoid(
copy: true, extraBytes: VoidNode.spaceForSpawningChild)
let item = node.removeItem(at: bucket, rslot)
let child = self.copyNodeAndAppendCollision {
$0.initialize(to: item)
}
node.insertChild(child.node, bucket)
var child = self.mapValuesToVoid(
copy: true, extraBytes: VoidNode.spaceForNewItem)
_ = child.ensureUniqueAndAppendCollision(
isUnique: true, (item.key, ()))
node.insertChild(child, bucket)
return .node(level, node)
}
if r.childMap.contains(bucket) {
let rslot = r.childMap.slot(of: bucket)
let rp = r.childPtr(at: rslot)
let child = rp.pointee._symmetricDifference(level.descend(), self)
return other.replacingChild(level, at: bucket, rslot, with: child)
return other
.mapValuesToVoid()
.replacingChild(level, at: bucket, rslot, with: child)
}
var node = other.copy(withFreeSpace: _Node.spaceForNewChild)
node.insertChild(self, bucket)
var node = other
.mapValuesToVoid(copy: true, extraBytes: VoidNode.spaceForNewChild)
node.insertChild(self.mapValuesToVoid(), bucket)
return .node(level, node)
}
}
@@ -11,23 +11,23 @@
extension _Node {
@inlinable
internal func union(
internal func union<Value2>(
_ level: _Level,
_ other: _Node
) -> (copied: Bool, node: _Node) {
guard self.count > 0 else { return (true, other) }
guard other.count > 0 else { return (false, self) }
_ other: _Node<Key, Value2>
) -> (copied: Bool, node: _Node<Key, Void>) {
guard self.count > 0 else { return (true, other.mapValuesToVoid()) }
guard other.count > 0 else { return (false, self.mapValuesToVoid()) }
if level.isAtRoot, self.hasSingletonItem {
// In this special case, the root node may turn into a collision node
// during the merge process. Prevent this from causing issues below by
// handling it up front.
return self.read { l in
let lp = l.itemPtr(at: .zero)
var copy = other
var copy = other.mapValuesToVoid(copy: true)
let r = copy.updateValue(
level, forKey: lp.pointee.key, _Hash(lp.pointee.key)
) {
$0.initialize(to: lp.pointee)
$0.initialize(to: (lp.pointee.key, ()))
}
if !r.inserted {
UnsafeHandle.update(r.leaf) {
@@ -41,12 +41,12 @@ extension _Node {
}
@inlinable
internal func _union(
internal func _union<Value2>(
_ level: _Level,
_ other: _Node
) -> (copied: Bool, node: _Node) {
_ other: _Node<Key, Value2>
) -> (copied: Bool, node: _Node<Key, Void>) {
if self.raw.storage === other.raw.storage {
return (false, self)
return (false, self.mapValuesToVoid())
}
if self.isCollisionNode || other.isCollisionNode {
@@ -55,7 +55,7 @@ extension _Node {
return self.read { l in
other.read { r in
var node = self
var node = self.mapValuesToVoid()
var copied = false
for (bucket, lslot) in l.itemMap {
@@ -75,7 +75,7 @@ extension _Node {
replacing: bucket,
itemSlot: slot,
newHash: _Hash(rp.pointee.key),
{ $0.initialize(to: rp.pointee) })
{ $0.initialize(to: (rp.pointee.key, ())) })
// If we hadn't handled the singleton root node case above,
// then this call would sometimes turn `node` into a collision
// node on a compressed path, causing mischief.
@@ -90,7 +90,8 @@ extension _Node {
node.ensureUnique(
isUnique: copied, withFreeSpace: _Node.spaceForSpawningChild)
let item = node.removeItem(at: bucket)
let r = rp.pointee.inserting(level.descend(), item, _Hash(item.key))
let r = rp.pointee.mapValuesToVoid()
.inserting(level.descend(), (item.key, ()), _Hash(item.key))
node.insertChild(r.node, bucket)
copied = true
}
@@ -102,7 +103,8 @@ extension _Node {
let rslot = r.itemMap.slot(of: bucket)
let rp = r.itemPtr(at: rslot)
let h = _Hash(rp.pointee.key)
let r = l[child: lslot].inserting(level.descend(), rp.pointee, h)
let r = l[child: lslot].mapValuesToVoid()
.inserting(level.descend(), (rp.pointee.key, ()), h)
guard r.inserted else {
// Nothing to do
continue
@@ -134,7 +136,7 @@ extension _Node {
for (bucket, _) in r.itemMap.subtracting(seen) {
let rslot = r.itemMap.slot(of: bucket)
node.ensureUniqueAndInsertItem(
isUnique: copied, r[item: rslot], at: bucket)
isUnique: copied, (r[item: rslot].key, ()), at: bucket)
copied = true
}
for (bucket, _) in r.childMap.subtracting(seen) {
@@ -142,7 +144,7 @@ extension _Node {
node.ensureUnique(
isUnique: copied, withFreeSpace: _Node.spaceForNewChild)
copied = true
node.insertChild(r[child: rslot], bucket)
node.insertChild(r[child: rslot].mapValuesToVoid(), bucket)
}
return (copied, node)
@@ -151,30 +153,30 @@ extension _Node {
}
@inlinable @inline(never)
internal func _union_slow(
internal func _union_slow<Value2>(
_ level: _Level,
_ other: _Node
) -> (copied: Bool, node: _Node) {
_ other: _Node<Key, Value2>
) -> (copied: Bool, node: _Node<Key, Void>) {
let lc = self.isCollisionNode
let rc = other.isCollisionNode
if lc && rc {
return read { l in
other.read { r in
guard l.collisionHash == r.collisionHash else {
let node = _Node.build(
let node = _Node<Key, Void>.build(
level: level,
child1: self, l.collisionHash,
child2: other, r.collisionHash)
child1: self.mapValuesToVoid(), l.collisionHash,
child2: other.mapValuesToVoid(), r.collisionHash)
return (true, node)
}
var copied = false
var node = self
var node = self.mapValuesToVoid()
let litems = l.reverseItems
for rs: _Slot in stride(from: .zero, to: r.itemsEndSlot, by: 1) {
let p = r.itemPtr(at: rs)
if !litems.contains(where: { $0.key == p.pointee.key }) {
_ = node.ensureUniqueAndAppendCollision(
isUnique: copied, p.pointee)
isUnique: copied, (p.pointee.key, ()))
copied = true
}
}
@@ -199,24 +201,25 @@ extension _Node {
r.hasSingletonItem
&& l.reverseItems.contains(where: { $0.key == rp.pointee.key })
{
return (false, self)
return (false, self.mapValuesToVoid())
}
let node = other.copyNodeAndPushItemIntoNewChild(
level: level, self, at: bucket, itemSlot: rslot)
let node = other.mapValuesToVoid().copyNodeAndPushItemIntoNewChild(
level: level, self.mapValuesToVoid(), at: bucket, itemSlot: rslot)
return (true, node)
}
if r.childMap.contains(bucket) {
let rslot = r.childMap.slot(of: bucket)
let res = self._union(level.descend(), r[child: rslot])
var node = other.copy()
var node = other.mapValuesToVoid(copy: true)
let delta = node.replaceChild(at: bucket, rslot, with: res.node)
assert(delta >= 0)
return (true, node)
}
var node = other.copy(withFreeSpace: _Node.spaceForNewChild)
node.insertChild(self, bucket)
var node = other.mapValuesToVoid(
copy: true, extraBytes: _Node<Key, Void>.spaceForNewChild)
node.insertChild(self.mapValuesToVoid(), bucket)
return (true, node)
}
}
@@ -224,28 +227,29 @@ extension _Node {
assert(rc)
// `other` is a collision node on a compressed path.
return read { l in
other.read { r in
return read { l -> (copied: Bool, node: _Node<Key, Void>) in
other.read { r -> (copied: Bool, node: _Node<Key, Void>) in
let bucket = r.collisionHash[level]
if l.itemMap.contains(bucket) {
let lslot = l.itemMap.slot(of: bucket)
assert(!l.hasSingletonItem) // Handled up front above
let node = self.copyNodeAndPushItemIntoNewChild(
level: level, other, at: bucket, itemSlot: lslot)
let node = self.mapValuesToVoid().copyNodeAndPushItemIntoNewChild(
level: level, other.mapValuesToVoid(), at: bucket, itemSlot: lslot)
return (true, node)
}
if l.childMap.contains(bucket) {
let lslot = l.childMap.slot(of: bucket)
let child = l[child: lslot]._union(level.descend(), other)
guard child.copied else { return (false, self) }
var node = self.copy()
guard child.copied else { return (false, self.mapValuesToVoid()) }
var node = self.mapValuesToVoid(copy: true)
let delta = node.replaceChild(at: bucket, lslot, with: child.node)
assert(delta > 0) // If we didn't add an item, why did we copy?
return (true, node)
}
var node = self.copy(withFreeSpace: _Node.spaceForNewChild)
node.insertChild(other, bucket)
var node = self.mapValuesToVoid(
copy: true, extraBytes: _Node.spaceForNewChild)
node.insertChild(other.mapValuesToVoid(), bucket)
return (true, node)
}
}
@@ -34,6 +34,7 @@
/// in a fixed-size array; this would speed up walking over the tree, but it
/// would considerably embiggen the size of the path construct.)
@usableFromInline
@frozen
internal struct _UnsafePath {
@usableFromInline
internal var ancestors: _AncestorSlots
@@ -0,0 +1,72 @@
# ``PersistentCollections/PersistentDictionary``
<!-- Summary -->
<!-- ## Overview -->
## Topics
### Collection Views
- ``Keys-swift.struct``
- ``Values-swift.struct``
- ``keys-swift.property``
- ``values-swift.property``
### Creating a Dictionary
- ``init()``
- ``init(_:)-7jshe``
- ``init(_:)-8ls8p``
- ``init(uniqueKeysWithValues:)-65ax0``
- ``init(uniqueKeysWithValues:)-5ok18``
- ``init(_:uniquingKeysWith:)-7fuzu``
- ``init(_:uniquingKeysWith:)-4jee3``
- ``init(grouping:by:)-8ntzv``
- ``init(grouping:by:)-7cu86``
- ``init(keys:valueGenerator:)``
### Inspecting a Dictionary
- ``isEmpty-65s43``
- ``count-9cdqd``
### Accessing Keys and Values
- ``subscript(_:)-g0oi``
- ``subscript(_:default:)``
- ``index(forKey:)``
### Adding or Updating Keys and Values
- ``updateValue(_:forKey:)``
- ``updateValue(forKey:with:)``
- ``updateValue(forKey:default:with:)``
- ``merge(_:uniquingKeysWith:)-853bf``
- ``merge(_:uniquingKeysWith:)-19xxn``
- ``merge(_:uniquingKeysWith:)-2osh``
- ``merging(_:uniquingKeysWith:)-2a7cl``
- ``merging(_:uniquingKeysWith:)-1tq3e``
- ``merging(_:uniquingKeysWith:)-2kjqq``
### Removing Keys and Values
- ``removeValue(forKey:)``
- ``remove(at:)``
### Non-mutating Dictionary Operations
- ``updatingValue(_:forKey:)``
- ``removingValue(forKey:)``
### Comparing Dictionaries
- ``==(_:_:)``
### Transforming a Dictionary
- ``filter(_:)``
- ``mapValues(_:)``
- ``compactMapValues(_:)``
@@ -0,0 +1,163 @@
# ``PersistentCollections/PersistentSet``
### Implementation Details
`PersistentSet` and `PersistentDictionary` are based on a Swift adaptation
of the *Compressed Hash-Array Mapped Prefix Tree* (CHAMP) data structure.
- Michael J Steindorfer and Jurgen J Vinju. Optimizing Hash-Array Mapped
Tries for Fast and Lean Immutable JVM Collections. In *Proc.
International Conference on Object-Oriented Programming, Systems,
Languages, and Applications,* pp. 783-800, 2015.
https://doi.org/10.1145/2814270.2814312
In this setup, the members of such a collection are organized into a tree
data structure based on their hash values. For example, assuming 16 bit hash
values sliced into 4-bit chunks, each node in the prefix tree would have
sixteen slots (one for each digit), each of which may contain a member, a
child node reference, or it may be empty. A `PersistentSet` containing the
tree items `Maximo`, `Julia` and `Don Pablo` (with hash values of `0x2B65`,
`0xA69F` and `0xADA1`, respectively) may be organized into a prefix tree of
two nodes:
```
┌0┬1┬2───────┬3┬4┬5┬6┬7┬8┬9┬A──┬B┬C┬D┬E┬F┐
│ │ │ Maximo │ │ │ │ │ │ │ │ • │ │ │ │ │ │
└─┴─┴────────┴─┴─┴─┴─┴─┴─┴─┴─┼─┴─┴─┴─┴─┴─┘
╎
╎
┌0┬1┬2┬3┬4┬5┬6───┴──┬7┬8┬9┬A┬B┬C┬D──────────┬E┬F┐
│ │ │ │ │ │ │ Julia │ │ │ │ │ │ │ Don Pablo │ │ │
└─┴─┴─┴─┴─┴─┴───────┴─┴─┴─┴─┴─┴─┴───────────┴─┴─┘
```
The root node directly contains `Maximo`, because it is the only set member
whose hash value starts with `8`. However, the first digits of the hashes of
`Julia` and `Don Pablo` are both `A`, so these items reside in a separate
node, one level below the root.
(To save space, nodes are actually stored in a more compact form, with just
enough space allocated to store their contents: empty slots do not take up
any room. Hence the term "compressed" in "Compressed Hash-Array Mapped
Prefix Tree".)
The resulting tree structure lends itself well to sharing nodes across
multiple collection values. Inserting or removing an item in a completely
shared tree requires copying at most log(n) nodes -- every node along the
path to the item needs to be uniqued, but all other nodes can remain shared.
While the cost of copying this many nodes isn't trivial, it is dramatically
lower than the cost of having to copy the entire data structure, like the
standard `Set` has to do.
When looking up a particular member, we descend from the root node,
following along the path specified by successive digits of the member's hash
value. As long as hash values are unique, we will either find the member
we're looking for, or we will know for sure that it does not exist in the
set.
In practice, hash values aren't guaranteed to be unique though. Members with
conflicting hash values need to be collected in special collision nodes that
are able to grow as large as necessary to contain all colliding members that
share the same hash. Looking up a member in one of these nodes requires a
linear search, so it is crucial that such collisions do not happen often.
As long as `Element` properly implements `Hashable`, lookup operations in a
`PersistentSet` are expected to be able to decide whether the set contains a
particular item by looking at no more than a constant number of items on
average -- typically they will need to compare against just one member.
<!-- ## Overview -->
## Topics
### Creating a Set
- ``init()``
- ``init(_:)-6nn9e``
- ``init(_:)-6qbps``
- ``init(_:)-30nei``
### Finding Elements
- ``contains(_:)``
- ``firstIndex(of:)``
- ``lastIndex(of:)``
### Adding and Updating Elements
- ``insert(_:)``
- ``update(with:)``
- ``update(_:at:)``
### Removing Elements
- ``filter(_:)``
- ``remove(_:)``
- ``remove(at:)``
### Non-mutating Set Operations
- ``inserting(_:)``
- ``updating(with:)``
- ``removing(_:)``
### Combining Sets
- ``intersection(_:)-9dx2a``
- ``intersection(_:)-5z4my``
- ``intersection(_:)-1d4e0``
- ``union(_:)-1nk1t``
- ``union(_:)-8otnp``
- ``union(_:)-6eysm``
- ``subtracting(_:)-8sczx``
- ``subtracting(_:)-2iv0a``
- ``subtracting(_:)-63bfb``
- ``symmetricDifference(_:)-76bw``
- ``symmetricDifference(_:)-92ha9``
- ``symmetricDifference(_:)-1n89g``
- ``formIntersection(_:)-4s0od``
- ``formIntersection(_:)-7dqfx``
- ``formIntersection(_:)-8i59p``
- ``formUnion(_:)-68pog``
- ``formUnion(_:)-82rrc``
- ``formUnion(_:)-4r7qz``
- ``subtract(_:)-7rmd3``
- ``subtract(_:)-47r93``
- ``subtract(_:)-3v8ms``
- ``formSymmetricDifference(_:)-499uq``
- ``formSymmetricDifference(_:)-8wue8``
- ``formSymmetricDifference(_:)-4t8jr``
### Comparing Sets
- ``==(_:_:)``
- ``isEqual(to:)-3m3in``
- ``isEqual(to:)-7mkn1``
- ``isEqual(to:)-5px5r``
- ``isSubset(of:)-9mp7l``
- ``isSubset(of:)-2jlh``
- ``isSubset(of:)-8vn0j``
- ``isSuperset(of:)-5af8o``
- ``isSuperset(of:)-6mvxj``
- ``isSuperset(of:)-864jy``
- ``isStrictSubset(of:)-48nx2``
- ``isStrictSubset(of:)-2j680``
- ``isStrictSubset(of:)-1s6n9``
- ``isStrictSuperset(of:)-nd5j``
- ``isStrictSuperset(of:)-5z263``
- ``isStrictSuperset(of:)-ivbh``
- ``isDisjoint(with:)-12irx``
- ``isDisjoint(with:)-1hhyf``
- ``isDisjoint(with:)-61lde``
@@ -0,0 +1,20 @@
# ``PersistentCollections``
**Swift Collections** is an open-source package of data structure implementations for the Swift programming language.
## Overview
#### Additional Resources
- [`Swift Collections` on GitHub](https://github.com/apple/swift-collections/)
- [`Swift Collections` on the Swift Forums](https://forums.swift.org/c/related-projects/collections/72)
## Topics
### Persistent Collections
- ``PersistentSet``
- ``PersistentDictionary``
@@ -38,6 +38,9 @@ internal struct _DictionaryCodingKey: CodingKey {
extension PersistentDictionary: Encodable
where Key: Encodable, Value: Encodable
{
/// Encodes the elements of this dictionary into the given encoder.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
if Key.self == String.self {
// Since the keys are already Strings, we can use them as keys directly.
@@ -10,6 +10,12 @@
//===----------------------------------------------------------------------===//
extension PersistentDictionary {
/// The position of an element in a persistent dictionary.
///
/// An index in a persistent dictionary is a compact encoding of a path in
/// the underlying prefix tree. Such indices are valid until the tree
/// structure is changed; hence, indices are usually invalidated every time
/// the dictionary gets mutated.
@frozen
public struct Index {
@usableFromInline
@@ -38,6 +44,12 @@ where Key: Sendable, Value: Sendable {}
#endif
extension PersistentDictionary.Index: Equatable {
/// Returns a Boolean value indicating whether two index values are equal.
///
/// Note that comparing two indices that do not belong to the same tree
/// leads to a runtime error.
///
/// - Complexity: O(1)
@inlinable
public static func ==(left: Self, right: Self) -> Bool {
precondition(
@@ -47,14 +59,14 @@ extension PersistentDictionary.Index: Equatable {
}
}
extension PersistentDictionary.Index: Hashable {
@inlinable
public func hash(into hasher: inout Hasher) {
hasher.combine(_path)
}
}
extension PersistentDictionary.Index: Comparable {
/// Returns a Boolean value indicating whether the value of the first argument
/// is less than the second argument.
///
/// Note that comparing two indices that do not belong to the same tree
/// leads to a runtime error.
///
/// - Complexity: O(1)
public static func <(left: Self, right: Self) -> Bool {
precondition(
left._root == right._root && left._version == right._version,
@@ -63,23 +75,52 @@ extension PersistentDictionary.Index: Comparable {
}
}
extension PersistentDictionary.Index: Hashable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// - Complexity: O(1)
@inlinable
public func hash(into hasher: inout Hasher) {
hasher.combine(_path)
}
}
extension PersistentDictionary.Index: CustomStringConvertible {
// A textual representation of this instance.
public var description: String {
_path.description
}
}
extension PersistentDictionary: BidirectionalCollection {
extension PersistentDictionary.Index: CustomDebugStringConvertible {
/// A textual representation of this instance, suitable for debugging.
public var debugDescription: String {
_path.description
}
}
extension PersistentDictionary: Collection {
/// A Boolean value indicating whether the collection is empty.
///
/// - Complexity: O(1)
@inlinable
public var isEmpty: Bool {
_root.count == 0
}
/// The number of elements in the collection.
///
/// - Complexity: O(1)
@inlinable
public var count: Int {
_root.count
}
/// The position of the first element in a nonempty collection, or `endIndex`
/// if the collection is empty.
///
/// - Complexity: O(1)
@inlinable
public var startIndex: Index {
var path = _UnsafePath(root: _root.raw)
@@ -87,6 +128,10 @@ extension PersistentDictionary: BidirectionalCollection {
return Index(_root: _root.unmanaged, version: _version, path: path)
}
/// The collection’s “past the end” position—that is, the position one greater
/// than the last valid subscript argument.
///
/// - Complexity: O(1)
@inlinable
public var endIndex: Index {
var path = _UnsafePath(root: _root.raw)
@@ -105,6 +150,12 @@ extension PersistentDictionary: BidirectionalCollection {
}
/// Accesses the key-value pair at the specified position.
///
/// - Parameter position: The position of the element to access. `position`
/// must be a valid index of the collection that is not equal to
/// `endIndex`.
///
/// - Complexity: O(1)
@inlinable
public subscript(i: Index) -> Element {
precondition(_isValid(i), "Invalid index")
@@ -114,6 +165,12 @@ extension PersistentDictionary: BidirectionalCollection {
}
}
/// Replaces the given index with its successor.
///
/// - Parameter i: A valid index of the collection.
/// `i` must be less than `endIndex`.
///
/// - Complexity: O(1)
@inlinable
public func formIndex(after i: inout Index) {
precondition(_isValid(i), "Invalid index")
@@ -122,14 +179,12 @@ extension PersistentDictionary: BidirectionalCollection {
}
}
@inlinable
public func formIndex(before i: inout Index) {
precondition(_isValid(i), "Invalid index")
guard i._path.findPredecessorItem(under: _root.raw) else {
preconditionFailure("The start index has no predecessor")
}
}
/// Returns the position immediately after the given index.
///
/// - Parameter i: A valid index of the collection.
/// `i` must be less than `endIndex`.
///
/// - Complexity: O(1)
@inlinable @inline(__always)
public func index(after i: Index) -> Index {
var i = i
@@ -137,19 +192,38 @@ extension PersistentDictionary: BidirectionalCollection {
return i
}
@inlinable @inline(__always)
public func index(before i: Index) -> Index {
var i = i
formIndex(before: &i)
return i
}
/// Returns the distance between two arbitrary valid indices in this
/// collection.
///
/// - Parameter start: A valid index of the collection.
/// - Parameter end: Another valid index of the collection.
/// - Returns: The distance between `start` and `end`.
/// (The result can be negative, even though `PersistentDictionary` is not
/// a bidirectional collection.)
/// - Complexity: O(log(`count`))
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
precondition(_isValid(start) && _isValid(end), "Invalid index")
return _root.raw.distance(.top, from: start._path, to: end._path)
}
/// Returns an index that is the specified distance from the given index.
///
/// The value passed as `distance` must not offset `i` beyond the bounds of
/// the collection.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - distance: The distance to offset `i`. As a special exception,
/// `distance` is allowed to be negative even though
/// `PersistentDictionary` isn't a bidirectional collection.
/// - Returns: An index offset by `distance` from the index `i`. If
/// `distance` is positive, this is the same value as the result of
/// `distance` calls to `index(after:)`. If distance is negative, then
/// `distance` calls to `index(after:)` on the returned value will be the
/// same as `start`.
///
/// - Complexity: O(log(`distance`))
@inlinable
public func index(_ i: Index, offsetBy distance: Int) -> Index {
precondition(_isValid(i), "Invalid index")
@@ -159,6 +233,27 @@ extension PersistentDictionary: BidirectionalCollection {
return i
}
/// Returns an index that is the specified distance from the given index,
/// unless that distance is beyond a given limiting index.
///
/// The value passed as `distance` must not offset `i` beyond the bounds of
/// the collection, unless the index passed as `limit` prevents offsetting
/// beyond those bounds.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - distance: The distance to offset `i`. As a special exception,
/// `distance` is allowed to be negative even though
/// `PersistentDictionary` isn't a bidirectional collection.
/// - limit: A valid index of the collection to use as a limit. If
/// `distance > 0`, a limit that is less than `i` has no effect.
/// Likewise, if `distance < 0`, a limit that is greater than `i` has no
/// effect.
/// - Returns: An index offset by `distance` from the index `i`, unless that
/// index would be beyond `limit` in the direction of movement. In that
/// case, the method returns `nil`.
///
/// - Complexity: O(log(`distance`))
@inlinable
public func index(
_ i: Index, offsetBy distance: Int, limitedBy limit: Index
@@ -174,3 +269,37 @@ extension PersistentDictionary: BidirectionalCollection {
return nil
}
}
#if false
// Note: Let's not do this. `BidirectionalCollection` would imply that
// the ordering of elements would be meaningful, which isn't true for
// `PersistentDictionary`.
extension PersistentDictionary: BidirectionalCollection {
/// Replaces the given index with its predecessor.
///
/// - Parameter i: A valid index of the collection.
/// `i` must be greater than `startIndex`.
///
/// - Complexity: O(1)
@inlinable
public func formIndex(before i: inout Index) {
precondition(_isValid(i), "Invalid index")
guard i._path.findPredecessorItem(under: _root.raw) else {
preconditionFailure("The start index has no predecessor")
}
}
/// Returns the position immediately before the given index.
///
/// - Parameter i: A valid index of the collection.
/// `i` must be greater than `startIndex`.
///
/// - Complexity: O(1)
@inlinable @inline(__always)
public func index(before i: Index) -> Index {
var i = i
formIndex(before: &i)
return i
}
}
#endif
@@ -10,6 +10,7 @@
//===----------------------------------------------------------------------===//
extension PersistentDictionary: CustomReflectable {
/// The custom mirror for this instance.
public var customMirror: Mirror {
Mirror(self, unlabeledChildren: self, displayStyle: .dictionary)
}
@@ -12,18 +12,20 @@
import _CollectionsUtilities
extension PersistentDictionary: CustomStringConvertible {
// A textual representation of this instance.
public var description: String {
_dictionaryDescription(for: self)
}
}
extension PersistentDictionary: CustomDebugStringConvertible {
/// A textual representation of this instance, suitable for debugging.
public var debugDescription: String {
_dictionaryDescription(
for: self, debug: true, typeName: _debugTypeName())
for: self, debug: true, typeName: Self._debugTypeName())
}
internal func _debugTypeName() -> String {
internal static func _debugTypeName() -> String {
"PersistentDictionary<\(Key.self), \(Value.self)>"
}
}
@@ -10,6 +10,12 @@
//===----------------------------------------------------------------------===//
extension PersistentDictionary: Equatable where Value: Equatable {
/// Returns a Boolean value indicating whether two values are equal.
///
/// Two persistent dictionaries are considered equal if they contain the same
/// key-value pairs, but not necessarily in the same order.
///
/// - Complexity: O(`min(left.count, right.count)`)
@inlinable
public static func == (left: Self, right: Self) -> Bool {
left._root.isEqual(to: right._root, by: { $0 == $1 })
@@ -10,6 +10,23 @@
//===----------------------------------------------------------------------===//
extension PersistentDictionary: ExpressibleByDictionaryLiteral {
/// Creates a new dictionary from the contents of a dictionary literal.
///
/// The literal must not contain duplicate elements.
///
/// Do not call this initializer directly. It is used by the compiler when
/// you use a dictionary literal. Instead, create a new dictionary using a
/// dictionary literal as its value by enclosing a comma-separated list of
/// values in square brackets. You can use a dictionary literal anywhere a
/// persistent dictionary is expected by the type context.
///
/// Like the standard `Dictionary`, persistent dictionaries do not preserve
/// the order of elements inside the array literal.
///
/// - Parameter elements: A variadic list of elements of the new set.
///
/// - Complexity: O(`elements.count`) if `Element` properly implements
/// hashing.
@inlinable
@inline(__always)
public init(dictionaryLiteral elements: (Key, Value)...) {
@@ -10,6 +10,16 @@
//===----------------------------------------------------------------------===//
extension PersistentDictionary {
/// Returns a new persistent dictionary containing the key-value pairs of this
/// dictionary that satisfy the given predicate.
///
/// - Parameter isIncluded: A closure that takes a key-value pair as its
/// argument and returns a Boolean value indicating whether it should be
/// included in the returned dictionary.
///
/// - Returns: A dictionary of the key-value pairs that `isIncluded` allows.
///
/// - Complexity: O(`count`)
@inlinable
public func filter(
_ isIncluded: (Element) throws -> Bool
@@ -0,0 +1,61 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension PersistentDictionary {
/// Return a new dictionary that has the specified key-value pair in addition
/// to all existing elements in this dictionary.
///
/// If `self` already contains the given key, then the result replaces its
/// original value in `self` with `value`, without updating the existing key.
/// (In some cases, equal keys may be distinguishable from each other by
/// identity comparison or some other means.)
///
/// - Parameters:
/// - value: The new value to add to the dictionary.
/// - key: The key to associate with `value`. If `key` already exists in
/// the dictionary, `value` replaces the existing associated value in the
/// result. If `key` isn't already a key of the dictionary, then the
/// `(key, value)` pair is added to the result.
///
/// - Returns: A new dictionary with the update applied.
///
/// - Complexity: This operation is expected to copy at most O(log(`count`))
/// existing members and to perform at most O(1) hashing/comparison
/// operations on the `Element` type, as long as `Element` properly
/// implements hashing.
@inlinable
public func updatingValue(_ value: Value, forKey key: Key) -> Self {
var copy = self
copy.updateValue(value, forKey: key)
return copy
}
/// Return a new dictionary that contains all key-value pairs that are in
/// this dictionary except for the pair that matches given `key`.
///
/// If this dictionary does not contain a value for `key`, then this
/// method simply returns `self`.
///
/// - Parameter key: The key to remove from the returned dictionary.
///
/// - Returns: A new dictionary with all existing key-value pairs in `self`
/// except for the one that matches `key` (if any).
///
/// - Complexity: This operation is expected to copy at most O(log(`count`))
/// existing members and to perform at most O(1) hashing/comparison
/// operations on the `Element` type, as long as `Element` properly
/// implements hashing.
@inlinable
public func removingValue(forKey key: Key) -> Self {
guard let r = _root.removing(.top, key, _Hash(key)) else { return self }
return Self(_new: r.replacement.finalize(.top))
}
}
@@ -10,6 +10,10 @@
//===----------------------------------------------------------------------===//
extension PersistentDictionary: Hashable where Value: Hashable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Complexity: O(`count`)
@inlinable
public func hash(into hasher: inout Hasher) {
var commutativeHash = 0
@@ -10,26 +10,67 @@
//===----------------------------------------------------------------------===//
extension PersistentDictionary {
/// Creates an empty dictionary.
///
/// This initializer is equivalent to initializing with an empty dictionary
/// literal.
///
/// - Complexity: O(1)
@inlinable
public init() {
self.init(_new: ._emptyNode())
}
/// Makes a copy of an existing persistent dictionary.
///
/// - Complexity: O(1)
@inlinable
public init(_ other: PersistentDictionary<Key, Value>) {
self = other
}
// FIXME: This is a non-standard addition
/// Creates a new persistent dictionary that contains the same key-value
/// pairs as the given `Dictionary` instance, although not necessarily
/// in the same order.
///
/// - Complexity: O(`other.count`)
@inlinable
public init(_ other: Dictionary<Key, Value>) {
self.init(_uniqueKeysWithValues: other)
}
/// Creates a new persistent dictionary by associating the given persistent
/// set of keys with the values generated using the specified closure.
///
/// - Complexity: O(`other.count`)
@inlinable
public init(
keys: PersistentSet<Key>,
_ valueTransform: (Key) throws -> Value
valueGenerator valueTransform: (Key) throws -> Value
) rethrows {
// FIXME: This is a non-standard addition
let root = try keys._root.mapValues { try valueTransform($0.key) }
self.init(_new: root)
}
/// Creates a new dictionary from the key-value pairs in the given sequence.
///
/// You use this initializer to create a dictionary when you have a sequence
/// of key-value tuples with unique keys. Passing a sequence with duplicate
/// keys to this initializer results in a runtime error. If your
/// sequence might have duplicate keys, use the
/// `Dictionary(_:uniquingKeysWith:)` initializer instead.
///
/// - Parameter keysAndValues: A sequence of key-value pairs to use for
/// the new dictionary. Every key in `keysAndValues` must be unique.
///
/// - Returns: A new dictionary initialized with the elements of
/// `keysAndValues`.
///
/// - Precondition: The sequence must not have duplicate keys.
///
/// - Complexity: Expected O(*n*) on average, where *n* is the count if
/// key-value pairs, if `Key` properly implements hashing.
@inlinable
public init<S: Sequence>(
uniqueKeysWithValues keysAndValues: S
@@ -43,6 +84,24 @@ extension PersistentDictionary {
_invariantCheck()
}
/// Creates a new dictionary from the key-value pairs in the given sequence.
///
/// You use this initializer to create a dictionary when you have a sequence
/// of key-value tuples with unique keys. Passing a sequence with duplicate
/// keys to this initializer results in a runtime error. If your
/// sequence might have duplicate keys, use the
/// `Dictionary(_:uniquingKeysWith:)` initializer instead.
///
/// - Parameter keysAndValues: A sequence of key-value pairs to use for
/// the new dictionary. Every key in `keysAndValues` must be unique.
///
/// - Returns: A new dictionary initialized with the elements of
/// `keysAndValues`.
///
/// - Precondition: The sequence must not have duplicate keys.
///
/// - Complexity: Expected O(*n*) on average, where *n* is the count if
/// key-value pairs, if `Key` properly implements hashing.
@_disfavoredOverload // https://github.com/apple/swift-collections/issues/125
@inlinable
public init<S: Sequence>(
@@ -52,18 +111,58 @@ extension PersistentDictionary {
self = keysAndValues as! Self
return
}
self.init(
uniqueKeysWithValues: keysAndValues.lazy.map { ($0.key, $0.value ) })
if S.self == Dictionary<Key, Value>.self {
self.init(keysAndValues as! Dictionary<Key, Value>)
return
}
self.init(_uniqueKeysWithValues: keysAndValues)
}
@inlinable
public init<Keys: Sequence, Values: Sequence>(
uniqueKeys keys: Keys,
values: Values
) where Keys.Element == Key, Values.Element == Value {
self.init(uniqueKeysWithValues: zip(keys, values))
internal init<S: Sequence>(
_uniqueKeysWithValues keysAndValues: S
) where S.Element == Element {
self.init()
for item in keysAndValues {
let hash = _Hash(item.key)
let r = _root.insert(.top, item, hash)
precondition(r.inserted, "Duplicate key: '\(item.key)'")
}
_invariantCheck()
}
/// Creates a new dictionary from the key-value pairs in the given sequence,
/// using a combining closure to determine the value for any duplicate keys.
///
/// You use this initializer to create a dictionary when you have a sequence
/// of key-value tuples that might have duplicate keys. As the dictionary is
/// built, the initializer calls the `combine` closure with the current and
/// new values for any duplicate keys. Pass a closure as `combine` that
/// returns the value to use in the resulting dictionary: The closure can
/// choose between the two values, combine them to produce a new value, or
/// even throw an error.
///
/// let pairsWithDuplicateKeys = [("a", 1), ("b", 2), ("a", 3), ("b", 4)]
///
/// let firstValues = PersistentDictionary(
/// pairsWithDuplicateKeys,
/// uniquingKeysWith: { (first, _) in first })
/// // ["a": 1, "b": 2]
///
/// let lastValues = PersistentDictionary(
/// pairsWithDuplicateKeys,
/// uniquingKeysWith: { (_, last) in last })
/// // ["a": 3, "b": 4]
///
/// - Parameters:
/// - keysAndValues: A sequence of key-value pairs to use for the new
/// dictionary.
/// - combine: A closure that is called with the values for any duplicate
/// keys that are encountered. The closure returns the desired value for
/// the final dictionary.
///
/// - Complexity: Expected O(*n*) on average, where *n* is the count of
/// key-value pairs, if `Key` properly implements hashing.
public init<S: Sequence>(
_ keysAndValues: S, uniquingKeysWith combine: (Value, Value) throws -> Value
) rethrows where S.Element == (Key, Value) {
@@ -71,6 +170,38 @@ extension PersistentDictionary {
try self.merge(keysAndValues, uniquingKeysWith: combine)
}
/// Creates a new dictionary from the key-value pairs in the given sequence,
/// using a combining closure to determine the value for any duplicate keys.
///
/// You use this initializer to create a dictionary when you have a sequence
/// of key-value tuples that might have duplicate keys. As the dictionary is
/// built, the initializer calls the `combine` closure with the current and
/// new values for any duplicate keys. Pass a closure as `combine` that
/// returns the value to use in the resulting dictionary: The closure can
/// choose between the two values, combine them to produce a new value, or
/// even throw an error.
///
/// let pairsWithDuplicateKeys = [("a", 1), ("b", 2), ("a", 3), ("b", 4)]
///
/// let firstValues = PersistentDictionary(
/// pairsWithDuplicateKeys,
/// uniquingKeysWith: { (first, _) in first })
/// // ["a": 1, "b": 2]
///
/// let lastValues = PersistentDictionary(
/// pairsWithDuplicateKeys,
/// uniquingKeysWith: { (_, last) in last })
/// // ["a": 3, "b": 4]
///
/// - Parameters:
/// - keysAndValues: A sequence of key-value pairs to use for the new
/// dictionary.
/// - combine: A closure that is called with the values for any duplicate
/// keys that are encountered. The closure returns the desired value for
/// the final dictionary.
///
/// - Complexity: Expected O(*n*) on average, where *n* is the count of
/// key-value pairs, if `Key` properly implements hashing.
@_disfavoredOverload // https://github.com/apple/swift-collections/issues/125
public init<S: Sequence>(
_ keysAndValues: S, uniquingKeysWith combine: (Value, Value) throws -> Value
@@ -82,6 +213,31 @@ extension PersistentDictionary {
}
extension PersistentDictionary {
/// Creates a new dictionary whose keys are the groupings returned by the
/// given closure and whose values are arrays of the elements that returned
/// each key.
///
/// The arrays in the "values" position of the new dictionary each contain at
/// least one element, with the elements in the same order as the source
/// sequence.
///
/// The following example declares an array of names, and then creates a
/// dictionary from that array by grouping the names by first letter:
///
/// let students = ["Kofi", "Abena", "Efua", "Kweku", "Akosua"]
/// let studentsByLetter = PersistentDictionary(grouping: students, by: { $0.first! })
/// // ["K": ["Kofi", "Kweku"], "A": ["Abena", "Akosua"], "E": ["Efua"]]
///
/// The new `studentsByLetter` dictionary has three entries, with students'
/// names grouped by the keys `"E"`, `"K"`, and `"A"`.
///
/// - Parameters:
/// - values: A sequence of values to group into a dictionary.
/// - keyForValue: A closure that returns a key for each element in
/// `values`.
///
/// - Complexity: Expected O(*n*) on average, where *n* is the count of
/// values, if `Key` properly implements hashing.
@inlinable @inline(__always)
public init<S: Sequence>(
grouping values: S,
@@ -92,6 +248,31 @@ extension PersistentDictionary {
try self.init(_grouping: values, by: keyForValue)
}
/// Creates a new dictionary whose keys are the groupings returned by the
/// given closure and whose values are arrays of the elements that returned
/// each key.
///
/// The arrays in the "values" position of the new dictionary each contain at
/// least one element, with the elements in the same order as the source
/// sequence.
///
/// The following example declares an array of names, and then creates a
/// dictionary from that array by grouping the names by first letter:
///
/// let students = ["Kofi", "Abena", "Efua", "Kweku", "Akosua"]
/// let studentsByLetter = PersistentDictionary(grouping: students, by: { $0.first! })
/// // ["K": ["Kofi", "Kweku"], "A": ["Abena", "Akosua"], "E": ["Efua"]]
///
/// The new `studentsByLetter` dictionary has three entries, with students'
/// names grouped by the keys `"E"`, `"K"`, and `"A"`.
///
/// - Parameters:
/// - values: A sequence of values to group into a dictionary.
/// - keyForValue: A closure that returns a key for each element in
/// `values`.
///
/// - Complexity: Expected O(*n*) on average, where *n* is the count of
/// values, if `Key` properly implements hashing.
@inlinable @inline(__always)
public init<S: Sequence>(
grouping values: S,
@@ -12,7 +12,7 @@
import _CollectionsUtilities
extension PersistentDictionary {
/// A view of a dictionary’s keys.
/// A view of a persistent dictionary’s keys, as a standalone collection.
@frozen
public struct Keys {
@usableFromInline
@@ -28,6 +28,8 @@ extension PersistentDictionary {
}
/// A collection containing just the keys of the dictionary.
///
/// - Complexity: O(1)
@inlinable
public var keys: Keys {
Keys(_base: self)
@@ -39,9 +41,31 @@ extension PersistentDictionary.Keys: Sendable
where Key: Sendable, Value: Sendable {}
#endif
extension PersistentDictionary.Keys: _UniqueCollection {}
extension PersistentDictionary.Keys: CustomStringConvertible {
// A textual representation of this instance.
public var description: String {
_arrayDescription(for: self)
}
}
extension PersistentDictionary.Keys: CustomDebugStringConvertible {
/// A textual representation of this instance, suitable for debugging.
public var debugDescription: String {
_arrayDescription(
for: self,
debug: true,
typeName: "\(PersistentDictionary._debugTypeName()).Keys")
}
}
extension PersistentDictionary.Keys: Sequence {
/// The element type of the collection.
public typealias Element = Key
/// The type that allows iteration over the elements of the keys view
/// of a persistent dictionary.
@frozen
public struct Iterator: IteratorProtocol {
public typealias Element = Key
@@ -72,6 +96,16 @@ extension PersistentDictionary.Keys: Sequence {
_base._root.containsKey(.top, element, _Hash(element))
}
/// Returns a Boolean value that indicates whether the given key exists
/// in the dictionary.
///
/// - Parameter element: A key to look for in the dictionary/
///
/// - Returns: `true` if `element` exists in the set; otherwise, `false`.
///
/// - Complexity: This operation is expected to perform O(1) hashing and
/// comparison operations on average, provided that `Element` implements
/// high-quality hashing.
@inlinable
public func contains(_ element: Element) -> Bool {
_base._root.containsKey(.top, element, _Hash(element))
@@ -83,7 +117,7 @@ extension PersistentDictionary.Keys.Iterator: Sendable
where Key: Sendable, Value: Sendable {}
#endif
extension PersistentDictionary.Keys: BidirectionalCollection {
extension PersistentDictionary.Keys: Collection {
public typealias Index = PersistentDictionary.Index
@inlinable
@@ -108,21 +142,11 @@ extension PersistentDictionary.Keys: BidirectionalCollection {
_base.formIndex(after: &i)
}
@inlinable
public func formIndex(before i: inout Index) {
_base.formIndex(before: &i)
}
@inlinable
public func index(after i: Index) -> Index {
_base.index(after: i)
}
@inlinable
public func index(before i: Index) -> Index {
_base.index(before: i)
}
@inlinable
public func index(_ i: Index, offsetBy distance: Int) -> Index {
_base.index(i, offsetBy: distance)
@@ -140,3 +164,124 @@ extension PersistentDictionary.Keys: BidirectionalCollection {
_base.distance(from: start, to: end)
}
}
#if false
extension PersistentDictionary.Keys: BidirectionalCollection {
// Note: Let's not do this. `BidirectionalCollection` would imply that
// the ordering of elements would be meaningful, which isn't true for
// `PersistentDictionary.Keys`.
@inlinable
public func formIndex(before i: inout Index) {
_base.formIndex(before: &i)
}
@inlinable
public func index(before i: Index) -> Index {
_base.index(before: i)
}
}
#endif
extension PersistentDictionary.Keys {
/// Returns a new keys view with the elements that are common to both this
/// view and the provided other one.
///
/// var a: PersistentDictionary = ["a": 1, "b": 2, "c": 3]
/// let b: PersistentDictionary = ["b": 4, "d": 5, "e": 6]
/// let c = a.keys.intersection(b.keys)
/// // `c` is `["b"]`
///
/// The result will only contain instances that were originally in `self`.
/// (This matters if equal members can be distinguished by comparing their
/// identities, or by some other means.)
///
/// - Parameter other: The keys view of a persistent dictionary with the same
/// `Key` type.
///
/// - Complexity: Expected complexity is O(`self.count`) in
/// the worst case, if `Element` properly implements hashing.
/// However, the implementation is careful to make the best use of
/// hash tree structure to minimize work when possible, e.g. by linking
/// parts of the input trees directly into the result.
public func intersection<Value2>(
_ other: PersistentDictionary<Key, Value2>.Keys
) -> Self {
guard let r = _base._root.intersection(.top, other._base._root) else {
return self
}
return PersistentDictionary(_new: r).keys
}
/// Returns a new keys view with the elements that are common to both this
/// view and the provided persistent set.
///
/// var a: PersistentDictionary = ["a": 1, "b": 2, "c": 3]
/// let b: PersistentSet = ["b", "d", "e"]
/// let c = a.keys.intersection(b)
/// // `c` is `["b"]`
///
/// The result will only contain instances that were originally in `self`.
/// (This matters if equal members can be distinguished by comparing their
/// identities, or by some other means.)
///
/// - Parameter other: A persistent set whose `Element` type is `Key`.
///
/// - Complexity: Expected complexity is O(`self.count`) in
/// the worst case, if `Element` properly implements hashing.
/// However, the implementation is careful to make the best use of
/// hash tree structure to minimize work when possible, e.g. by linking
/// parts of the input trees directly into the result.
public func intersection(_ other: PersistentSet<Key>) -> Self {
guard let r = _base._root.intersection(.top, other._root) else {
return self
}
return PersistentDictionary(_new: r).keys
}
/// Returns a new keys view containing the elements of `self` that do not
/// occur in the provided other one.
///
/// var a: PersistentDictionary = ["a": 1, "b": 2, "c": 3]
/// let b: PersistentDictionary = ["b": 4, "d": 5, "e": 6]
/// let c = a.keys.subtracting(b.keys)
/// // `c` is some permutation of `["a", "c"]`
///
/// - Parameter other: The keys view of a persistent dictionary with the same
/// `Key` type.
///
/// - Complexity: Expected complexity is O(`self.count`) in
/// the worst case, if `Element` properly implements hashing.
/// However, the implementation is careful to make the best use of
/// hash tree structure to minimize work when possible, e.g. by linking
/// parts of the input trees directly into the result.
public func subtracting<Value2>(
_ other: PersistentDictionary<Key, Value2>.Keys
) -> Self {
guard let r = _base._root.subtracting(.top, other._base._root) else {
return self
}
return PersistentDictionary(_new: r).keys
}
/// Returns a new keys view containing the elements of `self` that do not
/// occur in the provided persistent set.
///
/// var a: PersistentDictionary = ["a": 1, "b": 2, "c": 3]
/// let b: PersistentSet = ["b", "d", "e"]
/// let c = a.keys.subtracting(b)
/// // `c` is some permutation of `["a", "c"]`
///
/// - Parameter other: A persistent set whose `Element` type is `Key`.
///
/// - Complexity: Expected complexity is O(`self.count`) in
/// the worst case, if `Element` properly implements hashing.
/// However, the implementation is careful to make the best use of
/// hash tree structure to minimize work when possible, e.g. by linking
/// parts of the input trees directly into the result.
public func subtracting(_ other: PersistentSet<Key>) -> Self {
guard let r = _base._root.subtracting(.top, other._root) else {
return self
}
return PersistentDictionary(_new: r).keys
}
}
@@ -10,6 +10,16 @@
//===----------------------------------------------------------------------===//
extension PersistentDictionary {
/// Returns a new dictionary containing the keys of this dictionary with the
/// values transformed by the given closure.
///
/// - Parameter transform: A closure that transforms a value. `transform`
/// accepts each value of the dictionary as its parameter and returns a
/// transformed value of the same or of a different type.
/// - Returns: A dictionary containing the keys and transformed values of
/// this dictionary.
///
/// - Complexity: O(`count`)
@inlinable
public func mapValues<T>(
_ transform: (Value) throws -> T
@@ -18,6 +28,32 @@ extension PersistentDictionary {
return PersistentDictionary<Key, T>(_new: transformed)
}
/// Returns a new dictionary containing only the key-value pairs that have
/// non-`nil` values as the result of transformation by the given closure.
///
/// Use this method to receive a dictionary with non-optional values when
/// your transformation produces optional values.
///
/// In this example, note the difference in the result of using `mapValues`
/// and `compactMapValues` with a transformation that returns an optional
/// `Int` value.
///
/// let data: PersistentDictionary = ["a": "1", "b": "three", "c": "///4///"]
///
/// let m: [String: Int?] = data.mapValues { str in Int(str) }
/// // ["a": Optional(1), "b": nil, "c": nil]
///
/// let c: [String: Int] = data.compactMapValues { str in Int(str) }
/// // ["a": 1]
///
/// - Parameter transform: A closure that transforms a value. `transform`
/// accepts each value of the dictionary as its parameter and returns an
/// optional transformed value of the same or of a different type.
///
/// - Returns: A dictionary containing the keys and non-`nil` transformed
/// values of this dictionary.
///
/// - Complexity: O(`count`)
@inlinable
public func compactMapValues<T>(
_ transform: (Value) throws -> T?
@@ -10,6 +10,33 @@
//===----------------------------------------------------------------------===//
extension PersistentDictionary {
/// Merges the key-value pairs in the given sequence into the dictionary,
/// using a combining closure to determine the value for any duplicate keys.
///
/// Use the `combine` closure to select a value to use in the updated
/// dictionary, or to combine existing and new values. As the key-value
/// pairs are merged with the dictionary, the `combine` closure is called
/// with the current and new values for any duplicate keys that are
/// encountered.
///
/// This example shows how to choose the current or new values for any
/// duplicate keys:
///
/// var dictionary: PersistentDictionary = ["a": 1, "b": 2]
///
/// // Keeping existing value for key "a":
/// dictionary.merge(zip(["a", "c"], [3, 4])) { (current, _) in current }
/// // ["a": 1, "b": 2, "c": 4] (in some order)
///
/// // Taking the new value for key "a":
/// dictionary.merge(zip(["a", "d"], [5, 6])) { (_, new) in new }
/// // ["a": 5, "b": 2, "c": 4, "d": 6] (in some order)
///
/// - Parameters:
/// - keysAndValues: A sequence of key-value pairs.
/// - combine: A closure that takes the current and new values for any
/// duplicate keys. The closure returns the desired value for the final
/// dictionary.
@inlinable
public mutating func merge(
_ keysAndValues: Self,
@@ -19,6 +46,33 @@ extension PersistentDictionary {
try _root.merge(.top, keysAndValues._root, combine)
}
/// Merges the key-value pairs in the given sequence into the dictionary,
/// using a combining closure to determine the value for any duplicate keys.
///
/// Use the `combine` closure to select a value to use in the updated
/// dictionary, or to combine existing and new values. As the key-value
/// pairs are merged with the dictionary, the `combine` closure is called
/// with the current and new values for any duplicate keys that are
/// encountered.
///
/// This example shows how to choose the current or new values for any
/// duplicate keys:
///
/// var dictionary: PersistentDictionary = ["a": 1, "b": 2]
///
/// // Keeping existing value for key "a":
/// dictionary.merge(zip(["a", "c"], [3, 4])) { (current, _) in current }
/// // ["a": 1, "b": 2, "c": 4] (in some order)
///
/// // Taking the new value for key "a":
/// dictionary.merge(zip(["a", "d"], [5, 6])) { (_, new) in new }
/// // ["a": 5, "b": 2, "c": 4, "d": 6] (in some order)
///
/// - Parameters:
/// - keysAndValues: A sequence of key-value pairs.
/// - combine: A closure that takes the current and new values for any
/// duplicate keys. The closure returns the desired value for the final
/// dictionary.
@inlinable
public mutating func merge<S: Sequence>(
_ keysAndValues: __owned S,
@@ -35,6 +89,33 @@ extension PersistentDictionary {
}
}
/// Merges the key-value pairs in the given sequence into the dictionary,
/// using a combining closure to determine the value for any duplicate keys.
///
/// Use the `combine` closure to select a value to use in the updated
/// dictionary, or to combine existing and new values. As the key-value
/// pairs are merged with the dictionary, the `combine` closure is called
/// with the current and new values for any duplicate keys that are
/// encountered.
///
/// This example shows how to choose the current or new values for any
/// duplicate keys:
///
/// var dictionary: PersistentDictionary = ["a": 1, "b": 2]
///
/// // Keeping existing value for key "a":
/// dictionary.merge(zip(["a", "c"], [3, 4])) { (current, _) in current }
/// // ["a": 1, "b": 2, "c": 4] (in some order)
///
/// // Taking the new value for key "a":
/// dictionary.merge(zip(["a", "d"], [5, 6])) { (_, new) in new }
/// // ["a": 5, "b": 2, "c": 4, "d": 6] (in some order)
///
/// - Parameters:
/// - keysAndValues: A sequence of key-value pairs.
/// - combine: A closure that takes the current and new values for any
/// duplicate keys. The closure returns the desired value for the final
/// dictionary.
@_disfavoredOverload // https://github.com/apple/swift-collections/issues/125
@inlinable
public mutating func merge<S: Sequence>(
@@ -46,6 +127,41 @@ extension PersistentDictionary {
uniquingKeysWith: combine)
}
/// Creates a dictionary by merging key-value pairs in a sequence into this
/// dictionary, using a combining closure to determine the value for
/// duplicate keys.
///
/// Use the `combine` closure to select a value to use in the returned
/// dictionary, or to combine existing and new values. As the key-value
/// pairs are merged with the dictionary, the `combine` closure is called
/// with the current and new values for any duplicate keys that are
/// encountered.
///
/// This example shows how to choose the current or new values for any
/// duplicate keys:
///
/// let dictionary: OrderedDictionary = ["a": 1, "b": 2]
/// let newKeyValues = zip(["a", "b"], [3, 4])
///
/// let keepingCurrent = dictionary.merging(newKeyValues) { (current, _) in current }
/// // ["a": 1, "b": 2]
/// let replacingCurrent = dictionary.merging(newKeyValues) { (_, new) in new }
/// // ["a": 3, "b": 4]
///
/// - Parameters:
/// - other: A sequence of key-value pairs.
/// - combine: A closure that takes the current and new values for any
/// duplicate keys. The closure returns the desired value for the final
/// dictionary.
///
/// - Returns: A new dictionary with the combined keys and values of this
/// dictionary and `other`. The order of keys in the result dictionary
/// matches that of `self`, with additional key-value pairs (if any)
/// appended at the end in the order they appear in `other`.
///
/// - Complexity: Expected to be O(`count` + *n*) on average, where *n* is the
/// number of elements in `keysAndValues`, if `Key` implements high-quality
/// hashing.
@inlinable
public func merging(
_ other: Self,
@@ -56,6 +172,41 @@ extension PersistentDictionary {
return copy
}
/// Creates a dictionary by merging key-value pairs in a sequence into this
/// dictionary, using a combining closure to determine the value for
/// duplicate keys.
///
/// Use the `combine` closure to select a value to use in the returned
/// dictionary, or to combine existing and new values. As the key-value
/// pairs are merged with the dictionary, the `combine` closure is called
/// with the current and new values for any duplicate keys that are
/// encountered.
///
/// This example shows how to choose the current or new values for any
/// duplicate keys:
///
/// let dictionary: OrderedDictionary = ["a": 1, "b": 2]
/// let newKeyValues = zip(["a", "b"], [3, 4])
///
/// let keepingCurrent = dictionary.merging(newKeyValues) { (current, _) in current }
/// // ["a": 1, "b": 2]
/// let replacingCurrent = dictionary.merging(newKeyValues) { (_, new) in new }
/// // ["a": 3, "b": 4]
///
/// - Parameters:
/// - other: A sequence of key-value pairs.
/// - combine: A closure that takes the current and new values for any
/// duplicate keys. The closure returns the desired value for the final
/// dictionary.
///
/// - Returns: A new dictionary with the combined keys and values of this
/// dictionary and `other`. The order of keys in the result dictionary
/// matches that of `self`, with additional key-value pairs (if any)
/// appended at the end in the order they appear in `other`.
///
/// - Complexity: Expected to be O(`count` + *n*) on average, where *n* is the
/// number of elements in `keysAndValues`, if `Key` implements high-quality
/// hashing.
@inlinable
public func merging<S: Sequence>(
_ other: __owned S,
@@ -67,6 +218,41 @@ extension PersistentDictionary {
return copy
}
/// Creates a dictionary by merging key-value pairs in a sequence into this
/// dictionary, using a combining closure to determine the value for
/// duplicate keys.
///
/// Use the `combine` closure to select a value to use in the returned
/// dictionary, or to combine existing and new values. As the key-value
/// pairs are merged with the dictionary, the `combine` closure is called
/// with the current and new values for any duplicate keys that are
/// encountered.
///
/// This example shows how to choose the current or new values for any
/// duplicate keys:
///
/// let dictionary: OrderedDictionary = ["a": 1, "b": 2]
/// let newKeyValues = zip(["a", "b"], [3, 4])
///
/// let keepingCurrent = dictionary.merging(newKeyValues) { (current, _) in current }
/// // ["a": 1, "b": 2]
/// let replacingCurrent = dictionary.merging(newKeyValues) { (_, new) in new }
/// // ["a": 3, "b": 4]
///
/// - Parameters:
/// - other: A sequence of key-value pairs.
/// - combine: A closure that takes the current and new values for any
/// duplicate keys. The closure returns the desired value for the final
/// dictionary.
///
/// - Returns: A new dictionary with the combined keys and values of this
/// dictionary and `other`. The order of keys in the result dictionary
/// matches that of `self`, with additional key-value pairs (if any)
/// appended at the end in the order they appear in `other`.
///
/// - Complexity: Expected to be O(`count` + *n*) on average, where *n* is the
/// number of elements in `keysAndValues`, if `Key` implements high-quality
/// hashing.
@_disfavoredOverload // https://github.com/apple/swift-collections/issues/125
@inlinable
public func merging<S: Sequence>(
@@ -10,8 +10,11 @@
//===----------------------------------------------------------------------===//
extension PersistentDictionary: Sequence {
/// The element type of a dictionary: a tuple containing an individual
/// key-value pair.
public typealias Element = (key: Key, value: Value)
/// The type that allows iteration over a persistent dictionary's elements.
@frozen
public struct Iterator {
// Fixed-stack iterator for traversing a hash tree.
@@ -30,11 +33,18 @@ extension PersistentDictionary: Sequence {
}
}
/// A value less than or equal to the number of elements in the sequence,
/// calculated nondestructively.
///
/// - Complexity: O(1)
@inlinable
public var underestimatedCount: Int {
_root.count
}
/// Returns an iterator over the elements of this collection.
///
/// - Complexity: O(1)
@inlinable
public __consuming func makeIterator() -> Iterator {
return Iterator(_root: _root.raw)
@@ -47,8 +57,16 @@ where Key: Sendable, Value: Sendable {}
#endif
extension PersistentDictionary.Iterator: IteratorProtocol {
/// The element type of a dictionary: a tuple containing an individual
/// key-value pair.
public typealias Element = (key: Key, value: Value)
/// Advances to the next element and returns it, or `nil` if no next
/// element exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
///
/// - Complexity: O(1)
@inlinable
public mutating func next() -> Element? {
guard let (node, slot) = _it.next() else { return nil }
@@ -9,6 +9,8 @@
//
//===----------------------------------------------------------------------===//
import _CollectionsUtilities
extension PersistentDictionary {
/// A view of a dictionary’s values.
@frozen
@@ -31,20 +33,11 @@ extension PersistentDictionary {
/// A collection containing just the values of the dictionary.
@inlinable
public var values: Values {
// Note: this property is kept read only for now until we decide whether
// it's worth providing setters without a `MutableCollection` conformance.
get {
Values(_base: self)
}
set { // FIXME: Consider removing
self = newValue._base
}
_modify { // FIXME: Consider removing
var values = Values(_base: self)
self = Self()
defer {
self = values._base
}
yield &values
}
}
}
@@ -53,6 +46,23 @@ extension PersistentDictionary.Values: Sendable
where Key: Sendable, Value: Sendable {}
#endif
extension PersistentDictionary.Values: CustomStringConvertible {
// A textual representation of this instance.
public var description: String {
_arrayDescription(for: self)
}
}
extension PersistentDictionary.Values: CustomDebugStringConvertible {
/// A textual representation of this instance, suitable for debugging.
public var debugDescription: String {
_arrayDescription(
for: self,
debug: true,
typeName: "\(PersistentDictionary._debugTypeName()).Values")
}
}
extension PersistentDictionary.Values: Sequence {
public typealias Element = Value
@@ -87,7 +97,7 @@ where Key: Sendable, Value: Sendable {}
// Note: This cannot be a MutableCollection because its subscript setter
// needs to invalidate indices.
extension PersistentDictionary.Values: BidirectionalCollection {
extension PersistentDictionary.Values: Collection {
public typealias Index = PersistentDictionary.Index
@inlinable
@@ -104,29 +114,13 @@ extension PersistentDictionary.Values: BidirectionalCollection {
@inlinable
public subscript(index: Index) -> Element {
// The subscript is kept read only for now until we decide whether it's
// worth providing setters without a `MutableCollection` conformance.
// (With the current index implementation, mutating values must invalidate
// indices.)
get {
_base[index].value
}
set { // FIXME: Consider removing
precondition(_base._isValid(index), "Invalid index")
precondition(index._path.isOnItem, "Cannot set value at end index")
let (leaf, slot) = _base._root.ensureUnique(level: .top, at: index._path)
_UnsafeHandle.update(leaf) { $0[item: slot].value = newValue }
_base._invalidateIndices()
}
_modify { // FIXME: Consider removing
precondition(_base._isValid(index), "Invalid index")
precondition(index._path.isOnItem, "Cannot set value at end index")
let (leaf, slot) = _base._root.ensureUnique(level: .top, at: index._path)
var item = _UnsafeHandle.update(leaf) { $0.itemPtr(at: slot).move() }
defer {
_Node.UnsafeHandle.update(leaf) {
$0.itemPtr(at: slot).initialize(to: item)
}
_base._invalidateIndices()
}
yield &item.value
}
}
@inlinable
@@ -134,21 +128,11 @@ extension PersistentDictionary.Values: BidirectionalCollection {
_base.formIndex(after: &i)
}
@inlinable
public func formIndex(before i: inout Index) {
_base.formIndex(before: &i)
}
@inlinable
public func index(after i: Index) -> Index {
_base.index(after: i)
}
@inlinable
public func index(before i: Index) -> Index {
_base.index(before: i)
}
@inlinable
public func index(_ i: Index, offsetBy distance: Int) -> Index {
_base.index(i, offsetBy: distance)
@@ -166,3 +150,20 @@ extension PersistentDictionary.Values: BidirectionalCollection {
_base.distance(from: start, to: end)
}
}
#if false
extension PersistentDictionary.Values: BidirectionalCollection {
// Note: Let's not do this. `BidirectionalCollection` would imply that
// the ordering of elements would be meaningful, which isn't true for
// `PersistentDictionary.Values`.
@inlinable
public func formIndex(before i: inout Index) {
_base.formIndex(before: &i)
}
@inlinable
public func index(before i: Index) -> Index {
_base.index(before: i)
}
}
#endif
@@ -9,6 +9,59 @@
//
//===----------------------------------------------------------------------===//
/// An unordered collection of unique keys and associated values, optimized for
/// mutating shared copies and comparing different snapshots of the same
/// collection.
///
/// `PersistentDictionary` has the same functionality as a standard
/// `Dictionary`, and it largely implements the same APIs: both are hashed
/// collection types with convenient and efficient ways to look up the value
/// associated with a particular key, and both types are unordered, meaning that
/// neither type provides any guarantees about the ordering of their items.
///
/// However, `PersistentDictionary` is optimizing specifically for use cases
/// that need to mutate shared copies or to compare a set value to one of its
/// older snapshots.
///
/// The standard `Dictionary` stores its members in a single, flat hash table,
/// and it implements value semantics with all-or-nothing copy-on-write
/// behavior: every time a shared copy of a set is mutated, the mutation needs
/// to make a full copy of the set's storage. `PersistentDictionary` takes a
/// different approach: it organizes its members into a tree structure, the
/// nodes of which can be freely shared across collection values. When mutating
/// a shared copy of a set value, `PersistentSet` is able to simply link the
/// unchanged parts of the tree directly into the result, saving both time and
/// memory.
///
/// This structural sharing also makes it more efficient to compare mutated
/// dictionaries values to earlier versions of themselves. When comparing or
/// combining dictionaries, parts that are shared across both inputs can
/// typically be handled in constant time, leading to a dramatic performance
/// boost when the two inputs are still largely unchanged:
///
/// var d = PersistentDictionary(
/// uniqueKeysWithValues: (0 ..< 10_000).map { ($0, 2 * $0) })
/// let copy = d
/// d[20_000] = 42 // Expected to be an O(log(n)) operation
/// let diff = d.keys.subtracting(copy.keys) // Also O(log(n))!
/// // `diff` now holds the single item 20_000.
///
/// The tree structure also eliminates the need to reserve capacity in advance:
/// `PersistentDictionary` creates, destroys and resizes individual nodes as
/// needed, always consuming just enough memory to store its contents. As of
/// Swift 5.7, the standard collection types never shrink their storage, so
/// temporary storage spikes can linger as unused but still allocated memory
/// long after the collection has shrunk back to its usual size.
///
/// Of course, switching to a tree structure comes with some trade offs. In
/// particular, inserting new items, removing existing ones, and iterating over
/// a `PersistentDictionary` is expected to be a constant factor slower than a
/// standard `Dictionary` -- allocating/deallocating nodes isn't free, and
/// navigating the tree structure requires more pointer dereferences than
/// accessing a flat hash table. However the algorithmic improvements above
/// usually more than make up for this, as long as the use case can make use of
/// them.
@frozen // Not really -- this package is not at all ABI stable
public struct PersistentDictionary<Key: Hashable, Value> {
@usableFromInline
internal typealias _Node = PersistentCollections._Node<Key, Value>
@@ -57,10 +110,6 @@ extension PersistentDictionary {
/// dictionary overwrites the existing value. If the dictionary doesn't
/// contain the key, the key and value are added as a new key-value pair.
///
/// Inserting a new key-value pair into a dictionary invalidates all
/// previously returned indices to it. Updating the value of an existing key
/// does not invalidate any indices.
///
/// Here, the value for the key `"Coral"` is updated from `16` to `18` and a
/// new key-value pair is added for the key `"Cerise"`.
///
@@ -73,9 +122,7 @@ extension PersistentDictionary {
/// // Prints "Optional(330)"
///
/// If you assign `nil` as the value for the given key, the dictionary
/// removes that key and its associated value. Removing an existing key-value
/// pair in the dictionary invalidates all previously returned indices to it.
/// Removing a key that doesn't exist does not invalidate any indices.
/// removes that key and its associated value.
///
/// In the following example, the key-value pair for the key `"Aquamarine"`
/// is removed from the dictionary by assigning `nil` to the key-based
@@ -85,19 +132,27 @@ extension PersistentDictionary {
/// print(hues)
/// // Prints "["Coral": 18, "Heliotrope": 296, "Cerise": 330]"
///
/// Updating the value of an existing key only modifies the value: it does not
/// change the key that is stored in the dictionary. (In some cases, equal
/// keys may be distinguishable from each other by identity comparison or
/// some other means.)
///
/// Removing or updating an existing key-value pair or inserting a new
/// key-value pair invalidates all indices in the dictionary. Removing a
/// key that doesn't exist does not invalidate any indices.
///
/// - Parameter key: The key to find in the dictionary.
///
/// - Returns: The value associated with `key` if `key` is in the dictionary;
/// otherwise, `nil`.
///
/// - Complexity: Traversing the hash tree to find a key requires visiting
/// O(log(`count`)) nodes. Looking up and updating values in the
/// dictionary through this subscript has an expected complexity of O(1)
/// hashing/comparison operations on average, if `Key` implements
/// high-quality hashing.
/// - Complexity: Looking up the value for a key is expected to traverse
/// O(log(`count`)) tree nodes and to do at most O(1) hashing/comparison
/// operations on the `Element` type, as long as `Element` properly
/// implements hashing.
///
/// When used to mutate dictionary values with shared storage, this
/// operation is expected to copy at most O(log(`count`)) items.
/// Updating the dictionary through this subscript is expected to copy at
/// most O(log(`count`)) existing members.
@inlinable
public subscript(key: Key) -> Value? {
get {
@@ -163,9 +218,12 @@ extension PersistentDictionary {
/// specified default value (`0`) is returned from the subscript,
/// incremented, and then added to the dictionary under that key.
///
/// Inserting a new key-value pair invalidates all existing indices in the
/// dictionary. Updating the value of an existing key does not invalidate
/// any indices.
/// Updating the value of an existing key only modifies the value: it does not
/// change the key that is stored in the dictionary. (In some cases, equal
/// keys may be distinguishable from each other by identity comparison or
/// some other means.)
///
/// Calling this method invalidates all existing indices in the dictionary.
///
/// - Note: Do not use this subscript to modify dictionary values if the
/// dictionary's `Value` type is a class. In that case, the default value
@@ -181,14 +239,12 @@ extension PersistentDictionary {
/// - Returns: The value associated with `key` in the dictionary; otherwise,
/// `defaultValue`.
///
/// - Complexity: Traversing the hash tree to find a key requires visiting
/// O(log(`count`)) nodes. Looking up and updating values in the
/// dictionary through this subscript has an expected complexity of O(1)
/// hashing/comparison operations on average, if `Key` implements
/// high-quality hashing.
/// - Complexity: Looking up the value for a key is expected to do at most
/// O(1) hashing/comparison operations on the `Element` type, as long as
/// `Element` properly implements hashing.
///
/// When used to mutate dictionary values with shared storage, this
/// operation is expected to copy at most O(log(`count`)) items.
/// Updating the dictionary through this subscript is expected to copy at
/// most O(log(`count`)) existing members.
@inlinable
public subscript(
key: Key,
@@ -213,13 +269,20 @@ extension PersistentDictionary {
}
}
// FIXME: New addition; needs discussion
@inlinable
public func contains(_ key: Key) -> Bool {
_root.containsKey(.top, key, _Hash(key))
}
/// Returns the index for the given key.
///
/// If the given key is found in the dictionary, this method returns an index
/// into the dictionary that corresponds with the key-value pair. If the
/// key is not found, then this method returns `nil`.
///
/// - Parameter key: The key to find in the dictionary.
///
/// - Returns: The index for `key` and its associated value if `key` is in
/// the dictionary; otherwise, `nil`.
///
/// - Complexity: This operation is expected to perform O(1) hashing and
/// comparison operations on average, provided that `Element` implements
/// high-quality hashing.
@inlinable
public func index(forKey key: Key) -> Index? {
guard let path = _root.path(to: key, _Hash(key))
@@ -255,9 +318,12 @@ extension PersistentDictionary {
/// }
/// // Prints "No value was found in the dictionary for that key."
///
/// Inserting a new key-value pair invalidates all existing indices in the
/// dictionary. Updating the value of an existing key does not invalidate
/// any indices.
/// Updating the value of an existing key only modifies the value: it does not
/// change the key that is stored in the dictionary. (In some cases, equal
/// keys may be distinguishable from each other by identity comparison or
/// some other means.)
///
/// Calling this method invalidates all existing indices in the dictionary.
///
/// - Parameters:
/// - value: The new value to add to the dictionary.
@@ -269,13 +335,10 @@ extension PersistentDictionary {
/// - Returns: The value that was replaced, or `nil` if a new key-value pair
/// was added.
///
/// - Complexity: Traversing the hash tree to find a key requires visiting
/// O(log(`count`)) nodes. Updating values in the has an expected
/// complexity of O(1) hashing/comparison operations on average, if
/// `Key` implements high-quality hashing.
///
/// When used to mutate dictionary values with shared storage, this
/// operation is expected to copy at most O(log(`count`)) items.
/// - Complexity: This operation is expected to copy at most O(log(`count`))
/// existing members and to perform at most O(1) hashing/comparison
/// operations on the `Element` type, as long as `Element` properly
/// implements hashing.
@inlinable
@discardableResult
public mutating func updateValue(
@@ -311,15 +374,48 @@ extension PersistentDictionary {
return false
}
// fluid/immutable API
@inlinable
public func updatingValue(_ value: Value, forKey key: Key) -> Self {
var copy = self
copy.updateValue(value, forKey: key)
return copy
}
// FIXME: New addition; needs discussion
/// Calls `body` to directly update the current value of `key` in the
/// dictionary.
///
/// You can use this method to perform in-place operations on values in the
/// dictionary, whether or not `Value` has value semantics. The following
/// example uses this method while counting the occurrences of each letter
/// in a string:
///
/// let message = "Hello, Elle!"
/// var letterCounts: PersistentDictionary<Character, Int> = [:]
/// for letter in message {
/// letterCounts.updateValue(forKey: letter) { count in
/// if count == nil {
/// count = 1
/// } else
/// count! += 1
/// }
/// }
/// }
/// // letterCounts == ["H": 1, "e": 2, "l": 4, "o": 1, ...]
///
/// Updating the value of an existing key only modifies the value: it does not
/// change the key that is stored in the dictionary. (In some cases, equal
/// keys may be distinguishable from each other by identity comparison or
/// some other means.)
///
/// Removing or updating an existing key-value pair or inserting a new
/// key-value pair invalidates all indices in the dictionary. Removing a
/// key that doesn't exist does not invalidate any indices.
///
/// - Parameters:
/// - key: The key whose value to look up.
/// - body: A function that performs an in-place mutation on the dictionary
/// value. If `key` exists in the dictionary, then `body` is called with
/// its current value; otherwise `body` is passed `nil`.
///
/// - Returns: The return value of `body`.
///
/// - Complexity: In addition to calling `body`, this operation is expected
/// to copy at most O(log(`count`)) existing members and to perform at
/// most O(1) hashing/comparison operations on the `Element` type, as long
/// as `Element` properly implements hashing.
@inlinable @inline(__always)
public mutating func updateValue<R>(
forKey key: Key,
@@ -328,6 +424,45 @@ extension PersistentDictionary {
try body(&self[key])
}
/// Ensures that the specified key exists in the dictionary (by inserting one
/// with the supplied default value if necessary), then calls `body` to update
/// it in place.
///
/// You can use this method to perform in-place operations on values in the
/// dictionary, whether or not `Value` has value semantics. The following
/// example uses this method while counting the occurrences of each letter
/// in a string:
///
/// let message = "Hello, Elle!"
/// var letterCounts: PersistentDictionary<Character, Int> = [:]
/// for letter in message {
/// letterCounts.updateValue(forKey: letter, default: 0) { count in
/// count += 1
/// }
/// }
/// // letterCounts == ["H": 1, "e": 2, "l": 4, "o": 1, ...]
///
/// Updating the value of an existing key only modifies the value: it does not
/// change the key that is stored in the dictionary. (In some cases, equal
/// keys may be distinguishable from each other by identity comparison or
/// some other means.)
///
/// Calling this method invalidates all existing indices in the dictionary.
///
/// - Parameters:
/// - key: The key to look up (or insert). If `key` does not already exist
/// in the dictionary, it is inserted with the supplied default value.
/// - defaultValue: The default value to insert if `key` doesn't exist in
/// the dictionary.
/// - body: A function that performs an in-place mutation on the dictionary
/// value.
///
/// - Returns: The return value of `body`.
///
/// - Complexity: In addition to calling `body`, this operation is expected
/// to copy at most O(log(`count`)) existing members and to perform at
/// most O(1) hashing/comparison operations on the `Element` type, as long
/// as `Element` properly implements hashing.
@inlinable
public mutating func updateValue<R>(
forKey key: Key,
@@ -348,7 +483,7 @@ extension PersistentDictionary {
/// If the key is found in the dictionary, this method returns the key's
/// associated value, and invalidates all previously returned indices.
///
/// var hues: OrderedDictionary = [
/// var hues: PersistentDictionary = [
/// "Heliotrope": 296,
/// "Coral": 16,
/// "Aquamarine": 156]
@@ -369,16 +504,14 @@ extension PersistentDictionary {
/// // Prints "No value found for that key.""
///
/// - Parameter key: The key to remove along with its associated value.
///
/// - Returns: The value that was removed, or `nil` if the key was not
/// present in the dictionary.
///
/// - Complexity: Traversing the hash tree to find a key requires visiting
/// O(log(`count`)) nodes. Updating values in the has an expected
/// complexity of O(1) hashing/comparison operations on average, if
/// `Key` implements high-quality hashing.
///
/// When used to mutate dictionary values with shared storage, this
/// operation is expected to copy at most O(log(`count`)) items.
/// - Complexity: In addition to calling `body`, this operation is expected
/// to copy at most O(log(`count`)) existing members and to perform at
/// most O(1) hashing/comparison operations on the `Element` type, as long
/// as `Element` properly implements hashing.
@inlinable
@discardableResult
public mutating func removeValue(forKey key: Key) -> Value? {
@@ -389,13 +522,19 @@ extension PersistentDictionary {
return r.removed.value
}
// fluid/immutable API
@inlinable
public func removingValue(forKey key: Key) -> Self {
guard let r = _root.removing(.top, key, _Hash(key)) else { return self }
return Self(_new: r.replacement.finalize(.top))
}
/// Removes and returns the key-value pair at the specified index.
///
/// Calling this method invalidates all existing indices in the dictionary.
///
/// - Parameter index: The position of the element to remove. `index` must be
/// a valid index of the dictionary that is not equal to `endIndex`.
///
/// - Returns: The removed key-value pair.
///
/// - Complexity: This operation is expected to copy at most O(log(`count`))
/// existing members and to perform at most O(1) hashing/comparison
/// operations on the `Element` type, as long as `Element` properly
/// implements hashing.
@inlinable
public mutating func remove(at index: Index) -> Element {
precondition(_isValid(index), "Invalid index")
@@ -10,7 +10,7 @@
//===----------------------------------------------------------------------===//
extension PersistentSet: Encodable where Element: Encodable {
/// Encodes the elements of this ordered set into the given encoder.
/// Encodes the elements of this set into the given encoder.
///
/// - Parameter encoder: The encoder to write data to.
@inlinable
@@ -21,7 +21,7 @@ extension PersistentSet: Encodable where Element: Encodable {
}
extension PersistentSet: Decodable where Element: Decodable {
/// Creates a new ordered set by decoding from the given decoder.
/// Creates a new set by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the decoded contents contain duplicate values.
@@ -10,6 +10,12 @@
//===----------------------------------------------------------------------===//
extension PersistentSet {
/// The position of an element in a persistent set.
///
/// An index in a persistent set is a compact encoding of a path in the
/// underlying prefix tree. Such indices are valid until the tree structure
/// is changed; hence, indices are usually invalidated every time the set
/// gets mutated.
@frozen
public struct Index {
@usableFromInline
@@ -38,6 +44,12 @@ where Element: Sendable {}
#endif
extension PersistentSet.Index: Equatable {
/// Returns a Boolean value indicating whether two index values are equal.
///
/// Note that comparing two indices that do not belong to the same tree
/// leads to a runtime error.
///
/// - Complexity: O(1)
@inlinable
public static func ==(left: Self, right: Self) -> Bool {
precondition(
@@ -48,6 +60,13 @@ extension PersistentSet.Index: Equatable {
}
extension PersistentSet.Index: Comparable {
/// Returns a Boolean value indicating whether the value of the first argument
/// is less than the second argument.
///
/// Note that comparing two indices that do not belong to the same tree
/// leads to a runtime error.
///
/// - Complexity: O(1)
@inlinable
public static func <(left: Self, right: Self) -> Bool {
precondition(
@@ -58,6 +77,10 @@ extension PersistentSet.Index: Comparable {
}
extension PersistentSet.Index: Hashable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// - Complexity: O(1)
@inlinable
public func hash(into hasher: inout Hasher) {
hasher.combine(_path)
@@ -65,28 +88,50 @@ extension PersistentSet.Index: Hashable {
}
extension PersistentSet.Index: CustomStringConvertible {
// A textual representation of this instance.
public var description: String {
_path.description
}
}
extension PersistentSet: BidirectionalCollection {
extension PersistentSet.Index: CustomDebugStringConvertible {
/// A textual representation of this instance, suitable for debugging.
public var debugDescription: String {
description
}
}
extension PersistentSet: Collection {
/// A Boolean value indicating whether the collection is empty.
///
/// - Complexity: O(1)
@inlinable
public var isEmpty: Bool {
_root.count == 0
}
/// The number of elements in the collection.
///
/// - Complexity: O(1)
@inlinable
public var count: Int {
_root.count
}
/// The position of the first element in a nonempty collection, or `endIndex`
/// if the collection is empty.
///
/// - Complexity: O(1)
public var startIndex: Index {
var path = _UnsafePath(root: _root.raw)
path.descendToLeftMostItem()
return Index(_root: _root.unmanaged, version: _version, path: path)
}
/// The collection’s “past the end” position—that is, the position one greater
/// than the last valid subscript argument.
///
/// - Complexity: O(1)
@inlinable
public var endIndex: Index {
var path = _UnsafePath(root: _root.raw)
@@ -105,15 +150,27 @@ extension PersistentSet: BidirectionalCollection {
}
/// Accesses the key-value pair at the specified position.
///
/// - Parameter position: The position of the element to access. `position`
/// must be a valid index of the collection that is not equal to
/// `endIndex`.
///
/// - Complexity: O(1)
@inlinable
public subscript(i: Index) -> Element {
precondition(_isValid(i), "Invalid index")
precondition(i._path.isOnItem, "Can't get element at endIndex")
return _UnsafeHandle.read(i._path.node) {
$0[item: i._path.currentItemSlot].key
public subscript(position: Index) -> Element {
precondition(_isValid(position), "Invalid index")
precondition(position._path.isOnItem, "Can't get element at endIndex")
return _UnsafeHandle.read(position._path.node) {
$0[item: position._path.currentItemSlot].key
}
}
/// Replaces the given index with its successor.
///
/// - Parameter i: A valid index of the collection.
/// `i` must be less than `endIndex`.
///
/// - Complexity: O(1)
@inlinable
public func formIndex(after i: inout Index) {
precondition(_isValid(i), "Invalid index")
@@ -122,14 +179,12 @@ extension PersistentSet: BidirectionalCollection {
}
}
@inlinable
public func formIndex(before i: inout Index) {
precondition(_isValid(i), "Invalid index")
guard i._path.findPredecessorItem(under: _root.raw) else {
preconditionFailure("The start index has no predecessor")
}
}
/// Returns the position immediately after the given index.
///
/// - Parameter i: A valid index of the collection.
/// `i` must be less than `endIndex`.
///
/// - Complexity: O(1)
@inlinable @inline(__always)
public func index(after i: Index) -> Index {
var i = i
@@ -137,19 +192,38 @@ extension PersistentSet: BidirectionalCollection {
return i
}
@inlinable @inline(__always)
public func index(before i: Index) -> Index {
var i = i
formIndex(before: &i)
return i
}
/// Returns the distance between two arbitrary valid indices in this
/// collection.
///
/// - Parameter start: A valid index of the collection.
/// - Parameter end: Another valid index of the collection.
/// - Returns: The distance between `start` and `end`.
/// (The result can be negative, even though `PersistentSet` is not a
/// bidirectional collection.)
/// - Complexity: O(log(`count`))
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
precondition(_isValid(start) && _isValid(end), "Invalid index")
return _root.raw.distance(.top, from: start._path, to: end._path)
}
/// Returns an index that is the specified distance from the given index.
///
/// The value passed as `distance` must not offset `i` beyond the bounds of
/// the collection.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - distance: The distance to offset `i`. As a special exception,
/// `distance` is allowed to be negative even though `PersistentSet`
/// isn't a bidirectional collection.
/// - Returns: An index offset by `distance` from the index `i`. If
/// `distance` is positive, this is the same value as the result of
/// `distance` calls to `index(after:)`. If distance is negative, then
/// `distance` calls to `index(after:)` on the returned value will be the
/// same as `start`.
///
/// - Complexity: O(log(`distance`))
@inlinable
public func index(_ i: Index, offsetBy distance: Int) -> Index {
precondition(_isValid(i), "Invalid index")
@@ -159,6 +233,27 @@ extension PersistentSet: BidirectionalCollection {
return i
}
/// Returns an index that is the specified distance from the given index,
/// unless that distance is beyond a given limiting index.
///
/// The value passed as `distance` must not offset `i` beyond the bounds of
/// the collection, unless the index passed as `limit` prevents offsetting
/// beyond those bounds.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - distance: The distance to offset `i`. As a special exception,
/// `distance` is allowed to be negative even though `PersistentSet`
/// isn't a bidirectional collection.
/// - limit: A valid index of the collection to use as a limit. If
/// `distance > 0`, a limit that is less than `i` has no effect.
/// Likewise, if `distance < 0`, a limit that is greater than `i` has no
/// effect.
/// - Returns: An index offset by `distance` from the index `i`, unless that
/// index would be beyond `limit` in the direction of movement. In that
/// case, the method returns `nil`.
///
/// - Complexity: O(log(`distance`))
@inlinable
public func index(
_ i: Index, offsetBy distance: Int, limitedBy limit: Index
@@ -188,6 +283,34 @@ extension PersistentSet: BidirectionalCollection {
_index(of: element)
}
/// Returns the index of the specified member of the collection, or `nil` if
/// the value isn't a member.
///
/// - Parameter element: An element to search for in the collection.
/// - Returns: The index where `element` is found. If `element` is not
/// found in the collection, returns `nil`.
///
/// - Complexity: The expected complexity is O(1) hashing/comparison
/// operations, as long as `Element` properly implements `Hashable`.
@inlinable
public func firstIndex(of element: Element) -> Index? {
_index(of: element)
}
/// Returns the index of the specified member of the collection, or `nil` if
/// the value isn't a member.
///
/// - Parameter element: An element to search for in the collection.
/// - Returns: The index where `element` is found. If `element` is not
/// found in the collection, returns `nil`.
///
/// - Complexity: The expected complexity is O(1) hashing/comparison
/// operations, as long as `Element` properly implements `Hashable`.
@inlinable
public func lastIndex(of element: Element) -> Index? {
_index(of: element)
}
@inlinable
internal func _index(of element: Element) -> Index? {
let hash = _Hash(element)
@@ -213,3 +336,37 @@ extension PersistentSet: BidirectionalCollection {
precondition(_isValid(range.lowerBound) && _isValid(range.upperBound))
}
}
#if false
// Note: Let's not do this. `BidirectionalCollection` would imply that
// the ordering of elements would be meaningful, which isn't true for
// `PersistentSet`.
extension PersistentSet: BidirectionalCollection {
/// Replaces the given index with its predecessor.
///
/// - Parameter i: A valid index of the collection.
/// `i` must be greater than `startIndex`.
///
/// - Complexity: O(1)
@inlinable
public func formIndex(before i: inout Index) {
precondition(_isValid(i), "Invalid index")
guard i._path.findPredecessorItem(under: _root.raw) else {
preconditionFailure("The start index has no predecessor")
}
}
/// Returns the position immediately before the given index.
///
/// - Parameter i: A valid index of the collection.
/// `i` must be greater than `startIndex`.
///
/// - Complexity: O(1)
@inlinable @inline(__always)
public func index(before i: Index) -> Index {
var i = i
formIndex(before: &i)
return i
}
}
#endif
@@ -12,6 +12,6 @@
extension PersistentSet: CustomReflectable {
/// The custom mirror for this instance.
public var customMirror: Mirror {
Mirror(self, unlabeledChildren: self, displayStyle: .collection)
Mirror(self, unlabeledChildren: self, displayStyle: .set)
}
}
@@ -14,6 +14,16 @@ import _CollectionsUtilities
extension PersistentSet: _UniqueCollection {}
extension PersistentSet {
/// Removes the element at the given valid index.
///
/// Calling this method invalidates all existing indices of the collection.
///
/// - Parameter position: The index of the member to remove. `position` must
/// be a valid index of the set, and it must not be equal to the set’s
/// end index.
/// - Returns: The element that was removed from the set.
/// - Complexity: O(log(`count`)) if set storage might be shared; O(1)
/// otherwise.
@discardableResult
public mutating func remove(at position: Index) -> Element {
precondition(_isValid(position))
@@ -30,7 +40,7 @@ extension PersistentSet {
/// comparison or some other means. Updating a member through this method
/// does not require any hashing operations.
///
/// Calling this method invalidates all existing indices.
/// Calling this method invalidates all existing indices of the collection.
///
/// - Parameter item: The new value that should replace the original element.
/// `item` must compare equal to the original value.
@@ -39,7 +49,8 @@ extension PersistentSet {
///
/// - Returns: The original element that was replaced.
///
/// - Complexity: Amortized O(1).
/// - Complexity: O(log(`count`)) if set storage might be shared; O(1)
/// otherwise.
public mutating func update(_ member: Element, at index: Index) -> Element {
precondition(_isValid(index), "Invalid index")
precondition(index._path.isOnItem, "Can't get element at endIndex")
Loaded 100 of 142 files, more files were not shown because too many files have changed in this diff. Show more