diff --git a/.gitignore b/.gitignore
index 36bbb6fb..4b8a5292 100644
--- a/.gitignore
+++ b/.gitignore
@@ -4,3 +4,5 @@
/*.xcodeproj
xcuserdata/
.*.sw?
+/Benchmarks/.swiftpm
+/Benchmarks/.build
diff --git a/.swiftpm/xcode/xcshareddata/xcschemes/PriorityQueueModule.xcscheme b/.swiftpm/xcode/xcshareddata/xcschemes/PriorityQueueModule.xcscheme
index b34d2227..7e344592 100644
--- a/.swiftpm/xcode/xcshareddata/xcschemes/PriorityQueueModule.xcscheme
+++ b/.swiftpm/xcode/xcshareddata/xcschemes/PriorityQueueModule.xcscheme
@@ -26,7 +26,8 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
- shouldUseLaunchSchemeArgsEnv = "YES">
+ shouldUseLaunchSchemeArgsEnv = "YES"
+ codeCoverageEnabled = "YES">
diff --git a/.swiftpm/xcode/xcshareddata/xcschemes/swift-collections-Package.xcscheme b/.swiftpm/xcode/xcshareddata/xcschemes/swift-collections-Package.xcscheme
index a3af5c69..f76beda0 100644
--- a/.swiftpm/xcode/xcshareddata/xcschemes/swift-collections-Package.xcscheme
+++ b/.swiftpm/xcode/xcshareddata/xcschemes/swift-collections-Package.xcscheme
@@ -37,9 +37,23 @@
+
+
+
+
+ buildForAnalyzing = "NO">
+ buildForRunning = "NO"
+ buildForProfiling = "NO"
+ buildForArchiving = "NO"
+ buildForAnalyzing = "NO">
+ buildForRunning = "NO"
+ buildForProfiling = "NO"
+ buildForArchiving = "NO"
+ buildForAnalyzing = "NO">
-
-
-
-
-
-
-
-
-
-
-
-
@@ -132,20 +104,6 @@
ReferencedContainer = "container:">
-
-
-
-
-
-
-
-
-
-
-
-
-
+
-
+
diff --git a/.swiftpm/xcode/xcshareddata/xcschemes/swift-collections-benchmark.xcscheme b/.swiftpm/xcode/xcshareddata/xcschemes/swift-collections-benchmark.xcscheme
deleted file mode 100644
index 0e09399b..00000000
--- a/.swiftpm/xcode/xcshareddata/xcschemes/swift-collections-benchmark.xcscheme
+++ /dev/null
@@ -1,127 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/Benchmarks/Benchmarks/Cpp/CppBenchmarks.swift b/Benchmarks/Benchmarks/Cpp/CppBenchmarks.swift
new file mode 100644
index 00000000..6b345bf9
--- /dev/null
+++ b/Benchmarks/Benchmarks/Cpp/CppBenchmarks.swift
@@ -0,0 +1,45 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+import CollectionsBenchmark
+import CppBenchmarks
+
+extension Benchmark {
+ public mutating func addCppBenchmarks() {
+ cpp_set_hash_fn { value in value._rawHashValue(seed: 0) }
+
+ self.addSimple(
+ title: "std::hash",
+ input: [Int].self
+ ) { input in
+ input.withUnsafeBufferPointer { buffer in
+ cpp_hash(buffer.baseAddress, buffer.count)
+ }
+ }
+
+ self.addSimple(
+ title: "custom_intptr_hash (using Swift.Hasher)",
+ input: [Int].self
+ ) { input in
+ input.withUnsafeBufferPointer { buffer in
+ cpp_custom_hash(buffer.baseAddress, buffer.count)
+ }
+ }
+
+ _addCppVectorBenchmarks()
+ _addCppDequeBenchmarks()
+ _addCppUnorderedSetBenchmarks()
+ _addCppUnorderedMapBenchmarks()
+ _addCppPriorityQueueBenchmarks()
+ _addCppVectorBoolBenchmarks()
+ _addCppMapBenchmarks()
+ }
+}
diff --git a/Benchmarks/Benchmarks/Cpp/CppDequeBenchmarks.swift b/Benchmarks/Benchmarks/Cpp/CppDequeBenchmarks.swift
new file mode 100644
index 00000000..12026b7c
--- /dev/null
+++ b/Benchmarks/Benchmarks/Cpp/CppDequeBenchmarks.swift
@@ -0,0 +1,170 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+import CollectionsBenchmark
+import CppBenchmarks
+
+internal class CppDeque {
+ var ptr: UnsafeMutableRawPointer?
+
+ init(_ input: [Int]) {
+ self.ptr = input.withUnsafeBufferPointer { buffer in
+ cpp_deque_create(buffer.baseAddress, buffer.count)
+ }
+ }
+
+ deinit {
+ destroy()
+ }
+
+ func destroy() {
+ if let ptr = ptr {
+ cpp_deque_destroy(ptr)
+ }
+ ptr = nil
+ }
+}
+
+extension Benchmark {
+ internal mutating func _addCppDequeBenchmarks() {
+ self.addSimple(
+ title: "std::deque push_back from integer range",
+ input: Int.self
+ ) { count in
+ cpp_deque_from_int_range(count)
+ }
+
+ self.addSimple(
+ title: "std::deque constructor from buffer",
+ input: [Int].self
+ ) { input in
+ input.withUnsafeBufferPointer { buffer in
+ cpp_deque_from_int_buffer(buffer.baseAddress, buffer.count)
+ }
+ }
+
+ self.add(
+ title: "std::deque sequential iteration",
+ input: [Int].self
+ ) { input in
+ let deque = CppDeque(input)
+ return { timer in
+ cpp_deque_iterate(deque.ptr)
+ }
+ }
+
+ self.add(
+ title: "std::deque random-access offset lookups (operator [])",
+ input: ([Int], [Int]).self
+ ) { input, lookups in
+ let vector = CppDeque(input)
+ return { timer in
+ lookups.withUnsafeBufferPointer { buffer in
+ cpp_deque_lookups_subscript(vector.ptr, buffer.baseAddress, buffer.count)
+ }
+ }
+ }
+
+ self.add(
+ title: "std::deque at, random offsets",
+ input: ([Int], [Int]).self
+ ) { input, lookups in
+ let deque = CppDeque(input)
+ return { timer in
+ lookups.withUnsafeBufferPointer { buffer in
+ cpp_deque_lookups_at(deque.ptr, buffer.baseAddress, buffer.count)
+ }
+ }
+ }
+
+ self.addSimple(
+ title: "std::deque push_back",
+ input: [Int].self
+ ) { input in
+ input.withUnsafeBufferPointer { buffer in
+ cpp_deque_append_integers(buffer.baseAddress, buffer.count)
+ }
+ }
+
+ self.addSimple(
+ title: "std::deque push_front",
+ input: [Int].self
+ ) { input in
+ input.withUnsafeBufferPointer { buffer in
+ cpp_deque_prepend_integers(buffer.baseAddress, buffer.count)
+ }
+ }
+
+ self.addSimple(
+ title: "std::deque random insertions",
+ input: Insertions.self
+ ) { insertions in
+ insertions.values.withUnsafeBufferPointer { buffer in
+ cpp_deque_random_insertions(buffer.baseAddress, buffer.count)
+ }
+ }
+
+ self.add(
+ title: "std::deque pop_back",
+ input: Int.self
+ ) { size in
+ return { timer in
+ let deque = CppDeque(Array(0 ..< size))
+ timer.measure {
+ cpp_deque_pop_back(deque.ptr)
+ }
+ deque.destroy()
+ }
+ }
+
+ self.add(
+ title: "std::deque pop_front",
+ input: Int.self
+ ) { size in
+ return { timer in
+ let deque = CppDeque(Array(0 ..< size))
+ timer.measure {
+ cpp_deque_pop_front(deque.ptr)
+ }
+ deque.destroy()
+ }
+ }
+
+ self.add(
+ title: "std::deque random removals",
+ input: Insertions.self
+ ) { insertions in
+ let removals = Array(insertions.values.reversed())
+ return { timer in
+ let deque = CppDeque(Array(0 ..< removals.count))
+ timer.measure {
+ removals.withUnsafeBufferPointer { buffer in
+ cpp_deque_random_removals(deque.ptr, buffer.baseAddress, buffer.count)
+ }
+ }
+ deque.destroy()
+ }
+ }
+
+ self.add(
+ title: "std::deque sort",
+ input: [Int].self
+ ) { input in
+ return { timer in
+ let deque = CppDeque(input)
+ timer.measure {
+ cpp_deque_sort(deque.ptr)
+ }
+ deque.destroy()
+ }
+ }
+ }
+}
diff --git a/Benchmarks/Benchmarks/Cpp/CppMapBenchmarks.swift b/Benchmarks/Benchmarks/Cpp/CppMapBenchmarks.swift
new file mode 100644
index 00000000..00d39b10
--- /dev/null
+++ b/Benchmarks/Benchmarks/Cpp/CppMapBenchmarks.swift
@@ -0,0 +1,59 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+import CollectionsBenchmark
+import CppBenchmarks
+
+internal class CppMap {
+ var ptr: UnsafeMutableRawPointer?
+
+ init(_ input: [Int]) {
+ self.ptr = input.withUnsafeBufferPointer { buffer in
+ cpp_map_create(buffer.baseAddress, buffer.count)
+ }
+ }
+
+ deinit {
+ destroy()
+ }
+
+ func destroy() {
+ if let ptr = ptr {
+ cpp_map_destroy(ptr)
+ }
+ ptr = nil
+ }
+}
+
+extension Benchmark {
+ internal mutating func _addCppMapBenchmarks() {
+ self.addSimple(
+ title: "std::map insert",
+ input: [Int].self
+ ) { input in
+ input.withUnsafeBufferPointer { buffer in
+ cpp_map_insert_integers(buffer.baseAddress, buffer.count)
+ }
+ }
+
+ self.add(
+ title: "std::map successful find",
+ input: ([Int], [Int]).self
+ ) { input, lookups in
+ let map = CppMap(input)
+ return { timer in
+ lookups.withUnsafeBufferPointer { buffer in
+ cpp_map_lookups(map.ptr, buffer.baseAddress, buffer.count)
+ }
+ }
+ }
+ }
+}
diff --git a/Benchmarks/Benchmarks/Cpp/CppPriorityQueueBenchmarks.swift b/Benchmarks/Benchmarks/Cpp/CppPriorityQueueBenchmarks.swift
new file mode 100644
index 00000000..cd8d1012
--- /dev/null
+++ b/Benchmarks/Benchmarks/Cpp/CppPriorityQueueBenchmarks.swift
@@ -0,0 +1,96 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+import CollectionsBenchmark
+import CppBenchmarks
+
+internal class CppPriorityQueue {
+ var ptr: UnsafeMutableRawPointer?
+
+ init(_ input: [Int]) {
+ self.ptr = input.withUnsafeBufferPointer { buffer in
+ cpp_priority_queue_create(buffer.baseAddress, buffer.count)
+ }
+ }
+
+ convenience init() {
+ self.init([])
+ }
+
+ deinit {
+ destroy()
+ }
+
+ func destroy() {
+ if let ptr = ptr {
+ cpp_priority_queue_destroy(ptr)
+ }
+ ptr = nil
+ }
+
+ func push(_ value: Int) {
+ cpp_priority_queue_push(ptr, value)
+ }
+
+ func push(_ values: [Int]) {
+ values.withUnsafeBufferPointer { buffer in
+ cpp_priority_queue_push_loop(ptr, buffer.baseAddress, buffer.count)
+ }
+ }
+
+ func pop() -> Int {
+ cpp_priority_queue_pop(ptr)
+ }
+
+ func popAll() {
+ cpp_priority_queue_pop_all(ptr)
+ }
+}
+
+extension Benchmark {
+ internal mutating func _addCppPriorityQueueBenchmarks() {
+ self.addSimple(
+ title: "std::priority_queue construct from buffer",
+ input: [Int].self
+ ) { input in
+ let pq = CppPriorityQueue(input)
+ blackHole(pq)
+ }
+
+ self.add(
+ title: "std::priority_queue push",
+ input: [Int].self
+ ) { input in
+ return { timer in
+ let pq = CppPriorityQueue()
+ timer.measure {
+ pq.push(input)
+ }
+ blackHole(pq)
+ pq.destroy()
+ }
+ }
+
+ self.add(
+ title: "std::priority_queue pop",
+ input: [Int].self
+ ) { input in
+ return { timer in
+ let pq = CppPriorityQueue(input)
+ timer.measure {
+ pq.popAll()
+ }
+ blackHole(pq)
+ pq.destroy()
+ }
+ }
+ }
+}
diff --git a/Benchmarks/Benchmarks/Cpp/CppUnorderedMapBenchmarks.swift b/Benchmarks/Benchmarks/Cpp/CppUnorderedMapBenchmarks.swift
new file mode 100644
index 00000000..bf1ccd9f
--- /dev/null
+++ b/Benchmarks/Benchmarks/Cpp/CppUnorderedMapBenchmarks.swift
@@ -0,0 +1,153 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+import CollectionsBenchmark
+import CppBenchmarks
+
+internal class CppUnorderedMap {
+ var ptr: UnsafeMutableRawPointer?
+
+ init(_ input: [Int]) {
+ self.ptr = input.withUnsafeBufferPointer { buffer in
+ cpp_unordered_map_create(buffer.baseAddress, buffer.count)
+ }
+ }
+
+ deinit {
+ destroy()
+ }
+
+ func destroy() {
+ if let ptr = ptr {
+ cpp_unordered_map_destroy(ptr)
+ }
+ ptr = nil
+ }
+}
+
+extension Benchmark {
+ internal mutating func _addCppUnorderedMapBenchmarks() {
+ self.addSimple(
+ title: "std::unordered_map insert from integer range",
+ input: Int.self
+ ) { count in
+ cpp_unordered_map_from_int_range(count)
+ }
+
+ self.add(
+ title: "std::unordered_map sequential iteration",
+ input: [Int].self
+ ) { input in
+ let map = CppUnorderedMap(input)
+ return { timer in
+ cpp_unordered_map_iterate(map.ptr)
+ }
+ }
+
+ self.add(
+ title: "std::unordered_map successful find",
+ input: ([Int], [Int]).self
+ ) { input, lookups in
+ let map = CppUnorderedMap(input)
+ return { timer in
+ lookups.withUnsafeBufferPointer { buffer in
+ cpp_unordered_map_lookups(map.ptr, buffer.baseAddress, buffer.count, true)
+ }
+ }
+ }
+
+ self.add(
+ title: "std::unordered_map unsuccessful find",
+ input: ([Int], [Int]).self
+ ) { input, lookups in
+ let map = CppUnorderedMap(input)
+ let lookups = lookups.map { $0 + input.count }
+ return { timer in
+ lookups.withUnsafeBufferPointer { buffer in
+ cpp_unordered_map_lookups(map.ptr, buffer.baseAddress, buffer.count, false)
+ }
+ }
+ }
+
+ self.add(
+ title: "std::unordered_map subscript, existing key",
+ input: ([Int], [Int]).self
+ ) { input, lookups in
+ let map = CppUnorderedMap(input)
+ return { timer in
+ lookups.withUnsafeBufferPointer { buffer in
+ cpp_unordered_map_subscript(map.ptr, buffer.baseAddress, buffer.count)
+ }
+ }
+ }
+
+ self.add(
+ title: "std::unordered_map subscript, new key",
+ input: ([Int], [Int]).self
+ ) { input, lookups in
+ let map = CppUnorderedMap(input)
+ let lookups = lookups.map { $0 + input.count }
+ return { timer in
+ lookups.withUnsafeBufferPointer { buffer in
+ cpp_unordered_map_subscript(map.ptr, buffer.baseAddress, buffer.count)
+ }
+ }
+ }
+
+ self.addSimple(
+ title: "std::unordered_map insert",
+ input: [Int].self
+ ) { input in
+ input.withUnsafeBufferPointer { buffer in
+ cpp_unordered_map_insert_integers(buffer.baseAddress, buffer.count, false)
+ }
+ }
+
+ self.addSimple(
+ title: "std::unordered_map insert, reserving capacity",
+ input: [Int].self
+ ) { input in
+ input.withUnsafeBufferPointer { buffer in
+ cpp_unordered_map_insert_integers(buffer.baseAddress, buffer.count, true)
+ }
+ }
+
+ self.add(
+ title: "std::unordered_map erase existing",
+ input: ([Int], [Int]).self
+ ) { input, removals in
+ return { timer in
+ let map = CppUnorderedMap(input)
+ timer.measure {
+ removals.withUnsafeBufferPointer { buffer in
+ cpp_unordered_map_removals(map.ptr, buffer.baseAddress, buffer.count)
+ }
+ }
+ map.destroy()
+ }
+ }
+
+ self.add(
+ title: "std::unordered_map erase missing",
+ input: ([Int], [Int]).self
+ ) { input, removals in
+ return { timer in
+ let map = CppUnorderedMap(input.map { input.count + $0 })
+ timer.measure {
+ removals.withUnsafeBufferPointer { buffer in
+ cpp_unordered_map_removals(map.ptr, buffer.baseAddress, buffer.count)
+ }
+ }
+ map.destroy()
+ }
+ }
+ }
+}
diff --git a/Benchmarks/Benchmarks/Cpp/CppUnorderedSetBenchmarks.swift b/Benchmarks/Benchmarks/Cpp/CppUnorderedSetBenchmarks.swift
new file mode 100644
index 00000000..5719e872
--- /dev/null
+++ b/Benchmarks/Benchmarks/Cpp/CppUnorderedSetBenchmarks.swift
@@ -0,0 +1,122 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+import CollectionsBenchmark
+import CppBenchmarks
+
+internal class CppUnorderedSet {
+ var ptr: UnsafeMutableRawPointer?
+
+ init(_ input: [Int]) {
+ self.ptr = input.withUnsafeBufferPointer { buffer in
+ cpp_unordered_set_create(buffer.baseAddress, buffer.count)
+ }
+ }
+
+ deinit {
+ destroy()
+ }
+
+ func destroy() {
+ if let ptr = ptr {
+ cpp_unordered_set_destroy(ptr)
+ }
+ ptr = nil
+ }
+}
+
+extension Benchmark {
+ internal mutating func _addCppUnorderedSetBenchmarks() {
+ self.addSimple(
+ title: "std::unordered_set insert from integer range",
+ input: Int.self
+ ) { count in
+ cpp_unordered_set_from_int_range(count)
+ }
+
+ self.addSimple(
+ title: "std::unordered_set constructor from buffer",
+ input: [Int].self
+ ) { input in
+ input.withUnsafeBufferPointer { buffer in
+ cpp_unordered_set_from_int_buffer(buffer.baseAddress, buffer.count)
+ }
+ }
+
+ self.add(
+ title: "std::unordered_set sequential iteration",
+ input: [Int].self
+ ) { input in
+ let set = CppUnorderedSet(input)
+ return { timer in
+ cpp_unordered_set_iterate(set.ptr)
+ }
+ }
+
+ self.add(
+ title: "std::unordered_set successful find",
+ input: ([Int], [Int]).self
+ ) { input, lookups in
+ let set = CppUnorderedSet(input)
+ return { timer in
+ lookups.withUnsafeBufferPointer { buffer in
+ cpp_unordered_set_lookups(set.ptr, buffer.baseAddress, buffer.count, true)
+ }
+ }
+ }
+
+ self.add(
+ title: "std::unordered_set unsuccessful find",
+ input: ([Int], [Int]).self
+ ) { input, lookups in
+ let set = CppUnorderedSet(input)
+ let lookups = lookups.map { $0 + input.count }
+ return { timer in
+ lookups.withUnsafeBufferPointer { buffer in
+ cpp_unordered_set_lookups(set.ptr, buffer.baseAddress, buffer.count, false)
+ }
+ }
+ }
+
+ self.addSimple(
+ title: "std::unordered_set insert",
+ input: [Int].self
+ ) { input in
+ input.withUnsafeBufferPointer { buffer in
+ cpp_unordered_set_insert_integers(buffer.baseAddress, buffer.count, false)
+ }
+ }
+
+ self.addSimple(
+ title: "std::unordered_set insert, reserving capacity",
+ input: [Int].self
+ ) { input in
+ input.withUnsafeBufferPointer { buffer in
+ cpp_unordered_set_insert_integers(buffer.baseAddress, buffer.count, true)
+ }
+ }
+
+ self.add(
+ title: "std::unordered_set erase",
+ input: ([Int], [Int]).self
+ ) { input, removals in
+ return { timer in
+ let set = CppUnorderedSet(input)
+ timer.measure {
+ removals.withUnsafeBufferPointer { buffer in
+ cpp_unordered_set_removals(set.ptr, buffer.baseAddress, buffer.count)
+ }
+ }
+ set.destroy()
+ }
+ }
+ }
+}
diff --git a/Benchmarks/Benchmarks/Cpp/CppVectorBenchmarks.swift b/Benchmarks/Benchmarks/Cpp/CppVectorBenchmarks.swift
new file mode 100644
index 00000000..c188d1ff
--- /dev/null
+++ b/Benchmarks/Benchmarks/Cpp/CppVectorBenchmarks.swift
@@ -0,0 +1,188 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+import CollectionsBenchmark
+import CppBenchmarks
+
+internal class CppVector {
+ var ptr: UnsafeMutableRawPointer?
+
+ init(_ input: [Int]) {
+ self.ptr = input.withUnsafeBufferPointer { buffer in
+ cpp_vector_create(buffer.baseAddress, buffer.count)
+ }
+ }
+
+ deinit {
+ destroy()
+ }
+
+ func destroy() {
+ if let ptr = ptr {
+ cpp_vector_destroy(ptr)
+ }
+ ptr = nil
+ }
+}
+
+extension Benchmark {
+ internal mutating func _addCppVectorBenchmarks() {
+ self.addSimple(
+ title: "std::vector push_back from integer range",
+ input: Int.self
+ ) { count in
+ cpp_vector_from_int_range(count)
+ }
+
+ self.addSimple(
+ title: "std::vector constructor from buffer",
+ input: [Int].self
+ ) { input in
+ input.withUnsafeBufferPointer { buffer in
+ cpp_vector_from_int_buffer(buffer.baseAddress, buffer.count)
+ }
+ }
+
+ self.add(
+ title: "std::vector sequential iteration",
+ input: [Int].self
+ ) { input in
+ let vector = CppVector(input)
+ return { timer in
+ cpp_vector_iterate(vector.ptr)
+ }
+ }
+
+ self.add(
+ title: "std::vector random-access offset lookups (operator [])",
+ input: ([Int], [Int]).self
+ ) { input, lookups in
+ let vector = CppVector(input)
+ return { timer in
+ lookups.withUnsafeBufferPointer { buffer in
+ cpp_vector_lookups_subscript(vector.ptr, buffer.baseAddress, buffer.count)
+ }
+ }
+ }
+
+ self.add(
+ title: "std::vector random-access offset lookups (at)",
+ input: ([Int], [Int]).self
+ ) { input, lookups in
+ let deque = CppVector(input)
+ return { timer in
+ lookups.withUnsafeBufferPointer { buffer in
+ cpp_vector_lookups_at(deque.ptr, buffer.baseAddress, buffer.count)
+ }
+ }
+ }
+
+ self.addSimple(
+ title: "std::vector push_back",
+ input: [Int].self
+ ) { input in
+ input.withUnsafeBufferPointer { buffer in
+ cpp_vector_append_integers(buffer.baseAddress, buffer.count, false)
+ }
+ }
+
+ self.addSimple(
+ title: "std::vector push_back, reserving capacity",
+ input: [Int].self
+ ) { input in
+ input.withUnsafeBufferPointer { buffer in
+ cpp_vector_append_integers(buffer.baseAddress, buffer.count, true)
+ }
+ }
+
+ self.addSimple(
+ title: "std::vector insert at front",
+ input: [Int].self
+ ) { input in
+ input.withUnsafeBufferPointer { buffer in
+ cpp_vector_prepend_integers(buffer.baseAddress, buffer.count, false)
+ }
+ }
+
+ self.addSimple(
+ title: "std::vector insert at front, reserving capacity",
+ input: [Int].self
+ ) { input in
+ input.withUnsafeBufferPointer { buffer in
+ cpp_vector_prepend_integers(buffer.baseAddress, buffer.count, true)
+ }
+ }
+
+ self.addSimple(
+ title: "std::vector random insertions",
+ input: Insertions.self
+ ) { insertions in
+ insertions.values.withUnsafeBufferPointer { buffer in
+ cpp_vector_random_insertions(buffer.baseAddress, buffer.count, false)
+ }
+ }
+
+ self.add(
+ title: "std::vector pop_back",
+ input: Int.self
+ ) { size in
+ return { timer in
+ let vector = CppVector(Array(0 ..< size))
+ timer.measure {
+ cpp_vector_pop_back(vector.ptr)
+ }
+ vector.destroy()
+ }
+ }
+
+ self.add(
+ title: "std::vector erase first",
+ input: Int.self
+ ) { size in
+ return { timer in
+ let vector = CppVector(Array(0 ..< size))
+ timer.measure {
+ cpp_vector_pop_front(vector.ptr)
+ }
+ vector.destroy()
+ }
+ }
+
+ self.add(
+ title: "std::vector random removals",
+ input: Insertions.self
+ ) { insertions in
+ let removals = Array(insertions.values.reversed())
+ return { timer in
+ let vector = CppVector(Array(0 ..< removals.count))
+ timer.measure {
+ removals.withUnsafeBufferPointer { buffer in
+ cpp_vector_random_removals(vector.ptr, buffer.baseAddress, buffer.count)
+ }
+ }
+ vector.destroy()
+ }
+ }
+
+ self.add(
+ title: "std::vector sort",
+ input: [Int].self
+ ) { input in
+ return { timer in
+ let vector = CppVector(input)
+ timer.measure {
+ cpp_vector_sort(vector.ptr)
+ }
+ vector.destroy()
+ }
+ }
+ }
+}
diff --git a/Benchmarks/Benchmarks/Cpp/CppVectorBoolBenchmarks.swift b/Benchmarks/Benchmarks/Cpp/CppVectorBoolBenchmarks.swift
new file mode 100644
index 00000000..7c8afcca
--- /dev/null
+++ b/Benchmarks/Benchmarks/Cpp/CppVectorBoolBenchmarks.swift
@@ -0,0 +1,237 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+import CollectionsBenchmark
+import CppBenchmarks
+
+internal class CppVectorBool {
+ var ptr: UnsafeMutableRawPointer?
+
+ init(repeating value: Bool, count: Int) {
+ self.ptr = cpp_vector_bool_create_repeating(count, value)
+ }
+
+ init(count: Int, trueBits: ArraySlice) {
+ self.ptr = cpp_vector_bool_create_repeating(count, false)
+ trueBits.withUnsafeBufferPointer { buffer in
+ cpp_vector_bool_set_indices_subscript(
+ self.ptr,
+ buffer.baseAddress,
+ buffer.count)
+ }
+ withExtendedLifetime(self) {}
+ }
+
+ deinit {
+ destroy()
+ }
+
+ func destroy() {
+ if let ptr = ptr {
+ cpp_vector_bool_destroy(ptr)
+ }
+ ptr = nil
+ }
+}
+
+extension Array where Element == Bool {
+ init(count: Int, trueBits: S) where S.Element == Int {
+ self.init(repeating: false, count: count)
+ for index in trueBits {
+ self[index] = true
+ }
+ }
+}
+
+extension Benchmark {
+ internal mutating func _addCppVectorBoolBenchmarks() {
+ self.addSimple(
+ title: "std::vector create from integer buffer (subscript)",
+ input: [Int].self
+ ) { input in
+ let trueCount = input.count / 2
+ let v = CppVectorBool(repeating: false, count: input.count)
+ input.withUnsafeBufferPointer { buffer in
+ cpp_vector_bool_set_indices_subscript(
+ v.ptr,
+ buffer.baseAddress,
+ trueCount)
+ }
+ v.destroy()
+ }
+
+ self.addSimple(
+ title: "std::vector create from integer buffer (at)",
+ input: [Int].self
+ ) { input in
+ let trueCount = input.count / 2
+ let v = CppVectorBool(repeating: false, count: input.count)
+ input.withUnsafeBufferPointer { buffer in
+ cpp_vector_bool_set_indices_at(
+ v.ptr,
+ buffer.baseAddress,
+ trueCount)
+ }
+ v.destroy()
+ }
+
+ self.add(
+ title: "std::vector const_iterator",
+ input: [Int].self
+ ) { input in
+ let trueCount = input.count / 2
+ let v = CppVectorBool(count: input.count, trueBits: input[.. find true bits",
+ input: [Int].self
+ ) { input in
+ let trueCount = input.count / 2
+ let v = CppVectorBool(count: input.count, trueBits: input[.. count true bits",
+ input: [Int].self
+ ) { input in
+ let trueCount = input.count / 2
+ let v = CppVectorBool(count: input.count, trueBits: input[.. random-access offset lookups (subscript)",
+ input: ([Int], [Int]).self
+ ) { input, lookups in
+ let trueCount = input.count / 2
+ let v = CppVectorBool(count: input.count, trueBits: input[.. random-access offset lookups (at)",
+ input: ([Int], [Int]).self
+ ) { input, lookups in
+ let trueCount = input.count / 2
+ let v = CppVectorBool(count: input.count, trueBits: input[.. set bits to true (subscript)",
+ input: [Int].self
+ ) { input in
+ let v = CppVectorBool(repeating: false, count: input.count)
+ return { timer in
+ input.withUnsafeBufferPointer { buffer in
+ cpp_vector_bool_set_indices_subscript(v.ptr, buffer.baseAddress, buffer.count)
+ }
+ }
+ }
+
+ self.add(
+ title: "std::vector set bits to true (at)",
+ input: [Int].self
+ ) { input in
+ let v = CppVectorBool(repeating: false, count: input.count)
+ return { timer in
+ input.withUnsafeBufferPointer { buffer in
+ cpp_vector_bool_set_indices_at(v.ptr, buffer.baseAddress, buffer.count)
+ }
+ }
+ }
+
+ self.add(
+ title: "std::vector set bits to false (subscript)",
+ input: [Int].self
+ ) { input in
+ let v = CppVectorBool(repeating: true, count: input.count)
+ return { timer in
+ input.withUnsafeBufferPointer { buffer in
+ cpp_vector_bool_reset_indices_subscript(v.ptr, buffer.baseAddress, buffer.count)
+ }
+ }
+ }
+
+ self.add(
+ title: "std::vector set bits to false (at)",
+ input: [Int].self
+ ) { input in
+ let v = CppVectorBool(repeating: true, count: input.count)
+ return { timer in
+ input.withUnsafeBufferPointer { buffer in
+ cpp_vector_bool_reset_indices_at(v.ptr, buffer.baseAddress, buffer.count)
+ }
+ }
+ }
+
+ self.add(
+ title: "std::vector push_back",
+ input: [Int].self
+ ) { input in
+ let trueCount = input.count / 2
+ let bools = Array(count: input.count, trueBits: input[.. push_back, reserving capacity",
+ input: [Int].self
+ ) { input in
+ let trueCount = input.count / 2
+ let bools = Array(count: input.count, trueBits: input[.. pop_back",
+ input: [Int].self
+ ) { input in
+ return { timer in
+ let trueCount = input.count / 2
+ let v = CppVectorBool(count: input.count, trueBits: input[.. Int {
- cpp_priority_queue_pop(ptr)
- }
-
- func popAll() {
- cpp_priority_queue_pop_all(ptr)
- }
-}
-
-internal class CppMap {
- var ptr: UnsafeMutableRawPointer?
-
- init(_ input: [Int]) {
- self.ptr = input.withUnsafeBufferPointer { buffer in
- cpp_map_create(buffer.baseAddress, buffer.count)
- }
- }
-
- deinit {
- destroy()
- }
-
- func destroy() {
- if let ptr = ptr {
- cpp_map_destroy(ptr)
- }
- ptr = nil
- }
-}
-
-extension Benchmark {
- public mutating func addCppBenchmarks() {
- cpp_set_hash_fn { value in value._rawHashValue(seed: 0) }
-
- self.addSimple(
- title: "std::hash",
- input: [Int].self
- ) { input in
- input.withUnsafeBufferPointer { buffer in
- cpp_hash(buffer.baseAddress, buffer.count)
- }
- }
-
- self.addSimple(
- title: "custom_intptr_hash (using Swift.Hasher)",
- input: [Int].self
- ) { input in
- input.withUnsafeBufferPointer { buffer in
- cpp_custom_hash(buffer.baseAddress, buffer.count)
- }
- }
-
- self.addSimple(
- title: "std::vector push_back from integer range",
- input: Int.self
- ) { count in
- cpp_vector_from_int_range(count)
- }
-
- self.addSimple(
- title: "std::deque push_back from integer range",
- input: Int.self
- ) { count in
- cpp_deque_from_int_range(count)
- }
-
- //--------------------------------------------------------------------------
-
- self.addSimple(
- title: "std::vector constructor from buffer",
- input: [Int].self
- ) { input in
- input.withUnsafeBufferPointer { buffer in
- cpp_vector_from_int_buffer(buffer.baseAddress, buffer.count)
- }
- }
-
- self.addSimple(
- title: "std::deque constructor from buffer",
- input: [Int].self
- ) { input in
- input.withUnsafeBufferPointer { buffer in
- cpp_deque_from_int_buffer(buffer.baseAddress, buffer.count)
- }
- }
-
- //--------------------------------------------------------------------------
-
- self.add(
- title: "std::vector sequential iteration",
- input: [Int].self
- ) { input in
- let vector = CppVector(input)
- return { timer in
- cpp_vector_iterate(vector.ptr)
- }
- }
-
- self.add(
- title: "std::deque sequential iteration",
- input: [Int].self
- ) { input in
- let deque = CppDeque(input)
- return { timer in
- cpp_deque_iterate(deque.ptr)
- }
- }
-
- //--------------------------------------------------------------------------
-
- self.add(
- title: "std::vector random-access offset lookups (operator [])",
- input: ([Int], [Int]).self
- ) { input, lookups in
- let vector = CppVector(input)
- return { timer in
- lookups.withUnsafeBufferPointer { buffer in
- cpp_vector_lookups_subscript(vector.ptr, buffer.baseAddress, buffer.count)
- }
- }
- }
-
- self.add(
- title: "std::deque random-access offset lookups (operator [])",
- input: ([Int], [Int]).self
- ) { input, lookups in
- let vector = CppDeque(input)
- return { timer in
- lookups.withUnsafeBufferPointer { buffer in
- cpp_deque_lookups_subscript(vector.ptr, buffer.baseAddress, buffer.count)
- }
- }
- }
-
- //--------------------------------------------------------------------------
-
- self.add(
- title: "std::vector random-access offset lookups (at)",
- input: ([Int], [Int]).self
- ) { input, lookups in
- let deque = CppVector(input)
- return { timer in
- lookups.withUnsafeBufferPointer { buffer in
- cpp_vector_lookups_at(deque.ptr, buffer.baseAddress, buffer.count)
- }
- }
- }
-
- self.add(
- title: "std::deque at, random offsets",
- input: ([Int], [Int]).self
- ) { input, lookups in
- let deque = CppDeque(input)
- return { timer in
- lookups.withUnsafeBufferPointer { buffer in
- cpp_deque_lookups_at(deque.ptr, buffer.baseAddress, buffer.count)
- }
- }
- }
-
- //--------------------------------------------------------------------------
-
- self.addSimple(
- title: "std::vector push_back",
- input: [Int].self
- ) { input in
- input.withUnsafeBufferPointer { buffer in
- cpp_vector_append_integers(buffer.baseAddress, buffer.count, false)
- }
- }
-
- self.addSimple(
- title: "std::vector push_back, reserving capacity",
- input: [Int].self
- ) { input in
- input.withUnsafeBufferPointer { buffer in
- cpp_vector_append_integers(buffer.baseAddress, buffer.count, true)
- }
- }
-
- self.addSimple(
- title: "std::deque push_back",
- input: [Int].self
- ) { input in
- input.withUnsafeBufferPointer { buffer in
- cpp_deque_append_integers(buffer.baseAddress, buffer.count)
- }
- }
-
- //--------------------------------------------------------------------------
-
- self.addSimple(
- title: "std::vector insert at front",
- input: [Int].self
- ) { input in
- input.withUnsafeBufferPointer { buffer in
- cpp_vector_prepend_integers(buffer.baseAddress, buffer.count, false)
- }
- }
-
- self.addSimple(
- title: "std::vector insert at front, reserving capacity",
- input: [Int].self
- ) { input in
- input.withUnsafeBufferPointer { buffer in
- cpp_vector_prepend_integers(buffer.baseAddress, buffer.count, true)
- }
- }
-
- self.addSimple(
- title: "std::deque push_front",
- input: [Int].self
- ) { input in
- input.withUnsafeBufferPointer { buffer in
- cpp_deque_prepend_integers(buffer.baseAddress, buffer.count)
- }
- }
-
- //--------------------------------------------------------------------------
-
- self.addSimple(
- title: "std::vector random insertions",
- input: Insertions.self
- ) { insertions in
- insertions.values.withUnsafeBufferPointer { buffer in
- cpp_vector_random_insertions(buffer.baseAddress, buffer.count, false)
- }
- }
-
- self.addSimple(
- title: "std::deque random insertions",
- input: Insertions.self
- ) { insertions in
- insertions.values.withUnsafeBufferPointer { buffer in
- cpp_deque_random_insertions(buffer.baseAddress, buffer.count)
- }
- }
-
- //--------------------------------------------------------------------------
-
- self.add(
- title: "std::vector pop_back",
- input: Int.self
- ) { size in
- return { timer in
- let vector = CppVector(Array(0 ..< size))
- timer.measure {
- cpp_vector_pop_back(vector.ptr)
- }
- vector.destroy()
- }
- }
-
- self.add(
- title: "std::deque pop_back",
- input: Int.self
- ) { size in
- return { timer in
- let deque = CppDeque(Array(0 ..< size))
- timer.measure {
- cpp_deque_pop_back(deque.ptr)
- }
- deque.destroy()
- }
- }
-
- //--------------------------------------------------------------------------
-
- self.add(
- title: "std::vector erase first",
- input: Int.self
- ) { size in
- return { timer in
- let vector = CppVector(Array(0 ..< size))
- timer.measure {
- cpp_vector_pop_front(vector.ptr)
- }
- vector.destroy()
- }
- }
-
- self.add(
- title: "std::deque pop_front",
- input: Int.self
- ) { size in
- return { timer in
- let deque = CppDeque(Array(0 ..< size))
- timer.measure {
- cpp_deque_pop_front(deque.ptr)
- }
- deque.destroy()
- }
- }
-
- //--------------------------------------------------------------------------
-
- self.add(
- title: "std::vector random removals",
- input: Insertions.self
- ) { insertions in
- let removals = Array(insertions.values.reversed())
- return { timer in
- let vector = CppVector(Array(0 ..< removals.count))
- timer.measure {
- removals.withUnsafeBufferPointer { buffer in
- cpp_vector_random_removals(vector.ptr, buffer.baseAddress, buffer.count)
- }
- }
- vector.destroy()
- }
- }
-
- self.add(
- title: "std::deque random removals",
- input: Insertions.self
- ) { insertions in
- let removals = Array(insertions.values.reversed())
- return { timer in
- let deque = CppDeque(Array(0 ..< removals.count))
- timer.measure {
- removals.withUnsafeBufferPointer { buffer in
- cpp_deque_random_removals(deque.ptr, buffer.baseAddress, buffer.count)
- }
- }
- deque.destroy()
- }
- }
-
- //--------------------------------------------------------------------------
-
- self.add(
- title: "std::vector sort",
- input: [Int].self
- ) { input in
- return { timer in
- let vector = CppVector(input)
- timer.measure {
- cpp_vector_sort(vector.ptr)
- }
- vector.destroy()
- }
- }
-
- self.add(
- title: "std::deque sort",
- input: [Int].self
- ) { input in
- return { timer in
- let deque = CppDeque(input)
- timer.measure {
- cpp_deque_sort(deque.ptr)
- }
- deque.destroy()
- }
- }
-
- //--------------------------------------------------------------------------
-
- self.addSimple(
- title: "std::unordered_set insert from integer range",
- input: Int.self
- ) { count in
- cpp_unordered_set_from_int_range(count)
- }
-
- self.addSimple(
- title: "std::unordered_set constructor from buffer",
- input: [Int].self
- ) { input in
- input.withUnsafeBufferPointer { buffer in
- cpp_unordered_set_from_int_buffer(buffer.baseAddress, buffer.count)
- }
- }
-
- self.add(
- title: "std::unordered_set sequential iteration",
- input: [Int].self
- ) { input in
- let set = CppUnorderedSet(input)
- return { timer in
- cpp_unordered_set_iterate(set.ptr)
- }
- }
-
- self.add(
- title: "std::unordered_set successful find",
- input: ([Int], [Int]).self
- ) { input, lookups in
- let set = CppUnorderedSet(input)
- return { timer in
- lookups.withUnsafeBufferPointer { buffer in
- cpp_unordered_set_lookups(set.ptr, buffer.baseAddress, buffer.count, true)
- }
- }
- }
-
- self.add(
- title: "std::unordered_set unsuccessful find",
- input: ([Int], [Int]).self
- ) { input, lookups in
- let set = CppUnorderedSet(input)
- let lookups = lookups.map { $0 + input.count }
- return { timer in
- lookups.withUnsafeBufferPointer { buffer in
- cpp_unordered_set_lookups(set.ptr, buffer.baseAddress, buffer.count, false)
- }
- }
- }
-
- self.addSimple(
- title: "std::unordered_set insert",
- input: [Int].self
- ) { input in
- input.withUnsafeBufferPointer { buffer in
- cpp_unordered_set_insert_integers(buffer.baseAddress, buffer.count, false)
- }
- }
-
- self.addSimple(
- title: "std::unordered_set insert, reserving capacity",
- input: [Int].self
- ) { input in
- input.withUnsafeBufferPointer { buffer in
- cpp_unordered_set_insert_integers(buffer.baseAddress, buffer.count, true)
- }
- }
-
- self.add(
- title: "std::unordered_set erase",
- input: ([Int], [Int]).self
- ) { input, removals in
- return { timer in
- let set = CppUnorderedSet(input)
- timer.measure {
- removals.withUnsafeBufferPointer { buffer in
- cpp_unordered_set_removals(set.ptr, buffer.baseAddress, buffer.count)
- }
- }
- set.destroy()
- }
- }
-
- //--------------------------------------------------------------------------
-
- self.addSimple(
- title: "std::unordered_map insert from integer range",
- input: Int.self
- ) { count in
- cpp_unordered_map_from_int_range(count)
- }
-
- self.add(
- title: "std::unordered_map sequential iteration",
- input: [Int].self
- ) { input in
- let set = CppUnorderedMap(input)
- return { timer in
- cpp_unordered_map_iterate(set.ptr)
- }
- }
-
- self.add(
- title: "std::unordered_map successful find",
- input: ([Int], [Int]).self
- ) { input, lookups in
- let map = CppUnorderedMap(input)
- return { timer in
- lookups.withUnsafeBufferPointer { buffer in
- cpp_unordered_map_lookups(map.ptr, buffer.baseAddress, buffer.count, true)
- }
- }
- }
-
- self.add(
- title: "std::unordered_map unsuccessful find",
- input: ([Int], [Int]).self
- ) { input, lookups in
- let map = CppUnorderedMap(input)
- let lookups = lookups.map { $0 + input.count }
- return { timer in
- lookups.withUnsafeBufferPointer { buffer in
- cpp_unordered_map_lookups(map.ptr, buffer.baseAddress, buffer.count, false)
- }
- }
- }
-
- self.add(
- title: "std::unordered_map subscript, existing key",
- input: ([Int], [Int]).self
- ) { input, lookups in
- let map = CppUnorderedMap(input)
- return { timer in
- lookups.withUnsafeBufferPointer { buffer in
- cpp_unordered_map_subscript(map.ptr, buffer.baseAddress, buffer.count)
- }
- }
- }
-
- self.add(
- title: "std::unordered_map subscript, new key",
- input: ([Int], [Int]).self
- ) { input, lookups in
- let map = CppUnorderedMap(input)
- let lookups = lookups.map { $0 + input.count }
- return { timer in
- lookups.withUnsafeBufferPointer { buffer in
- cpp_unordered_map_subscript(map.ptr, buffer.baseAddress, buffer.count)
- }
- }
- }
-
- self.addSimple(
- title: "std::unordered_map insert",
- input: [Int].self
- ) { input in
- input.withUnsafeBufferPointer { buffer in
- cpp_unordered_map_insert_integers(buffer.baseAddress, buffer.count, false)
- }
- }
-
- self.addSimple(
- title: "std::unordered_map insert, reserving capacity",
- input: [Int].self
- ) { input in
- input.withUnsafeBufferPointer { buffer in
- cpp_unordered_map_insert_integers(buffer.baseAddress, buffer.count, true)
- }
- }
-
- self.add(
- title: "std::unordered_map erase existing",
- input: ([Int], [Int]).self
- ) { input, removals in
- return { timer in
- let map = CppUnorderedMap(input)
- timer.measure {
- removals.withUnsafeBufferPointer { buffer in
- cpp_unordered_map_removals(map.ptr, buffer.baseAddress, buffer.count)
- }
- }
- map.destroy()
- }
- }
-
- self.add(
- title: "std::unordered_map erase missing",
- input: ([Int], [Int]).self
- ) { input, removals in
- return { timer in
- let map = CppUnorderedMap(input.map { input.count + $0 })
- timer.measure {
- removals.withUnsafeBufferPointer { buffer in
- cpp_unordered_map_removals(map.ptr, buffer.baseAddress, buffer.count)
- }
- }
- map.destroy()
- }
- }
-
- //--------------------------------------------------------------------------
-
- self.addSimple(
- title: "std::priority_queue construct from buffer",
- input: [Int].self
- ) { input in
- let pq = CppPriorityQueue(input)
- blackHole(pq)
- }
-
- self.add(
- title: "std::priority_queue push",
- input: [Int].self
- ) { input in
- return { timer in
- let pq = CppPriorityQueue()
- timer.measure {
- pq.push(input)
- }
- blackHole(pq)
- pq.destroy()
- }
- }
-
- self.add(
- title: "std::priority_queue pop",
- input: [Int].self
- ) { input in
- return { timer in
- let pq = CppPriorityQueue(input)
- timer.measure {
- pq.popAll()
- }
- blackHole(pq)
- pq.destroy()
- }
- }
-
- //--------------------------------------------------------------------------
-
- self.addSimple(
- title: "std::map insert",
- input: [Int].self
- ) { input in
- input.withUnsafeBufferPointer { buffer in
- cpp_map_insert_integers(buffer.baseAddress, buffer.count)
- }
- }
-
- self.add(
- title: "std::map successful find",
- input: ([Int], [Int]).self
- ) { input, lookups in
- let map = CppMap(input)
- return { timer in
- lookups.withUnsafeBufferPointer { buffer in
- cpp_map_lookups(map.ptr, buffer.baseAddress, buffer.count)
- }
- }
- }
- }
-}
diff --git a/Benchmarks/Benchmarks/FoundationBenchmarks.swift b/Benchmarks/Benchmarks/Foundation/CFBinaryHeapBenchmarks.swift
similarity index 98%
rename from Benchmarks/Benchmarks/FoundationBenchmarks.swift
rename to Benchmarks/Benchmarks/Foundation/CFBinaryHeapBenchmarks.swift
index 0f950c65..5f7bde4a 100644
--- a/Benchmarks/Benchmarks/FoundationBenchmarks.swift
+++ b/Benchmarks/Benchmarks/Foundation/CFBinaryHeapBenchmarks.swift
@@ -37,7 +37,7 @@ extension CFBinaryHeap {
#endif
extension Benchmark {
- public mutating func addFoundationBenchmarks() {
+ internal mutating func _addCFBinaryHeapBenchmarks() {
self.add(
title: "CFBinaryHeapAddValue",
input: [Int].self
diff --git a/Benchmarks/Benchmarks/Foundation/CFBitVectorBenchmarks.swift b/Benchmarks/Benchmarks/Foundation/CFBitVectorBenchmarks.swift
new file mode 100644
index 00000000..bea983fa
--- /dev/null
+++ b/Benchmarks/Benchmarks/Foundation/CFBitVectorBenchmarks.swift
@@ -0,0 +1,161 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+import CollectionsBenchmark
+
+#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
+import Foundation
+
+extension CFMutableBitVector {
+ static func _create(
+ count: Int,
+ trueBits: S
+ ) -> CFMutableBitVector where S.Element == Int {
+ let bits = CFBitVectorCreateMutable(nil, count)!
+ CFBitVectorSetCount(bits, count)
+ for index in trueBits {
+ CFBitVectorSetBitAtIndex(bits, index, 1)
+ }
+ return bits
+ }
+}
+#endif
+
+extension Benchmark {
+ internal mutating func _addCFBitVectorBenchmarks() {
+ self.add(
+ title: "CFBitVector create from integer buffer",
+ input: [Int].self
+ ) { input in
+#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
+ return { timer in
+ let trueCount = input.count / 2
+ let bits = CFMutableBitVector._create(
+ count: input.count,
+ trueBits: input[..
+#include
+#include
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/// Create a `std::vector` of the specified size, filling it with the
+/// given value. Returns an opaque pointer to the created instance.
+extern void *cpp_vector_bool_create_repeating(size_t count, bool value);
+
+/// Destroy a vector previously returned by `cpp_vector_bool_create`.
+extern void cpp_vector_bool_destroy(void *ptr);
+
+extern void cpp_vector_bool_push_back(const bool *start, size_t count, bool reserve);
+
+extern void cpp_vector_bool_pop_back(void *ptr, size_t count);
+
+/// Set bits indexed by a buffer of integers to true, using the unchecked subscript.
+extern void cpp_vector_bool_set_indices_subscript(void *ptr, const intptr_t *start, size_t count);
+
+/// Set bits indexed by a buffer of integers to true, using the checked `at` method.
+extern void cpp_vector_bool_set_indices_at(void *ptr, const intptr_t *start, size_t count);
+
+/// Set bits indexed by a buffer of integers to false, using the unchecked subscript.
+extern void cpp_vector_bool_reset_indices_subscript(void *ptr, const intptr_t *start, size_t count);
+
+/// Set bits indexed by a buffer of integers to false, using the checked `at` method.
+extern void cpp_vector_bool_reset_indices_at(void *ptr, const intptr_t *start, size_t count);
+
+/// Retrieve all bits indexed by a buffer of integers, using the unchecked subscript.
+extern void cpp_vector_bool_lookups_subscript(void *ptr, const intptr_t *start, size_t count);
+
+/// Retrieve all bits indexed by a buffer of integers, using the checked `at` method.
+extern void cpp_vector_bool_lookups_at(void *ptr, const intptr_t *start, size_t count);
+
+/// Iterate through all the bits in a `vector`.
+extern void cpp_vector_bool_iterate(void *ptr);
+
+/// Use `std::find` to visit every true bit in a `vector`, returning
+/// the number of true bits found.
+extern size_t cpp_vector_bool_find_true_bits(void *ptr);
+
+/// Use `std::count` to return a count of every true bit in a `vector`.
+extern size_t cpp_vector_bool_count_true_bits(void *ptr);
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif /* CPPBENCHMARKS_VECTOR_BOOL_BENCHMARKS_H */
diff --git a/Benchmarks/CppBenchmarks/include/module.modulemap b/Benchmarks/CppBenchmarks/include/module.modulemap
index 900b0f1a..65f516c5 100644
--- a/Benchmarks/CppBenchmarks/include/module.modulemap
+++ b/Benchmarks/CppBenchmarks/include/module.modulemap
@@ -7,5 +7,6 @@ module CppBenchmarks {
header "UnorderedMapBenchmarks.h"
header "MapBenchmarks.h"
header "PriorityQueueBenchmarks.h"
+ header "VectorBoolBenchmarks.h"
export *
}
diff --git a/Benchmarks/CppBenchmarks/src/VectorBoolBenchmarks.cpp b/Benchmarks/CppBenchmarks/src/VectorBoolBenchmarks.cpp
new file mode 100644
index 00000000..29cc320a
--- /dev/null
+++ b/Benchmarks/CppBenchmarks/src/VectorBoolBenchmarks.cpp
@@ -0,0 +1,147 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+#include
+#include
+#include "VectorBoolBenchmarks.h"
+#include "Utils.h"
+
+void *
+cpp_vector_bool_create_repeating(size_t count, bool value)
+{
+ auto v = new std::vector(count, value);
+ return v;
+}
+
+void
+cpp_vector_bool_destroy(void *ptr)
+{
+ delete static_cast *>(ptr);
+}
+
+void
+cpp_vector_bool_push_back(const bool *start, size_t count, bool reserve)
+{
+ auto v = std::vector();
+
+ if (reserve) {
+ v.reserve(v.size() + count);
+ }
+
+ for (auto p = start; p < start + count; ++p) {
+ v.push_back(*p);
+ }
+
+ black_hole(&v);
+}
+
+void
+cpp_vector_bool_pop_back(void *ptr, size_t count)
+{
+ auto &v = *static_cast *>(ptr);
+
+ for (size_t i = 0; i < count; ++i) {
+ v.pop_back();
+ }
+}
+
+void
+cpp_vector_bool_set_indices_subscript(void *ptr, const intptr_t *start, size_t count)
+{
+ auto &v = *static_cast *>(ptr);
+
+ for (auto p = start; p < start + count; ++p) {
+ v[*p] = true;
+ }
+}
+
+void
+cpp_vector_bool_set_indices_at(void *ptr, const intptr_t *start, size_t count)
+{
+ auto &v = *static_cast *>(ptr);
+
+ for (auto p = start; p < start + count; ++p) {
+ v.at(*p) = true;
+ }
+}
+
+void
+cpp_vector_bool_reset_indices_subscript(void *ptr, const intptr_t *start, size_t count)
+{
+ auto &v = *static_cast *>(ptr);
+
+ for (auto p = start; p < start + count; ++p) {
+ v[*p] = false;
+ }
+}
+
+void
+cpp_vector_bool_reset_indices_at(void *ptr, const intptr_t *start, size_t count)
+{
+ auto &v = *static_cast *>(ptr);
+
+ for (auto p = start; p < start + count; ++p) {
+ v.at(*p) = false;
+ }
+}
+
+void
+cpp_vector_bool_lookups_subscript(void *ptr, const intptr_t *start, size_t count)
+{
+ auto &v = *static_cast *>(ptr);
+
+ for (auto p = start; p < start + count; ++p) {
+ black_hole(v[*p]);
+ }
+}
+
+void
+cpp_vector_bool_lookups_at(void *ptr, const intptr_t *start, size_t count)
+{
+ auto &v = *static_cast *>(ptr);
+
+ for (auto p = start; p < start + count; ++p) {
+ black_hole(v.at(*p));
+ }
+}
+
+void
+cpp_vector_bool_iterate(void *ptr)
+{
+ auto &v = *static_cast *>(ptr);
+
+ for (auto it = v.cbegin(); it != v.cend(); ++it) {
+ black_hole(*it);
+ }
+}
+
+size_t
+cpp_vector_bool_find_true_bits(void *ptr)
+{
+ auto &v = *static_cast *>(ptr);
+
+ size_t count = 0;
+ for (auto it = std::find(v.cbegin(), v.cend(), true);
+ it != v.cend();
+ it = std::find(it, v.cend(), true)) {
+ ++count;
+ ++it;
+ }
+ return count;
+}
+
+size_t
+cpp_vector_bool_count_true_bits(void *ptr)
+{
+ auto &v = *static_cast *>(ptr);
+
+ return std::count(v.cbegin(), v.cend(), true);
+}
diff --git a/Benchmarks/Libraries/BitSet.json b/Benchmarks/Libraries/BitSet.json
new file mode 100644
index 00000000..900631a5
--- /dev/null
+++ b/Benchmarks/Libraries/BitSet.json
@@ -0,0 +1,78 @@
+{
+ "kind": "group",
+ "title": "Bitset Benchmarks",
+ "directory": "Results",
+ "contents": [
+ {
+ "kind": "group",
+ "title": "BitSet Operations",
+ "contents": [
+ ]
+ },
+ {
+ "kind": "group",
+ "title": "BitArray Operations",
+ "contents": [
+ ]
+ },
+ {
+ "kind": "group",
+ "title": "Comparisons against reference implementations",
+ "directory": "versus",
+ "contents": [
+ {
+ "kind": "chart",
+ "title": "initializers",
+ "tasks": [
+ "std::vector create from integer buffer (subscript)",
+ "std::vector create from integer buffer (at)",
+ "CFBitVector create from integer buffer"
+ ]
+ },
+ {
+ "kind": "chart",
+ "title": "sequential iteration",
+ "tasks": [
+ "std::vector const_iterator",
+ "CFBitVectorGetBitAtIndex (sequential iteration)"
+ ]
+ },
+ {
+ "kind": "chart",
+ "title": "random-access lookups",
+ "tasks": [
+ "std::vector random-access offset lookups (subscript)",
+ "std::vector random-access offset lookups (at)",
+ "CFBitVectorGetBitAtIndex (random-access lookups)"
+ ]
+ },
+ {
+ "kind": "chart",
+ "title": "set random bits to true",
+ "tasks": [
+ "std::vector set bits to true (subscript)",
+ "std::vector set bits to true (at)",
+ "CFBitVectorSetBitAtIndex (random-access set)"
+ ]
+ },
+ {
+ "kind": "chart",
+ "title": "find true bits",
+ "tasks": [
+ "std::vector find true bits",
+ "CFBitVectorGetFirstIndexOfBit"
+ ]
+ },
+ {
+ "kind": "chart",
+ "title": "count true bits",
+ "tasks": [
+ "std::vector count true bits",
+ "CFBitVectorGetCountOfBit"
+ ]
+ },
+ ]
+ }
+ ]
+
+}
diff --git a/Package.resolved b/Benchmarks/Package.resolved
similarity index 89%
rename from Package.resolved
rename to Benchmarks/Package.resolved
index 6089c1fc..e881f916 100644
--- a/Package.resolved
+++ b/Benchmarks/Package.resolved
@@ -6,8 +6,8 @@
"repositoryURL": "https://github.com/apple/swift-argument-parser",
"state": {
"branch": null,
- "revision": "986d191f94cec88f6350056da59c2e59e83d1229",
- "version": "0.4.3"
+ "revision": "83b23d940471b313427da226196661856f6ba3e0",
+ "version": "0.4.4"
}
},
{
diff --git a/Benchmarks/Package.swift b/Benchmarks/Package.swift
new file mode 100644
index 00000000..d7a7ec64
--- /dev/null
+++ b/Benchmarks/Package.swift
@@ -0,0 +1,47 @@
+// swift-tools-version:5.3
+//===----------------------------------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+import PackageDescription
+
+let package = Package(
+ name: "swift-collections.Benchmarks",
+ dependencies: [
+ .package(name: "swift-collections", path: ".."),
+ .package(url: "https://github.com/apple/swift-collections-benchmark", from: "0.0.1"),
+ ],
+ targets: [
+ .target(
+ name: "Benchmarks",
+ dependencies: [
+ .product(name: "Collections", package: "swift-collections"),
+ .product(name: "CollectionsBenchmark", package: "swift-collections-benchmark"),
+ "CppBenchmarks",
+ ],
+ path: "Benchmarks",
+ resources: [
+ .copy("Library.json"),
+ ]
+ ),
+ .target(
+ name: "CppBenchmarks",
+ path: "CppBenchmarks"
+ ),
+ .target(
+ name: "benchmark",
+ dependencies: [
+ "Benchmarks",
+ ],
+ path: "benchmark-tool"
+ ),
+ ],
+ cxxLanguageStandard: .cxx1z
+)
diff --git a/Benchmarks/swift-collections-benchmark/main.swift b/Benchmarks/benchmark-tool/main.swift
similarity index 100%
rename from Benchmarks/swift-collections-benchmark/main.swift
rename to Benchmarks/benchmark-tool/main.swift
diff --git a/Documentation/Heap.md b/Documentation/Heap.md
index 8a37ec52..929c6fd4 100644
--- a/Documentation/Heap.md
+++ b/Documentation/Heap.md
@@ -104,17 +104,7 @@ We also have non-optional flavors that assume the heap isn't empty, `removeMin()
### Iteration
-`Heap` itself doesn't conform to `Sequence` because of the potential confusion around which direction it should iterate (largest-to-smallest? smallest-to-largest?). Instead, we expose two iterators that conform to `Sequence`:
-
-```swift
-for val in heap.ascending {
- ...
-}
-
-for val in heap.descending {
- ...
-}
-```
+`Heap` itself doesn't conform to `Sequence` because of the potential confusion around which direction it should iterate (largest-to-smallest? smallest-to-largest?).
### Performance
@@ -134,29 +124,30 @@ The above graph was generated in release mode on a MacBook Pro (16-inch, 2019) w
## Implementation Details
-The implementation is based off [Atkinson et al. Min-Max Heaps and Generalized Priority Queues (1986)](http://akira.ruc.dk/~keld/teaching/algoritmedesign_f03/Artikler/02/Atkinson86.pdf).
+The implementation is based on the min-max heap data structure as introduced by [Atkinson et al. 1986].
-In a min-max heap, each node at an even level in the tree is less than all its descendants, while each node at an odd level in the tree is greater than all of its descendants.
+[Atkinson et al. 1986]: https://doi.org/10.1145/6617.6621
-["A min-max heap is a complete binary tree data structure."](https://en.wikipedia.org/wiki/Min-max_heap) This means that all the levels in the tree are filled except the last and that they are filled from left to right. The tree can be stored in an array:
+Min-max heaps are complete binary trees represented implicitly as an array of their elements. Each node at an even level in the tree is less than or equal to all its descendants, while each node at an odd level in the tree is greater or equal to all of its descendants.
```
// Min-max heap:
-level 0: 8
-level 1: 71 41
-level 2: 31 10 11 16
-level 3: 46 51 31 21 13
+level 0 (min): ┌────── A ──────┐
+level 1 (max): ┌── J ──┐ ┌── G ──┐
+level 2 (min): ┌ D ┐ ┌ B F C
+level 3 (max): I E H
// Array representation:
-[8, 71, 41, 31, 10, 11, 16, 46, 51, 31, 21, 13]
+["A", "J", "G", "D", "B", "F", "C", "I", "E", "H"]
```
-**Heap property**: Each element in an even level in the tree is less than all its descendants; each element in an odd level in the tree is greater than all its descendants. _Mutations to the heap **must** maintain this heap property._
+By the min-max property above, the root node is an on even level, so its value ("A" in this example) must be the minimum of the entire heap. Its two children are on an odd level, so they hold the maximum value for their respective subtrees; it follows that one of them holds the maximum value for the whole tree -- in this case, "J". Accessing the minimum and maximum values in the heap can therefore be done in O(1) comparisons.
-The levels start at 0 (even), so the smallest element in the tree is at the root. In the example above, the root of the tree is 8, which is the smallest element. The next level in the tree (containing 71 and 41) is a max level, so those elements are greater than all their respective descendants. Because this is the first max level in the tree, the largest element in the tree is one of the two elements (71).
-
-Note that the comparisons only take into account descendants — it is possible, for example, for elements at a lower level to be larger than elements in a different branch that are higher up the tree. In the example above, 41 isn't the second-largest element in the tree, but _it is_ the largest element in the right branch of the root node.
+Mutations of the heap (insertions, removals) must ensure that items remain arranged in a way that maintain the min-max property. Inserting a single new element or removing the current minimum/maximum can be done by rearranging items on a single path in the tree; accordingly, these operations execute O(log(`count`)) comparisons/swaps.
---
-M.D. Atkinson, J.-R. Sack, N. Santoro, T. Strothotte. October 1986. Min-Max Heaps and Generalized Priority Queues. Communications of the ACM. 29(10):996-1000.
+M.D. Atkinson, J.-R. Sack, N. Santoro, T. Strothotte.
+"Min-Max Heaps and Generalized Priority Queues."
+*Communications of the ACM*, vol. 29, no. 10, Oct. 1986., pp. 996-1000,
+doi:[10.1145/6617.6621](https://doi.org/10.1145/6617.6621)
diff --git a/Documentation/Internals/README.md b/Documentation/Internals/README.md
new file mode 100644
index 00000000..a5594c39
--- /dev/null
+++ b/Documentation/Internals/README.md
@@ -0,0 +1,119 @@
+# Package Internals
+
+## Benchmarks
+
+The package includes an extensive library of benchmarks in the [Benchmarks](./Benchmarks) directory, driven by a command-line executable target, called `benchmark`. These benchmarks, the executable target, and its command-line interface are not considered part of the public interface of the package. As such, new releases may break them without any special ceremony. We do expect the benchmarks will stabilize with time.
+
+For more information on our benchmarking tool, please see its dedicated package, [**Swift Collections Benchmark**][swift-collections-benchmark].
+
+[swift-collections-benchmark]: https://github.com/apple/swift-collections-benchmark
+
+## Test Support Library
+
+The package comes with a rich test support library in the [Sources/_CollectionsTestSupport](./Sources/_CollectionsTestSupport) directory. These were loosely adapted from the contents of the `StdlibUnittest*` modules in the [Swift compiler repository](https://github.com/apple/swift/tree/main/stdlib/private), with some custom additions.
+
+These components would likely be of interest to the wider Swift community, but they aren't yet stable enough (or documented enough) to publish them. Accordingly, these testing helpers are currently considered implementation details of this package, and are subject to change at whim.
+
+The test support library currently provides the following functionality:
+
+- [`AssertionContexts`](./Sources/CollectionsTestSupport/AssertionContexts): Custom test assertions with support for keeping track of nested context information, including stopping execution when the current context matches a particular value. (Useful for debugging combinatorial tests.)
+
+
+ Click here for a short demonstration
+
+ ```swift
+ import XCTest
+ import _CollectionsTestSupport
+
+ final class DequeTests: CollectionTestCase {
+ func test_demo() {
+ let values = [0, 10, 20, 30, 42, 50, 60]
+ for i in values.indices {
+ context.withTrace("i: \(i)") {
+ expectEqual(values[i], 10 * i)
+ }
+ }
+ }
+ }
+ ```
+
+ ```
+ DemoTests.swift:21: error: -[DemoTests.DemoTests test_demo] : XCTAssertEqual failed: ("42") is not equal to ("40") -
+ Trace:
+ - i: 4
+ ```
+
+ To debug issues, copy the trace message into a `context.failIfTraceMatches(_:)` invocation and set a breakpoint on test failures.
+
+ ```swift
+ let values = [0, 10, 20, 30, 42, 50, 60]
+ for i in values.indices {
+ context.withTrace("i: \(i)") {
+ // This will report a test failure before executing the `i == 4` case,
+ // letting us investigate what's going on.
+ context.failIfTraceMatches("""
+ Trace:
+ - i: 4
+ """)
+ expectEqual(values[i], 10 * i)
+ }
+ }
+ ```
+
+
+
+- [`Combinatorics`](./Sources/CollectionsTestSupport/AssertionContexts/Combinatorics.swift): Basic support for exhaustive combinatorial testing. This allows us to easily verify that a collection operation works correctly on all possible instances up to a certain size, including behavioral variations such as unique/shared storage.
+
+
+ Click here for an example
+
+ ```swift
+ func test_popFirst() {
+ withEveryDeque("deque", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in
+ withEvery("isShared", in: [false, true]) { isShared in
+ withLifetimeTracking { tracker in
+ var (deque, contents) = tracker.deque(with: layout)
+ withHiddenCopies(if: isShared, of: &deque) { deque in
+ let expected = contents[...].popFirst()
+ let actual = deque.popFirst()
+ expectEqual(actual, expected)
+ expectEqualElements(deque, contents)
+ }
+ }
+ }
+ }
+ }
+ ```
+
+
+
+- [`ConformanceCheckers`](./Sources/CollectionsTestSupport/ConformanceCheckers): A set of generic, semi-automated protocol conformance tests for some Standard Library protocols. These can be used to easily validate the custom protocol conformances provided by this package. These checks aren't (can't be) complete -- but when used correctly, they are able to detect most accidental mistakes.
+
+ We currently have conformance checkers for the following protocols:
+
+ - [`Sequence`](./Sources/CollectionsTestSupport/ConformanceCheckers/CheckSequence.swift)
+ - [`Collection`](./Sources/CollectionsTestSupport/ConformanceCheckers/CheckCollection.swift)
+ - [`BidirectionalCollection`](./Sources/CollectionsTestSupport/ConformanceCheckers/CheckBidirectionalCollection.swift)
+ - [`Equatable`](./Sources/CollectionsTestSupport/ConformanceCheckers/CheckEquatable.swift)
+ - [`Hashable`](./Sources/CollectionsTestSupport/ConformanceCheckers/CheckHashable.swift)
+ - [`Comparable`](./Sources/CollectionsTestSupport/ConformanceCheckers/CheckComparable.swift)
+
+- [`MinimalTypes`](./Sources/CollectionsTestSupport/MinimalTypes): Minimally conforming implementations for standard protocols. These types conform to various standard protocols by implementing the requirements in as narrow-minded way as possible -- sometimes going to extreme lengths to, say, implement collection index invalidation logic in the most unhelpful way possible.
+
+ - [`MinimalSequence`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalSequence.swift)
+ - [`MinimalCollection`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalCollection.swift)
+ - [`MinimalBidirectionalCollection`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalBidirectionalCollection.swift)
+ - [`MinimalRandomAccessCollection`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalRandomAccessCollection.swift)
+ - [`MinimalMutableRandomAccessCollection`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalMutableRandomAccessCollection.swift)
+ - [`MinimalRangeReplaceableRandomAccessCollection`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalRangeReplaceableRandomAccessCollection.swift)
+ - [`MinimalMutableRangeReplaceableRandomAccessCollection`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalMutableRangeReplaceableRandomAccessCollection.swift)
+ - [`MinimalIterator`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalIterator.swift)
+ - [`MinimalIndex`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalIndex.swift)
+ - [`MinimalEncoder`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalEncoder.swift)
+ - [`MinimalDecoder`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalDecoder.swift)
+
+- [`Utilities`](./Sources/CollectionsTestSupport/Utilities): Utility types. Wrapper types for boxed values, a simple deterministic random number generator, and a lifetime tracker for catching simple memory management issues such as memory leaks. (The [Address Sanitizer][asan] can be used to catch more serious problems.)
+
+[asan]: https://developer.apple.com/documentation/xcode/diagnosing_memory_thread_and_crash_issues_early?language=objc
+
+
diff --git a/Documentation/Internals/ReleaseChecklist.md b/Documentation/Internals/ReleaseChecklist.md
new file mode 100644
index 00000000..cee53107
--- /dev/null
+++ b/Documentation/Internals/ReleaseChecklist.md
@@ -0,0 +1,58 @@
+# Swift Collections Release Checklist
+
+1. Create a milestone for the new version (if one doesn't exist yet).
+2. Collect all issues & PRs that are going to be included in the new tag under the new milestone.
+3. If the new release moves code between source files or adds new API that has the potential to cause mutual dependencies between source files, then run the [shuffle-sources.sh](./Utils/shuffle-sources.sh) script for at least a few hundred iterations on the affected module to help catch [nondeterministic build issues with the compiler's MergeModules phase](https://github.com/apple/swift-collections/issues/7). (Note: it's best to do this on a fresh clone. We can stop doing this when MergeModules is no longer used to build debug configurations in SPM.)
+4. Run the [full tests script](./Utils/run-full-tests.sh) on the commit that you intend to tag, with all supported (major) toolchain releases, and on as many supported platforms as are practical. (At minimum, run the script with the latest stable toolchain releases on macOS and one Linux distribution.)
+ The script exercises a tiny subset of the environments this package can be built and run on.
+
+ The full matrix includes the following axes:
+
+ - Toolchains
+ - All major Swift releases supported by the package, plus a recent toolchain snapshot from swift.org.
+ E.g., for the Swift Collection 1.0 release, this included:
+ - Swift 5.3 (from swift.org and Xcode 12)
+ - Swift 5.4 (from swift.org and Xcode 12.5)
+ - Prerelease builds of Swift 5.5 (using the latest swift.org snapshot and the latest Xcode 13 beta)
+ - The latest `main` development snapshot from swift.org.
+ - Platforms & architectures
+ - macOS (using SPM, xcodebuild, cmake)
+ - Intel, Apple Silicon
+ - Deploying on any macOS release starting from macOS 10.10
+ - Mac Catalyst (using xcodebuild)
+ - Intel, Apple Silicon
+ - Deploying on any macOS release starting from macOS 10.15
+ - iOS (using xcodebuild)
+ - Device (arm64, armv7), simulator (x86_64, i386, arm64)
+ - Deploying on any iOS release starting from iOS 8
+ - watchOS (using xcodebuild)
+ - Device (arm64_32, arm7k), simulator (x86_64, i386, arm64)
+ - Deploying on any watchOS release starting from watchOS 2
+ - tvOS (using xcodebuild)
+ - Device (arm64), simulator (x86_64, arm64)
+ - Deploying on any tvOS 9 release starting from tvOS 10
+ - Linux (using SPM, cmake)
+ - All supported distributions
+ - Build systems
+ - Swift Package Manager
+ - xcodebuild
+ - cmake & ninja (note: this support isn't source stable)
+ - Configurations
+ - Debug
+ - Release
+ - Build settings
+ - `COLLECTIONS_INTERNAL_CHECKS`
+ - `COLLECTIONS_DETERMINISTIC_HASHING`
+ - `BUILD_LIBRARY_FOR_DISTRIBUTION=YES` with xcodebuild (this is unsupported, but why break it)
+ - `-warnings-as-errors`
+ - Any combination of the above
+ - Components
+ - The swift-collections package
+ - The private `benchmark` executable under `Benchmarks/`
+
+5. Submit PRs to fix any issues that pop up, then try again until no issues are found.
+6. Update the README if necessary.
+7. Draft a new release on GitHub, following the template established by [previous releases](https://github.com/apple/swift-collections/releases/tag/0.0.7).
+8. As a final chance to catch issues, generate a diff between the last tagged release and the release candidate commit. Review it in case we landed something that isn't appropriate to include; watch out for potential issues such as source compatibility problems, or new public API without adequate documentation.
+9. Double check that the new tag will have the right version number and it will be on the correct branch.
+10. Hit publish.
diff --git a/Documentation/OrderedDictionary.md b/Documentation/OrderedDictionary.md
index aa56e195..834613e5 100644
--- a/Documentation/OrderedDictionary.md
+++ b/Documentation/OrderedDictionary.md
@@ -88,14 +88,14 @@ for character in text {
If the `Value` type implements reference semantics, or when you need to
perform a series of individual mutations on the values, the closure-based
-`modifyValue(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.
```swift
let text = "short string"
var counts: OrderedDictionary = [:]
for character in text {
- counts.modifyValue(forKey: character, default: 0) { value in
+ counts.updateValue(forKey: character, default: 0) { value in
value += 1
}
}
diff --git a/Documentation/OrderedSet.md b/Documentation/OrderedSet.md
index 3815437e..9786a66e 100644
--- a/Documentation/OrderedSet.md
+++ b/Documentation/OrderedSet.md
@@ -101,7 +101,7 @@ let b: OrderedSet = [3, 2, 1, 0]
a == b // false
a.unordered == b.unordered // true
-func frobnicate(_ set: S) { ... }
+func frobnicate(_ set: S) { ... }
frobnicate(a) // error: `OrderedSet` does not conform to `SetAlgebra`
frobnicate(a.unordered) // OK
```
diff --git a/Package.swift b/Package.swift
index 3ab9cdc8..e8628a98 100644
--- a/Package.swift
+++ b/Package.swift
@@ -57,10 +57,6 @@ let package = Package(
.library(name: "SortedCollections", targets: ["SortedCollections"]),
.library(name: "PriorityQueueModule", targets: ["PriorityQueueModule"]),
],
- dependencies: [
- // This is only used in the benchmark executable target.
- .package(url: "https://github.com/apple/swift-collections-benchmark", from: "0.0.1"),
- ],
targets: [
.target(
name: "Collections",
@@ -76,7 +72,7 @@ let package = Package(
// Testing support module
.target(
- name: "CollectionsTestSupport",
+ name: "_CollectionsTestSupport",
dependencies: [],
swiftSettings: settings,
linkerSettings: [
@@ -87,34 +83,9 @@ let package = Package(
),
.testTarget(
name: "CollectionsTestSupportTests",
- dependencies: ["CollectionsTestSupport"],
+ dependencies: ["_CollectionsTestSupport"],
swiftSettings: settings),
- // Benchmarking
- .target(
- name: "Benchmarks",
- dependencies: [
- .product(name: "CollectionsBenchmark", package: "swift-collections-benchmark"),
- "Collections",
- "CppBenchmarks",
- ],
- path: "Benchmarks/Benchmarks",
- resources: [
- .copy("Library.json"),
- ]
- ),
- .target(
- name: "CppBenchmarks",
- path: "Benchmarks/CppBenchmarks"
- ),
- .target(
- name: "swift-collections-benchmark",
- dependencies: [
- "Benchmarks",
- ],
- path: "Benchmarks/swift-collections-benchmark"
- ),
-
// Deque
.target(
name: "DequeModule",
@@ -122,7 +93,7 @@ let package = Package(
swiftSettings: settings),
.testTarget(
name: "DequeTests",
- dependencies: ["DequeModule", "CollectionsTestSupport"],
+ dependencies: ["DequeModule", "_CollectionsTestSupport"],
swiftSettings: settings),
// OrderedSet, OrderedDictionary
@@ -132,18 +103,9 @@ let package = Package(
swiftSettings: settings),
.testTarget(
name: "OrderedCollectionsTests",
- dependencies: ["OrderedCollections", "CollectionsTestSupport"],
+ dependencies: ["OrderedCollections", "_CollectionsTestSupport"],
swiftSettings: settings),
- // SortedDictionary
- .target(
- name: "SortedCollections",
- swiftSettings: settings),
- .testTarget(
- name: "SortedCollectionsTests",
- dependencies: ["SortedCollections", "CollectionsTestSupport"],
- swiftSettings: settings),
-
// PriorityQueue
.target(
name: "PriorityQueueModule",
@@ -153,6 +115,14 @@ let package = Package(
name: "PriorityQueueTests",
dependencies: ["PriorityQueueModule"],
swiftSettings: settings),
- ],
- cxxLanguageStandard: .cxx1z
+
+ // SortedDictionary
+ .target(
+ name: "SortedCollections",
+ swiftSettings: settings),
+ .testTarget(
+ name: "SortedCollectionsTests",
+ dependencies: ["SortedCollections", "_CollectionsTestSupport"],
+ swiftSettings: settings),
+ ]
)
diff --git a/README.md b/README.md
index 1ef75646..712fb3ea 100644
--- a/README.md
+++ b/README.md
@@ -16,13 +16,21 @@ The package currently provides the following implementations:
- [`OrderedDictionary`][OrderedDictionary], an ordered variant of the standard `Dictionary`, providing similar benefits.
-- [`Heap`](Documentation/Heap.md], a min-max heap backed by an array.
-
[Deque]: Documentation/Deque.md
[OrderedSet]: Documentation/OrderedSet.md
[OrderedDictionary]: Documentation/OrderedDictionary.md
-Swift Collections uses the same modularization approach as [**Swift Numerics**](https://github.com/apple/swift-numerics): it provides a standalone module for each group of data structures it implements. For instance, if you only need a double-ended queue type, you can pull in only that by importing `DequeModule`. `OrderedSet` and `OrderedDictionary` share much of the same underlying implementation, so they are provided by a single module, called `OrderedCollections`. However, there is also a top-level `Collections` module that gives you all of the included modules with a single import statement.
+The following data structures are currently being worked on but they aren't ready for inclusion in a tagged release:
+
+- [`Heap`][Heap] and [`PriorityQueue`](https://github.com/apple/swift-collections/pull/51), min-max heaps backed by an array.
+- [`SortedSet` and `SortedDictionary`](https://github.com/apple/swift-collections/pull/65), sorted collections backed by in-memory persistent b-trees.
+- [`HashSet` and `HashMap`](https://github.com/apple/swift-collections/pull/31), persistent hashed collections implemented as Compressed Hash-Array Mapped Prefix-Trees (CHAMP).
+- [`BitArray` and `BitSet`](https://github.com/apple/swift-collections/pull/83), dynamic bit vectors.
+- [`SparseSet`](https://github.com/apple/swift-collections/pull/80), a constant time set construct, trading off memory for speed.
+
+[Heap]: Documentation/Heap.md
+
+Swift Collections uses the same modularization approach as [**Swift Numerics**](https://github.com/apple/swift-numerics): it provides a standalone module for each thematic group of data structures it implements. For instance, if you only need a double-ended queue type, you can pull in only that by importing `DequeModule`. `OrderedSet` and `OrderedDictionary` share much of the same underlying implementation, so they are provided by a single module, called `OrderedCollections`. However, there is also a top-level `Collections` module that gives you every collection type with a single import statement:
``` swift
import Collections
@@ -35,156 +43,70 @@ print(deque) // ["Keeley", "Ted", "Rebecca", "Nathan"]
## Project Status
-We think the implementations in this package are robust, but the interfaces provided have not had time to stabilize. Accordingly, while the package is in its pre-1.0 state, from time to time new releases may sometimes include source-breaking changes. We'll try our best to keep such changes to a minimum, though, even during this chaotic initial period. Whenever feasible, we'll mitigate such changes with a multi-release deprecation period.
+The Swift Collections package is source stable. The version numbers follow [Semantic Versioning][semver] -- source breaking changes to public API can only land in a new major version.
-Before the 1.0 release, releases containing potentially source-breaking changes will increase the middle version number. The release notes will explain what changed, and how to update your code to work with the new version.
+[semver]: https://semver.org
-The implementations in this package have gone through an initial performance optimization pass, but there are lots of work still to be done. Still, we think these implementations are already quite fast enough for production use -- sometimes matching or exceeding the performance of similar constructs in popular prexisting implementations in other languages.
+The public API of version 1.0 of the `swift-collections` package consists of non-underscored declarations that are marked `public` in the `Collections`, `DequeModule` and `OrderedCollections` modules.
-### Underscored Interfaces
+Interfaces that aren't part of the public API may continue to change in any release, including patch releases.
+If you have a use case that requires using underscored APIs, please [submit a Feature Request][enhancement] describing it! We'd like the public interface to be as useful as possible -- although preferably without compromising safety or limiting future evolution.
-As customary in Swift, interfaces that are technically declared `public` but begin with an underscore are not considered part of the public interface of this package. We may remove or change them in any release without notice, including minor point releases. (If you have a use case that requires using them, please [submit a Feature Request][feature-request] describing it! We'd like the public interface to be as useful as possible -- preferably without compromising safety or limiting future evolution.)
+By "underscored declarations" we mean declarations that have a leading underscore anywhere in their fully qualified name. For instance, here are some names that wouldn't be considered part of the public API, even if they were technically marked public:
-[feature-request]: https://github.com/apple/swift-collections/issues/new?assignees=&labels=enhancement&template=FEATURE_REQUEST.md
+- `FooModule.Bar._someMember(value:)` (underscored member)
+- `FooModule._Bar.someMember` (underscored type)
+- `_FooModule.Bar` (underscored module)
+- `FooModule.Bar.init(_value:)` (underscored initializer)
-### Benchmarks
+Note that contents of the `Tests`, `Utils` and `Benchmarks` subdirectories aren't public API. We don't make any source compatibility promises about them -- they may change at whim, and code may be removed in any new release. Do not rely on anything about them.
-The package includes an extensive library of benchmarks in the [Benchmarks](./Benchmarks) directory, driven by a command-line executable target, `swift-collections-benchmark`. These benchmarks, the executable target, and its command-line interface are not considered part of the public interface of the package. As such, new releases may break them without any special ceremony. We do expect the benchmarks will stabilize with time.
-
-For more information on our benchmarking tool, please see its dedicated package, [**Swift Collections Benchmark**][swift-collections-benchmark].
-
-[swift-collections-benchmark]: https://github.com/apple/swift-collections-benchmark
-
-### Test Support Library
-
-The package comes with a rich test support library in the [Sources/CollectionsTestSupport](./Sources/CollectionsTestSupport) directory. These were loosely adapted from the contents of the `StdlibUnittest*` modules in the [Swift compiler repository](https://github.com/apple/swift/tree/main/stdlib/private), with some custom additions.
-
-These components would likely be of interest to the wider Swift community, but they aren't yet stable enough (or documented enough) to publish them. Accordingly, these testing helpers are currently considered implementation details of this package, and are subject to change at whim.
-
-The test support library currently provides the following functionality:
-
-- [`AssertionContexts`](./Sources/CollectionsTestSupport/AssertionContexts): Custom test assertions with support for keeping track of nested context information, including stopping execution when the current context matches a particular value. (Useful for debugging combinatorial tests.)
-
-
- Click here for a short demonstration
-
- ```swift
- import XCTest
- import CollectionsTestSupport
-
- final class DequeTests: CollectionTestCase {
- func test_demo() {
- let values = [0, 10, 20, 30, 42, 50, 60]
- for i in values.indices {
- context.withTrace("i: \(i)") {
- expectEqual(values[i], 10 * i)
- }
- }
- }
- }
- ```
-
- ```
- DemoTests.swift:21: error: -[DemoTests.DemoTests test_demo] : XCTAssertEqual failed: ("42") is not equal to ("40") -
- Trace:
- - i: 4
- ```
-
- To debug issues, copy the trace message into a `context.failIfTraceMatches(_:)` invocation and set a breakpoint on test failures.
-
- ```swift
- let values = [0, 10, 20, 30, 42, 50, 60]
- for i in values.indices {
- context.withTrace("i: \(i)") {
- // This will report a test failure before executing the `i == 4` case,
- // letting us investigate what's going on.
- context.failIfTraceMatches("""
- Trace:
- - i: 4
- """)
- expectEqual(values[i], 10 * i)
- }
- }
- ```
-
-
-
-- [`Combinatorics`](./Sources/CollectionsTestSupport/AssertionContexts/Combinatorics.swift): Basic support for exhaustive combinatorial testing. This allows us to easily verify that a collection operation works correctly on all possible instances up to a certain size, including behavioral variations such as unique/shared storage.
-
-
- Click here for an example
-
- ```swift
- func test_popFirst() {
- withEveryDeque("deque", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in
- withEvery("isShared", in: [false, true]) { isShared in
- withLifetimeTracking { tracker in
- var (deque, contents) = tracker.deque(with: layout)
- withHiddenCopies(if: isShared, of: &deque) { deque in
- let expected = contents[...].popFirst()
- let actual = deque.popFirst()
- expectEqual(actual, expected)
- expectEqualElements(deque, contents)
- }
- }
- }
- }
- }
- ```
-
-
-
-- [`ConformanceCheckers`](./Sources/CollectionsTestSupport/ConformanceCheckers): A set of generic, semi-automated protocol conformance tests for some Standard Library protocols. These can be used to easily validate the custom protocol conformances provided by this package. These checks aren't (can't be) complete -- but when used correctly, they are able to detect most accidental mistakes.
-
- We currently have conformance checkers for the following protocols:
-
- - [`Sequence`](./Sources/CollectionsTestSupport/ConformanceCheckers/CheckSequence.swift)
- - [`Collection`](./Sources/CollectionsTestSupport/ConformanceCheckers/CheckCollection.swift)
- - [`BidirectionalCollection`](./Sources/CollectionsTestSupport/ConformanceCheckers/CheckBidirectionalCollection.swift)
- - [`Equatable`](./Sources/CollectionsTestSupport/ConformanceCheckers/CheckEquatable.swift)
- - [`Hashable`](./Sources/CollectionsTestSupport/ConformanceCheckers/CheckHashable.swift)
- - [`Comparable`](./Sources/CollectionsTestSupport/ConformanceCheckers/CheckComparable.swift)
-
-- [`MinimalTypes`](./Sources/CollectionsTestSupport/MinimalTypes): Minimally conforming implementations for standard protocols. These types conform to various standard protocols by implementing the requirements in as narrow-minded way as possible -- sometimes going to extreme lengths to, say, implement collection index invalidation logic in the most unhelpful way possible.
-
- - [`MinimalSequence`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalSequence.swift)
- - [`MinimalCollection`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalCollection.swift)
- - [`MinimalBidirectionalCollection`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalBidirectionalCollection.swift)
- - [`MinimalRandomAccessCollection`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalRandomAccessCollection.swift)
- - [`MinimalMutableRandomAccessCollection`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalMutableRandomAccessCollection.swift)
- - [`MinimalRangeReplaceableRandomAccessCollection`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalRangeReplaceableRandomAccessCollection.swift)
- - [`MinimalMutableRangeReplaceableRandomAccessCollection`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalMutableRangeReplaceableRandomAccessCollection.swift)
- - [`MinimalIterator`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalIterator.swift)
- - [`MinimalIndex`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalIndex.swift)
- - [`MinimalEncoder`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalEncoder.swift)
- - [`MinimalDecoder`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalDecoder.swift)
-
-- [`Utilities`](./Sources/CollectionsTestSupport/Utilities): Utility types. Wrapper types for boxed values, a simple deterministic random number generator, and a lifetime tracker for catching simple memory management issues such as memory leaks. (The [Address Sanitizer][asan] can be used to catch more serious problems.)
-
-[asan]: https://developer.apple.com/documentation/xcode/diagnosing_memory_thread_and_crash_issues_early?language=objc
+Future minor versions of the package may update these rules as needed.
+We'd like this package to quickly embrace Swift language and toolchain improvements that are relevant to its mandate. Accordingly, from time to time, we expect that new versions of this package will require clients to upgrade to a more recent Swift toolchain release. (This allows the package to make use of new language/stdlib features, build on compiler bug fixes, and adopt new package manager functionality as soon as they are available.) Requiring a new Swift release will only need a minor version bump.
## Using **Swift Collections** in your project
-To use this package in a SwiftPM project, add the following line to the dependencies in your `Package.swift` file:
+To use this package in a SwiftPM project, you need to set it up as a package dependency:
```swift
-.package(url: "https://github.com/apple/swift-collections", from: "0.0.1"),
+// swift-tools-version:5.4
+import PackageDescription
+
+let package = Package(
+ name: "MyPackage",
+ dependencies: [
+ .package(
+ url: "https://github.com/apple/swift-collections.git",
+ .upToNextMajor(from: "1.0.0") // or `.upToNextMinor
+ )
+ ],
+ targets: [
+ .target(
+ name: "MyTarget",
+ dependencies: [
+ .product(name: "Collections", package: "swift-collections")
+ ]
+ )
+ ]
+)
```
## Contributing to Swift Collections
-### Asking questions
-
-We have a dedicated [Swift Collections Forum][forum] where we can ask and answer questions on how to use or work on this package. It's also a great place to discuss its evolution.
+We have a dedicated [Swift Collections Forum][forum] where people can ask and answer questions on how to use or work on this package. It's also a great place to discuss its evolution.
[forum]: https://forums.swift.org/c/related-projects/collections
-### Reporting a bug
-
If you find something that looks like a bug, please open a [Bug Report][bugreport]! Fill out as many details as you can.
-### Fixing a bug or making a small improvement
+### Working on the package
+
+We have some basic [documentation on package internals](./Documentation/Internals/README.md) that will help you get started.
+
+By submitting a pull request, you represent that you have the right to license your contribution to Apple and the community, and agree by submitting the patch that your contributions are licensed under the [Swift License](https://swift.org/LICENSE.txt), a copy of which is [provided in this repository](LICENSE.txt).
+
+#### Fixing a bug or making a small improvement
1. [Submit a PR][PR] with your change. If there is an [existing issue][issues] for the bug you're fixing, please include a reference to it.
2. Make sure to add tests covering whatever changes you are making.
@@ -194,7 +116,7 @@ If you find something that looks like a bug, please open a [Bug Report][bugrepor
[bugreport]: https://github.com/apple/swift-collections/issues/new?assignees=&labels=bug&template=BUG_REPORT.md
-### Proposing a small enhancement
+#### Proposing a small enhancement
1. Raise a [Feature Request][enhancement]. Discuss why it would be important to implement it.
2. Submit a PR with your implementation, participate in the review discussion.
@@ -203,7 +125,7 @@ If you find something that looks like a bug, please open a [Bug Report][bugrepor
[enhancement]: https://github.com/apple/swift-collections/issues/new?assignees=&labels=enhancement&template=FEATURE_REQUEST.md
-### Proposing the addition of a new data structure
+#### Proposing the addition of a new data structure
1. Start a topic on the [forum], explaining why you believe it would be important to implement the data structure. This way we can figure out if it would be right for the package, discuss implementation strategies, and plan to allocate capacity to help.
2. When maintainers agreed to your implementation plan, start work on it, and submit a PR with your implementation as soon as you have something that's ready to show! We'd love to get involved as early as you like.
@@ -211,17 +133,13 @@ If you find something that looks like a bug, please open a [Bug Report][bugrepor
3. When there is a consensus that the feature is ready, and the implementation is fully tested and documented, the PR will be merged by a maintainer.
4. Celebrate! You've achieved something great!
-### Licensing
-
-By submitting a pull request, you represent that you have the right to license your contribution to Apple and the community, and agree by submitting the patch that your contributions are licensed under the [Swift License](https://swift.org/LICENSE.txt), a copy of which is [provided in this repository](LICENSE.txt).
-
### Code of Conduct
Like all Swift.org projects, we would like the Swift Collections project to foster a diverse and friendly community. We expect contributors to adhere to the [Swift.org Code of Conduct](https://swift.org/code-of-conduct/). A copy of this document is [available in this repository][coc].
[coc]: CODE_OF_CONDUCT.md
-### Contacting the maintainers
+### Contact information
The current code owner of this package is Karoy Lorentey ([@lorentey](https://github.com/lorentey)). You can contact him [on the Swift forums](https://forums.swift.org/u/lorentey/summary), or by writing an email to klorentey at apple dot com. (Please keep it related to this project.)
diff --git a/Sources/DequeModule/Deque+Collection.swift b/Sources/DequeModule/Deque+Collection.swift
index d8884662..61ba34a2 100644
--- a/Sources/DequeModule/Deque+Collection.swift
+++ b/Sources/DequeModule/Deque+Collection.swift
@@ -16,6 +16,7 @@ extension Deque: Sequence {
// conversions from indices to storage slots.
/// An iterator over the members of a deque.
+ @frozen
public struct Iterator: IteratorProtocol {
@usableFromInline
internal var _storage: Deque._Storage
@@ -671,7 +672,7 @@ extension Deque: RangeReplaceableCollection {
}
let underestimatedCount = newElements.underestimatedCount
- reserveCapacity(count + underestimatedCount)
+ _storage.ensureUnique(minimumCapacity: count + underestimatedCount)
var it: S.Iterator = _storage.update { target in
let gaps = target.availableSegments()
let (it, copied) = gaps.initialize(fromSequencePrefix: newElements)
@@ -712,7 +713,7 @@ extension Deque: RangeReplaceableCollection {
let c = newElements.count
guard c > 0 else { return }
- reserveCapacity(count + c)
+ _storage.ensureUnique(minimumCapacity: count + c)
_storage.update { target in
let gaps = target.availableSegments().prefix(c)
gaps.initialize(from: newElements)
diff --git a/Sources/DequeModule/Deque+ExpressibleByArrayLiteral.swift b/Sources/DequeModule/Deque+ExpressibleByArrayLiteral.swift
index 54b6e917..fd7125c9 100644
--- a/Sources/DequeModule/Deque+ExpressibleByArrayLiteral.swift
+++ b/Sources/DequeModule/Deque+ExpressibleByArrayLiteral.swift
@@ -13,12 +13,12 @@ extension Deque: ExpressibleByArrayLiteral {
/// Creates a new deque from the contents of an array literal.
///
/// Do not call this initializer directly. It is used by the compiler when
- /// you use an array literal. Instead, create a new set using an array
+ /// you use an array literal. Instead, create a new deque using an array
/// literal as its value by enclosing a comma-separated list of values in
- /// square brackets. You can use an array literal anywhere a set is expected
+ /// square brackets. You can use an array literal anywhere a deque is expected
/// by the type context.
///
- /// - Parameter elements: A variadic list of elements of the new set.
+ /// - Parameter elements: A variadic list of elements of the new deque.
@inlinable
@inline(__always)
public init(arrayLiteral elements: Element...) {
diff --git a/Sources/DequeModule/Deque._Storage.swift b/Sources/DequeModule/Deque._Storage.swift
index 6e7de6d7..2c0a5d33 100644
--- a/Sources/DequeModule/Deque._Storage.swift
+++ b/Sources/DequeModule/Deque._Storage.swift
@@ -10,6 +10,7 @@
//===----------------------------------------------------------------------===//
extension Deque {
+ @frozen
@usableFromInline
struct _Storage {
@usableFromInline
diff --git a/Sources/DequeModule/Deque._UnsafeHandle.swift b/Sources/DequeModule/Deque._UnsafeHandle.swift
index b802821e..ed32110d 100644
--- a/Sources/DequeModule/Deque._UnsafeHandle.swift
+++ b/Sources/DequeModule/Deque._UnsafeHandle.swift
@@ -10,6 +10,7 @@
//===----------------------------------------------------------------------===//
extension Deque {
+ @frozen
@usableFromInline
internal struct _UnsafeHandle {
@usableFromInline
diff --git a/Sources/DequeModule/_DequeBuffer.swift b/Sources/DequeModule/_DequeBuffer.swift
index 62fd9e21..bc0df278 100644
--- a/Sources/DequeModule/_DequeBuffer.swift
+++ b/Sources/DequeModule/_DequeBuffer.swift
@@ -9,6 +9,7 @@
//
//===----------------------------------------------------------------------===//
+@_fixed_layout
@usableFromInline
internal class _DequeBuffer: ManagedBuffer<_DequeBufferHeader, Element> {
@inlinable
diff --git a/Sources/DequeModule/_UnsafeWrappedBuffer.swift b/Sources/DequeModule/_UnsafeWrappedBuffer.swift
index 0424403e..06a0a580 100644
--- a/Sources/DequeModule/_UnsafeWrappedBuffer.swift
+++ b/Sources/DequeModule/_UnsafeWrappedBuffer.swift
@@ -9,6 +9,7 @@
//
//===----------------------------------------------------------------------===//
+@frozen
@usableFromInline
internal struct _UnsafeWrappedBuffer {
@usableFromInline
@@ -51,6 +52,7 @@ internal struct _UnsafeWrappedBuffer {
internal var count: Int { first.count + (second?.count ?? 0) }
}
+@frozen
@usableFromInline
internal struct _UnsafeMutableWrappedBuffer {
@usableFromInline
diff --git a/Sources/OrderedCollections/CMakeLists.txt b/Sources/OrderedCollections/CMakeLists.txt
index 5d85c3d0..f595036c 100644
--- a/Sources/OrderedCollections/CMakeLists.txt
+++ b/Sources/OrderedCollections/CMakeLists.txt
@@ -8,6 +8,7 @@ See https://swift.org/LICENSE.txt for license information
#]]
add_library(OrderedCollections
+ "HashTable/_HashTable.swift"
"HashTable/_HashTable+Bucket.swift"
"HashTable/_HashTable+BucketIterator.swift"
"HashTable/_HashTable+Constants.swift"
@@ -15,8 +16,8 @@ add_library(OrderedCollections
"HashTable/_Hashtable+Header.swift"
"HashTable/_HashTable+Testing.swift"
"HashTable/_HashTable+UnsafeHandle.swift"
- "HashTable/_HashTable.swift"
+ "OrderedDictionary/OrderedDictionary.swift"
"OrderedDictionary/OrderedDictionary+Codable.swift"
"OrderedDictionary/OrderedDictionary+CustomDebugStringConvertible.swift"
"OrderedDictionary/OrderedDictionary+CustomReflectable.swift"
@@ -32,8 +33,9 @@ add_library(OrderedCollections
"OrderedDictionary/OrderedDictionary+Partial RangeReplaceableCollection.swift"
"OrderedDictionary/OrderedDictionary+Sequence.swift"
"OrderedDictionary/OrderedDictionary+Values.swift"
- "OrderedDictionary/OrderedDictionary.swift"
+ "OrderedDictionary/OrderedDictionary+Deprecations.swift"
+ "OrderedSet/OrderedSet.swift"
"OrderedSet/OrderedSet+Codable.swift"
"OrderedSet/OrderedSet+CustomDebugStringConvertible.swift"
"OrderedSet/OrderedSet+CustomReflectable.swift"
@@ -56,7 +58,6 @@ add_library(OrderedCollections
"OrderedSet/OrderedSet+Testing.swift"
"OrderedSet/OrderedSet+UnorderedView.swift"
"OrderedSet/OrderedSet+UnstableInternals.swift"
- "OrderedSet/OrderedSet.swift"
"Utilities/_UnsafeBitset.swift"
"Utilities/RandomAccessCollection+Offsets.swift")
diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Codable.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Codable.swift
index b303a454..61a9808c 100644
--- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Codable.swift
+++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Codable.swift
@@ -82,5 +82,6 @@ extension OrderedDictionary: Decodable where Key: Decodable, Value: Decodable {
_keys._appendNew(key, in: bucket)
_values.append(value)
}
+ _checkInvariants()
}
}
diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Deprecations.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Deprecations.swift
new file mode 100644
index 00000000..a8e531d8
--- /dev/null
+++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Deprecations.swift
@@ -0,0 +1,52 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+extension OrderedDictionary {
+ /// Accesses the element at the specified index.
+ ///
+ /// - Parameter offset: The offset of the element to access, measured from
+ /// the start of the collection. `offset` must be greater than or equal to
+ /// `0` and less than `count`.
+ ///
+ /// - Complexity: O(1)
+ @available(*, unavailable, // deprecated in 0.0.6, obsoleted in 1.0.0
+ message: "Please use `elements[offset]`")
+ @inlinable
+ @inline(__always)
+ public subscript(offset offset: Int) -> Element {
+ fatalError()
+ }
+}
+
+extension OrderedDictionary {
+ @available(*, unavailable, // deprecated in 0.0.6, obsoleted in 1.0.0
+ renamed: "updateValue(forKey:default:with:)")
+ @inlinable
+ public mutating func modifyValue(
+ forKey key: Key,
+ default defaultValue: @autoclosure () -> Value,
+ _ body: (inout Value) throws -> R
+ ) rethrows -> R {
+ fatalError()
+ }
+
+ @available(*, unavailable, // deprecated in 0.0.6, obsoleted in 1.0.0
+ renamed: "updateValue(forKey:insertingDefault:at:with:)")
+ @inlinable
+ public mutating func modifyValue(
+ forKey key: Key,
+ insertingDefault defaultValue: @autoclosure () -> Value,
+ at index: Int,
+ _ body: (inout Value) throws -> R
+ ) rethrows -> R {
+ fatalError()
+ }
+}
diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements+SubSequence.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements+SubSequence.swift
index 542defb3..ee7ccc1e 100644
--- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements+SubSequence.swift
+++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements+SubSequence.swift
@@ -53,19 +53,20 @@ extension OrderedDictionary.Elements.SubSequence {
extension OrderedDictionary.Elements.SubSequence {
/// 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 given key is found in the dictionary slice, this method returns an
+ /// index into the dictionary that corresponds with the key-value pair.
///
/// let countryCodes: OrderedDictionary = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]
- /// let index = countryCodes.index(forKey: "JP")
+ /// let slice = countryCodes.elements[1...]
+ /// let index = slice.index(forKey: "JP")
///
- /// print("Country code for \(countryCodes[index!].value): '\(countryCodes[index!].key)'.")
+ /// print("Country code for \(countryCodes[offset: index!].value): '\(countryCodes[offset: index!].key)'.")
/// // Prints "Country code for Japan: 'JP'."
///
- /// - Parameter key: The key to find in the dictionary.
+ /// - Parameter key: The key to find in the dictionary slice.
///
/// - Returns: The index for `key` and its associated value if `key` is in
- /// the dictionary; otherwise, `nil`.
+ /// the dictionary slice; otherwise, `nil`.
///
/// - Complexity: Expected to be O(1) on average, if `Key` implements
/// high-quality hashing.
@@ -95,10 +96,10 @@ extension OrderedDictionary.Elements.SubSequence: Sequence {
@inlinable
@inline(__always)
- internal init(_ base: OrderedDictionary.Elements.SubSequence) {
- self._base = base._base
- self._end = base._bounds.upperBound
- self._index = base._bounds.lowerBound
+ internal init(_base: OrderedDictionary.Elements.SubSequence) {
+ self._base = _base._base
+ self._end = _base._bounds.upperBound
+ self._index = _base._bounds.lowerBound
}
/// Advances to the next element and returns it, or `nil` if no next
@@ -117,7 +118,7 @@ extension OrderedDictionary.Elements.SubSequence: Sequence {
@inlinable
@inline(__always)
public func makeIterator() -> Iterator {
- Iterator(self)
+ Iterator(_base: self)
}
}
@@ -289,7 +290,7 @@ extension OrderedDictionary.Elements.SubSequence: RandomAccessCollection {
@inlinable
public subscript(position: Int) -> Element {
precondition(_bounds.contains(position), "Index out of range")
- return _base[offset: position]
+ return (_base._keys[position], _base._values[position])
}
/// Accesses a contiguous subrange of the dictionary's elements.
diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift
index a04799ad..d0507640 100644
--- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift
+++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift
@@ -79,9 +79,9 @@ extension OrderedDictionary.Elements {
/// into the dictionary that corresponds with the key-value pair.
///
/// let countryCodes: OrderedDictionary = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]
- /// let index = countryCodes.index(forKey: "JP")
+ /// let index = countryCodes.elements.index(forKey: "JP")
///
- /// print("Country code for \(countryCodes[index!].value): '\(countryCodes[index!].key)'.")
+ /// print("Country code for \(countryCodes[offset: index!].value): '\(countryCodes[offset: index!].key)'.")
/// // Prints "Country code for Japan: 'JP'."
///
/// - Parameter key: The key to find in the dictionary.
@@ -261,8 +261,7 @@ extension OrderedDictionary.Elements: RandomAccessCollection {
end - start
}
- /// Accesses the element at the specified position. This can be used to
- /// perform in-place mutations on dictionary values.
+ /// Accesses the element at the specified position.
///
/// - Parameter index: The position of the element to access. `index` must be
/// greater than or equal to `startIndex` and less than `endIndex`.
diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+ExpressibleByDictionaryLiteral.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+ExpressibleByDictionaryLiteral.swift
index 91f11600..8c1ed039 100644
--- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+ExpressibleByDictionaryLiteral.swift
+++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+ExpressibleByDictionaryLiteral.swift
@@ -13,17 +13,14 @@ extension OrderedDictionary: ExpressibleByDictionaryLiteral {
/// Creates a new ordered dictionary from the contents of a dictionary
/// literal.
///
- /// Duplicate elements in the literal are allowed, but the resulting
- /// set will only contain the first occurrence of each.
- ///
/// Do not call this initializer directly. It is used by the compiler when you
/// use a dictionary literal. Instead, create a new ordered dictionary using a
/// dictionary literal as its value by enclosing a comma-separated list of
- /// values in square brackets. You can use an array literal anywhere a set is
- /// expected by the type context.
+ /// key-value pairs in square brackets. You can use a dictionary literal
+ /// anywhere an ordered dictionary is expected by the type context.
///
/// - Parameter elements: A variadic list of key-value pairs for the new
- /// dictionary.
+ /// ordered dictionary.
///
/// - Complexity: O(`elements.count`) if `Key` implements
/// high-quality hashing.
diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Initializers.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Initializers.swift
index 1d27adaa..568be28d 100644
--- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Initializers.swift
+++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Initializers.swift
@@ -282,7 +282,7 @@ extension OrderedDictionary {
self.init()
for value in values {
let key = try keyForValue(value)
- self.modifyValue(forKey: key, default: Value()) { array in
+ self.updateValue(forKey: key, default: Value()) { array in
array.append(value)
}
}
@@ -300,6 +300,7 @@ extension OrderedDictionary {
_keys._appendNew(key)
_values.append(value)
}
+ _checkInvariants()
}
/// Creates a new dictionary from the key-value pairs in the given sequence,
diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial MutableCollection.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial MutableCollection.swift
index 4f58ae00..c01e9686 100644
--- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial MutableCollection.swift
+++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial MutableCollection.swift
@@ -51,6 +51,7 @@ extension OrderedDictionary {
let pivot = try _values.withUnsafeMutableBufferPointer { values in
try _keys._partition(values: values, by: belongsInSecondPartition)
}
+ _checkInvariants()
return pivot
}
}
@@ -103,6 +104,7 @@ extension OrderedDictionary {
_keys = OrderedSet(uncheckedUniqueElements: source.lazy.map { $0.key })
_values = ContiguousArray(source.lazy.map { $0.value })
}
+ _checkInvariants()
}
}
diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial RangeReplaceableCollection.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial RangeReplaceableCollection.swift
index af52aa35..bc5791ba 100644
--- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial RangeReplaceableCollection.swift
+++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial RangeReplaceableCollection.swift
@@ -178,6 +178,7 @@ extension OrderedDictionary {
by: shouldBeRemoved)
}
removeSubrange(pivot...)
+ _checkInvariants()
}
}
diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift
index 3b322743..1fe94039 100644
--- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift
+++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift
@@ -79,13 +79,13 @@
///
/// If the `Value` type implements reference semantics, or when you need to
/// perform a series of individual mutations on the values, the closure-based
-/// `modifyValue(forKey:default:_:)` method provides an easier-to-use
+/// `updateValue(forKey:default:_:)` method provides an easier-to-use
/// alternative to the defaulted key-based subscript.
///
/// let text = "short string"
/// var counts: OrderedDictionary = [:]
/// for character in text {
-/// counts.modifyValue(forKey: character, default: 0) { value in
+/// counts.updateValue(forKey: character, default: 0) { value in
/// value += 1
/// }
/// }
@@ -272,7 +272,7 @@ extension OrderedDictionary {
/// let countryCodes: OrderedDictionary = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]
/// let index = countryCodes.index(forKey: "JP")
///
- /// print("Country code for \(countryCodes[index!].value): '\(countryCodes[index!].key)'.")
+ /// print("Country code for \(countryCodes[offset: index!].value): '\(countryCodes[offset: index!].key)'.")
/// // Prints "Country code for Japan: 'JP'."
///
/// - Parameter key: The key to find in the dictionary.
@@ -287,20 +287,6 @@ extension OrderedDictionary {
public func index(forKey key: Key) -> Int? {
_keys.firstIndex(of: key)
}
-
- /// Accesses the element at the specified index. This can be used to
- /// perform in-place mutations on dictionary values.
- ///
- /// - Parameter offset: The offset of the element to access, measured from
- /// the start of the collection. `offset` must be greater than or equal to
- /// `0` and less than `count`.
- ///
- /// - Complexity: O(1)
- @inlinable
- @inline(__always)
- public subscript(offset offset: Int) -> Element {
- (_keys[offset], _values[offset])
- }
}
extension OrderedDictionary {
@@ -364,7 +350,7 @@ extension OrderedDictionary {
}
set {
// We have a separate `set` in addition to `_modify` in hopes of getting
- // rid of `_modify`'s swapAt dance in the usua case where the calle just
+ // rid of `_modify`'s swapAt dance in the usual case where the caller just
// wants to assign a new value.
let (index, bucket) = _keys._find(key)
switch (index, newValue) {
@@ -379,6 +365,7 @@ extension OrderedDictionary {
case (nil, nil): // Noop
break
}
+ _checkInvariants()
}
_modify {
let (index, bucket) = _keys._find(key)
@@ -408,6 +395,7 @@ extension OrderedDictionary {
case (nil, nil): // Noop
break
}
+ _checkInvariants()
}
yield &value
@@ -641,7 +629,7 @@ extension OrderedDictionary {
/// let message = "Hello, Elle!"
/// var letterCounts: [Character: Int] = [:]
/// for letter in message {
- /// letterCounts.modifyValue(forKey: letter, default: 0) { count in
+ /// letterCounts.updateValue(forKey: letter, default: 0) { count in
/// count += 1
/// }
/// }
@@ -660,10 +648,10 @@ extension OrderedDictionary {
/// - Complexity: expected complexity is amortized O(1), if `Key` implements
/// high-quality hashing. (Ignoring the complexity of calling `body`.)
@inlinable
- public mutating func modifyValue(
+ public mutating func updateValue(
forKey key: Key,
default defaultValue: @autoclosure () -> Value,
- _ body: (inout Value) throws -> R
+ with body: (inout Value) throws -> R
) rethrows -> R {
let (index, bucket) = _keys._find(key)
if let index = index {
@@ -687,7 +675,7 @@ extension OrderedDictionary {
/// let message = "Hello, Elle!"
/// var letterCounts: [Character: Int] = [:]
/// for letter in message {
- /// letterCounts.modifyValue(forKey: letter, default: 0) { count in
+ /// letterCounts.updateValue(forKey: letter, default: 0) { count in
/// count += 1
/// }
/// }
@@ -706,11 +694,11 @@ extension OrderedDictionary {
/// - Complexity: expected complexity is amortized O(1), if `Key` implements
/// high-quality hashing. (Ignoring the complexity of calling `body`.)
@inlinable
- public mutating func modifyValue(
+ public mutating func updateValue(
forKey key: Key,
insertingDefault defaultValue: @autoclosure () -> Value,
at index: Int,
- _ body: (inout Value) throws -> R
+ with body: (inout Value) throws -> R
) rethrows -> R {
let (existingIndex, bucket) = _keys._find(key)
if let existingIndex = existingIndex {
diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+ExpressibleByArrayLiteral.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+ExpressibleByArrayLiteral.swift
index 1b92f341..1d1d6dec 100644
--- a/Sources/OrderedCollections/OrderedSet/OrderedSet+ExpressibleByArrayLiteral.swift
+++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+ExpressibleByArrayLiteral.swift
@@ -12,16 +12,16 @@
extension OrderedSet: ExpressibleByArrayLiteral {
/// Creates a new ordered set from the contents of an array literal.
///
- /// Duplicate elements in the literal are allowed, but the resulting
+ /// Duplicate elements in the literal are allowed, but the resulting ordered
/// set will only contain the first occurrence of each.
///
/// Do not call this initializer directly. It is used by the compiler when
- /// you use an array literal. Instead, create a new set using an array
+ /// you use an array literal. Instead, create a new ordered set using an array
/// literal as its value by enclosing a comma-separated list of values in
- /// square brackets. You can use an array literal anywhere a set is expected
- /// by the type context.
+ /// square brackets. You can use an array literal anywhere an ordered set is
+ /// expected by the type context.
///
- /// - Parameter elements: A variadic list of elements of the new set.
+ /// - Parameter elements: A variadic list of elements of the new ordered set.
///
/// - Complexity: O(`elements.count`) if `Element` implements
/// high-quality hashing.
diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Initializers.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Initializers.swift
index 82a6a76b..e4cf7e94 100644
--- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Initializers.swift
+++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Initializers.swift
@@ -10,20 +10,6 @@
//===----------------------------------------------------------------------===//
extension OrderedSet {
- @inlinable
- internal init(_uncheckedUniqueElements elements: ContiguousArray) {
-#if DEBUG
- self.init(_uniqueElements: elements)
-#else
- guard elements.count > _HashTable.maximumUnhashedCount else {
- self.init(_uniqueElements: elements, nil)
- return
- }
- let table = _HashTable.create(uncheckedUniqueElements: elements)
- self.init(_uniqueElements: elements, table)
-#endif
- }
-
/// Creates a set with the contents of the given sequence, which
/// must not include duplicate elements.
///
@@ -44,7 +30,18 @@ extension OrderedSet {
@inline(__always)
public init(uncheckedUniqueElements elements: S)
where S.Element == Element {
- self.init(_uncheckedUniqueElements: ContiguousArray(elements))
+ let elements = ContiguousArray(elements)
+#if DEBUG
+ let (table, firstDupe) = _HashTable.create(untilFirstDuplicateIn: elements)
+ precondition(firstDupe == elements.endIndex,
+ "Duplicate elements found in input")
+#else
+ let table = _HashTable.create(uncheckedUniqueElements: elements)
+#endif
+ self.init(
+ _uniqueElements: elements,
+ elements.count > _HashTable.maximumUnhashedCount ? table : nil)
+ _checkInvariants()
}
}
diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Insertions.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Insertions.swift
index e1037edf..6b054366 100644
--- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Insertions.swift
+++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Insertions.swift
@@ -10,17 +10,18 @@
//===----------------------------------------------------------------------===//
extension OrderedSet {
- /// Append a new member to the end of the set, without verifying
- /// that the set doesn't already contain it.
+ /// Append a new item to the end of the set, assuming it's not already
+ /// a member.
///
- /// This operation performs no hashing operations unless it needs to
- /// reallocate the hash table.
+ /// In optimized builds, this does not check for duplicates.
///
+ /// - Parameter item: The item to add to the set. The item must no be already
+ /// a member.
/// - Complexity: Expected to be O(1) on average if `Element`
/// implements high-quality hashing.
@inlinable
internal mutating func _appendNew(_ item: Element) {
- assert(!contains(item))
+ assert(!contains(item), "Duplicate item")
_elements.append(item)
guard _elements.count <= _capacity else {
_regenerateHashTable()
@@ -128,6 +129,7 @@ extension OrderedSet {
return
}
+ _ensureUnique()
_table!.update { hashTable in
assert(!hashTable.isOccupied(bucket))
hashTable.adjustContents(preparingForInsertionOfElementAtOffset: index, in: _elements)
diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Invariants.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Invariants.swift
index 588ecd88..51c853b7 100644
--- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Invariants.swift
+++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Invariants.swift
@@ -13,7 +13,7 @@ extension OrderedSet {
#if COLLECTIONS_INTERNAL_CHECKS
@inlinable
@inline(never) @_effects(releasenone)
- internal func _checkInvariants() {
+ public func _checkInvariants() {
if _table == nil {
precondition(_elements.count <= _HashTable.maximumUnhashedCount,
"Oversized set without a hash table")
diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial RangeReplaceableCollection.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial RangeReplaceableCollection.swift
index 543c7c8b..fd8750d0 100644
--- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial RangeReplaceableCollection.swift
+++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial RangeReplaceableCollection.swift
@@ -215,7 +215,10 @@ extension OrderedSet {
public mutating func removeAll(
where shouldBeRemoved: (Element) throws -> Bool
) rethrows {
- defer { _regenerateHashTable() }
+ defer {
+ _regenerateHashTable()
+ _checkInvariants()
+ }
try _elements.removeAll(where: shouldBeRemoved)
}
}
diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra+Operations.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra+Operations.swift
index 9aac480d..474d7431 100644
--- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra+Operations.swift
+++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra+Operations.swift
@@ -165,6 +165,7 @@ extension OrderedSet {
result._appendNew(item)
}
}
+ result._checkInvariants()
return result
}
@@ -244,7 +245,9 @@ extension OrderedSet {
bitset.insert(index)
}
}
- return self._extractSubset(using: bitset)
+ let result = self._extractSubset(using: bitset)
+ result._checkInvariants()
+ return result
}
}
@@ -304,6 +307,7 @@ extension OrderedSet {
for offset in bitset2 {
result._appendNew(other._elements[offset])
}
+ result._checkInvariants()
return result
}
}
@@ -411,6 +415,7 @@ extension OrderedSet {
for item in new._elements {
result._appendNew(item)
}
+ result._checkInvariants()
return result
}
}
@@ -574,7 +579,9 @@ extension OrderedSet {
}
}
assert(difference.count > 0)
- return _extractSubset(using: difference)
+ let result = _extractSubset(using: difference)
+ result._checkInvariants()
+ return result
}
}
}
diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+RandomAccessCollection.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+RandomAccessCollection.swift
index d1228031..7e5eed85 100644
--- a/Sources/OrderedCollections/OrderedSet/OrderedSet+RandomAccessCollection.swift
+++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+RandomAccessCollection.swift
@@ -244,7 +244,7 @@ extension OrderedSet: RandomAccessCollection {
@inlinable
public subscript(bounds: Range) -> SubSequence {
_failEarlyRangeCheck(bounds, bounds: startIndex ..< endIndex)
- return SubSequence(base: self, bounds: bounds)
+ return SubSequence(_base: self, bounds: bounds)
}
/// A Boolean value indicating whether the collection is empty.
diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+SubSequence.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+SubSequence.swift
index 5500cffc..706c8f99 100644
--- a/Sources/OrderedCollections/OrderedSet/OrderedSet+SubSequence.swift
+++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+SubSequence.swift
@@ -26,8 +26,8 @@ extension OrderedSet {
@inlinable
@inline(__always)
- internal init(base: OrderedSet, bounds: Range) {
- self._base = base
+ internal init(_base: OrderedSet, bounds: Range) {
+ self._base = _base
self._bounds = bounds
}
}
@@ -289,7 +289,7 @@ extension OrderedSet.SubSequence: RandomAccessCollection {
@inline(__always)
public subscript(bounds: Range) -> SubSequence {
_failEarlyRangeCheck(bounds, bounds: startIndex ..< endIndex)
- return SubSequence(base: _base, bounds: bounds)
+ return SubSequence(_base: _base, bounds: bounds)
}
/// A Boolean value indicating whether the collection is empty.
diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Testing.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Testing.swift
index 2b87dfad..edac2d8b 100644
--- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Testing.swift
+++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Testing.swift
@@ -86,6 +86,7 @@ extension OrderedSet._UnstableInternals {
}
}
base._table = new
+ base._checkInvariants()
}
@_spi(Testing)
@@ -95,6 +96,7 @@ extension OrderedSet._UnstableInternals {
persistent: Bool
) {
base._reserveCapacity(minimumCapacity, persistent: persistent)
+ base._checkInvariants()
}
}
@@ -121,5 +123,6 @@ extension OrderedSet {
scale < _HashTable.minimumScale ? nil : table)
precondition(self._scale == scale)
precondition(self._bias == bias)
+ _checkInvariants()
}
}
diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+UnorderedView.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+UnorderedView.swift
index cc679d43..b0222a64 100644
--- a/Sources/OrderedCollections/OrderedSet/OrderedSet+UnorderedView.swift
+++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+UnorderedView.swift
@@ -12,6 +12,7 @@
extension OrderedSet {
/// An unordered view into an ordered set, providing `SetAlgebra`
/// conformance.
+ @frozen
public struct UnorderedView {
public typealias Element = OrderedSet.Element
diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet.swift
index 188d344c..9e3965bb 100644
--- a/Sources/OrderedCollections/OrderedSet/OrderedSet.swift
+++ b/Sources/OrderedCollections/OrderedSet/OrderedSet.swift
@@ -89,7 +89,7 @@
/// a == b // false
/// a.unordered == b.unordered // true
///
-/// func frobnicate(_ set: S) { ... }
+/// func frobnicate(_ set: S) { ... }
/// frobnicate(a) // error: `OrderedSet` does not conform to `SetAlgebra`
/// frobnicate(a.unordered) // OK
///
@@ -247,10 +247,10 @@ public struct OrderedSet where Element: Hashable
@inlinable
internal init(
_uniqueElements: ContiguousArray,
- _ table: _HashTable? = nil
+ _ table: _HashTable?
) {
self.__storage = table?._storage
- self._elements = ContiguousArray(_uniqueElements)
+ self._elements = _uniqueElements
}
@inlinable
diff --git a/Sources/PriorityQueueModule/CMakeLists.txt b/Sources/PriorityQueueModule/CMakeLists.txt
index 1ddcd8e2..14319cf3 100644
--- a/Sources/PriorityQueueModule/CMakeLists.txt
+++ b/Sources/PriorityQueueModule/CMakeLists.txt
@@ -8,10 +8,11 @@ See https://swift.org/LICENSE.txt for license information
#]]
add_library(PriorityQueueModule
+ _Node.swift
Heap.swift
Heap+ExpressibleByArrayLiteral.swift
Heap+Invariants.swift
- Heap+OrderedViews.swift)
+ Heap+UnsafeHandle.swift)
set_target_properties(PriorityQueueModule PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
diff --git a/Sources/PriorityQueueModule/Heap+ExpressibleByArrayLiteral.swift b/Sources/PriorityQueueModule/Heap+ExpressibleByArrayLiteral.swift
index 466d6c94..c6522ab4 100644
--- a/Sources/PriorityQueueModule/Heap+ExpressibleByArrayLiteral.swift
+++ b/Sources/PriorityQueueModule/Heap+ExpressibleByArrayLiteral.swift
@@ -18,7 +18,7 @@ extension Heap: ExpressibleByArrayLiteral {
/// square brackets. You can use an array literal anywhere a heap is expected
/// by the type context.
///
- /// - Parameter elements: A variadic list of elements of the new set.
+ /// - Parameter elements: A variadic list of elements of the new heap.
public init(arrayLiteral elements: Element...) {
self.init(elements)
}
diff --git a/Sources/PriorityQueueModule/Heap+Invariants.swift b/Sources/PriorityQueueModule/Heap+Invariants.swift
index 3396df5a..418bfe8c 100644
--- a/Sources/PriorityQueueModule/Heap+Invariants.swift
+++ b/Sources/PriorityQueueModule/Heap+Invariants.swift
@@ -10,82 +10,44 @@
//===----------------------------------------------------------------------===//
import Swift
-import Foundation
extension Heap {
#if COLLECTIONS_INTERNAL_CHECKS
- /// Iterates through all the levels in the heap, ensuring that items in min
- /// levels are smaller than all their descendants and items in max levels
- /// are larger than all their descendants.
- ///
- /// The min-max heap indices are structured like this:
- ///
- /// ```
- /// min 0
- /// max 1 2
- /// min 3 4 5 6
- /// max 7 8 9 10 11 12 13 14
- /// min 15...
- /// ...
- /// ```
- ///
- /// The iteration happens in depth-first order, so the descendants of the
- /// element at index 0 are checked to ensure they are >= that element. This is
- /// repeated for each child of the element at index 0 (inverting the
- /// comparison at each level).
- ///
- /// In the case of 7 elements total (spread across 3 levels), the checking
- /// happens in the following order:
- ///
- /// ```
- /// compare >= 0: 1, 3, 4, 2, 5, 6
- /// compare <= 1: 3, 4
- /// compare >= 3: (no children)
- /// compare >= 4: (no children)
- /// compare <= 2: 5, 6
- /// compare >= 5: (no children)
- /// compare >= 6: (no children)
- /// ```
+ /// Visits each item in the heap in depth-first order, verifying that the
+ /// contents satisfy the min-max heap property.
@inlinable
@inline(never)
internal func _checkInvariants() {
guard count > 1 else { return }
- var indicesToVisit: [Int] = [0]
+ _checkInvariants(node: .root, min: nil, max: nil)
+ }
- while let elementIdx = indicesToVisit.popLast() {
- let element = _storage[elementIdx]
-
- let isMinLevel = _minMaxHeapIsMinLevel(elementIdx)
-
- var descendantIndicesToVisit = [Int]()
-
- // Add the children of this element to the outer loop (as we want to check
- // that they are >= or <= their descendants as well)
- if let rightIdx = _rightChildIndex(of: elementIdx) {
- descendantIndicesToVisit.append(rightIdx)
- indicesToVisit.append(rightIdx)
+ @inlinable
+ internal func _checkInvariants(node: _Node, min: Element?, max: Element?) {
+ let value = _storage[node.offset]
+ if let min = min {
+ precondition(value >= min,
+ "Element \(value) at \(node) is less than min \(min)")
+ }
+ if let max = max {
+ precondition(value <= max,
+ "Element \(value) at \(node) is greater than max \(max)")
+ }
+ let left = node.leftChild()
+ let right = node.rightChild()
+ if node.isMinLevel {
+ if left.offset < count {
+ _checkInvariants(node: left, min: value, max: max)
}
- if let leftIdx = _leftChildIndex(of: elementIdx) {
- descendantIndicesToVisit.append(leftIdx)
- indicesToVisit.append(leftIdx)
+ if right.offset < count {
+ _checkInvariants(node: right, min: value, max: max)
}
-
- // Compare the current element against its descendants
- while let idx = descendantIndicesToVisit.popLast() {
- if isMinLevel {
- precondition(element <= _storage[idx],
- "Element '\(_storage[idx])' at index \(idx) should be >= '\(element)'")
- } else {
- precondition(element >= _storage[idx],
- "Element '\(_storage[idx])' at index \(idx) should be <= '\(element)'")
- }
-
- if let rightIdx = _rightChildIndex(of: idx) {
- descendantIndicesToVisit.append(rightIdx)
- }
- if let leftIdx = _leftChildIndex(of: idx) {
- descendantIndicesToVisit.append(leftIdx)
- }
+ } else {
+ if left.offset < count {
+ _checkInvariants(node: left, min: min, max: value)
+ }
+ if right.offset < count {
+ _checkInvariants(node: right, min: min, max: value)
}
}
}
diff --git a/Sources/PriorityQueueModule/Heap+OrderedViews.swift b/Sources/PriorityQueueModule/Heap+OrderedViews.swift
deleted file mode 100644
index bf6536c8..00000000
--- a/Sources/PriorityQueueModule/Heap+OrderedViews.swift
+++ /dev/null
@@ -1,60 +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
-//
-//===----------------------------------------------------------------------===//
-
-extension Heap {
- /// A view of a `Heap`'s elements, as a `Sequence` from the smallest to
- /// largest element.
- public struct AscendingView: Sequence, IteratorProtocol {
- @usableFromInline
- internal var _base: Heap
-
- /// Creates an ascending-element view from the given heap.
- @inlinable
- init(_base: Heap) {
- self._base = _base
- }
-
- @inlinable
- public mutating func next() -> Element? {
- return _base.popMin()
- }
- }
-
- /// A view of a `Heap`'s elements, as a `Sequence` from the largest to
- /// smallest element.
- public struct DescendingView: Sequence, IteratorProtocol {
- @usableFromInline
- internal var _base: Heap
-
- /// Creates a descending-element view from the given heap.
- @inlinable
- init(_base: Heap) {
- self._base = _base
- }
-
- @inlinable
- public mutating func next() -> Element? {
- return _base.popMax()
- }
- }
-
- /// Returns an iterator that orders elements from smallest to largest
- @inlinable
- public var ascending: AscendingView {
- return AscendingView(_base: self)
- }
-
- /// Returns an iterator that orders elements from largest to smallest
- @inlinable
- public var descending: DescendingView {
- return DescendingView(_base: self)
- }
-}
diff --git a/Sources/PriorityQueueModule/Heap+UnsafeHandle.swift b/Sources/PriorityQueueModule/Heap+UnsafeHandle.swift
new file mode 100644
index 00000000..d20f10c0
--- /dev/null
+++ b/Sources/PriorityQueueModule/Heap+UnsafeHandle.swift
@@ -0,0 +1,371 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+extension Heap {
+ @usableFromInline @frozen
+ struct _UnsafeHandle {
+ @usableFromInline
+ var buffer: UnsafeMutableBufferPointer
+
+ @inlinable @inline(__always)
+ init(_ buffer: UnsafeMutableBufferPointer) {
+ self.buffer = buffer
+ }
+ }
+
+ @inlinable @inline(__always)
+ mutating func _update(_ body: (_UnsafeHandle) -> R) -> R {
+ _storage.withUnsafeMutableBufferPointer { buffer in
+ body(_UnsafeHandle(buffer))
+ }
+ }
+}
+
+extension Heap._UnsafeHandle {
+ @inlinable @inline(__always)
+ internal var count: Int {
+ buffer.count
+ }
+
+ @inlinable
+ subscript(node: _Node) -> Element {
+ @inline(__always)
+ get {
+ buffer[node.offset]
+ }
+ @inline(__always)
+ nonmutating _modify {
+ yield &buffer[node.offset]
+ }
+ }
+
+ @inlinable @inline(__always)
+ internal func ptr(to node: _Node) -> UnsafeMutablePointer {
+ assert(node.offset < count)
+ return buffer.baseAddress! + node.offset
+ }
+
+ /// Move the value at the specified node out of the buffer, leaving it
+ /// uninitialized.
+ @inlinable @inline(__always)
+ internal func extract(_ node: _Node) -> Element {
+ ptr(to: node).move()
+ }
+
+ @inlinable @inline(__always)
+ internal func initialize(_ node: _Node, to value: __owned Element) {
+ ptr(to: node).initialize(to: value)
+ }
+
+ /// Swaps the elements in the heap at the given indices.
+ @inlinable @inline(__always)
+ internal func swapAt(_ i: _Node, _ j: _Node) {
+ buffer.swapAt(i.offset, j.offset)
+ }
+
+ /// Swaps the element at the given node with the supplied value.
+ @inlinable @inline(__always)
+ internal func swapAt(_ i: _Node, with value: inout Element) {
+ let p = buffer.baseAddress.unsafelyUnwrapped + i.offset
+ swap(&p.pointee, &value)
+ }
+
+
+ @inlinable @inline(__always)
+ internal func minValue(_ a: _Node, _ b: _Node) -> _Node {
+ self[a] < self[b] ? a : b
+ }
+
+ @inlinable @inline(__always)
+ internal func maxValue(_ a: _Node, _ b: _Node) -> _Node {
+ self[a] < self[b] ? b : a
+ }
+}
+
+extension Heap._UnsafeHandle {
+ @inlinable
+ internal func bubbleUp(_ node: _Node) {
+ guard !node.isRoot else { return }
+
+ let parent = node.parent()
+
+ var node = node
+ if (node.isMinLevel && self[node] > self[parent])
+ || (!node.isMinLevel && self[node] < self[parent]){
+ swapAt(node, parent)
+ node = parent
+ }
+
+ if node.isMinLevel {
+ while let grandparent = node.grandParent(),
+ self[node] < self[grandparent] {
+ swapAt(node, grandparent)
+ node = grandparent
+ }
+ } else {
+ while let grandparent = node.grandParent(),
+ self[node] > self[grandparent] {
+ swapAt(node, grandparent)
+ node = grandparent
+ }
+ }
+ }
+}
+
+extension Heap._UnsafeHandle {
+ /// Sink the item at `node` to its correct position in the heap.
+ /// The given node must be minimum-ordered.
+ @inlinable
+ internal func trickleDownMin(_ node: _Node) {
+ assert(node.isMinLevel)
+ var node = node
+ var value = extract(node)
+ _trickleDownMin(node: &node, value: &value)
+ initialize(node, to: value)
+ }
+
+ @inlinable @inline(__always)
+ internal func _trickleDownMin(node: inout _Node, value: inout Element) {
+ // Note: `_Node` is quite the useless abstraction here, as we don't need
+ // to look at its `level` property, and we need to move sideways amongst
+ // siblings/cousins in the tree, for which we don't have direct operations.
+ // Luckily, all the `_Node` business gets optimized away, so this only
+ // affects the readability of the code, not its performance.
+ // The alternative would be to reintroduce offset-based parent/child
+ // navigation methods, which seems less palatable.
+
+ var gc0 = node.firstGrandchild()
+ while gc0.offset &+ 3 < count {
+ // Invariant: buffer slot at `node` is uninitialized
+
+ // We have four grandchildren, so we don't need to compare children.
+ let gc1 = _Node(offset: gc0.offset &+ 1, level: gc0.level)
+ let minA = minValue(gc0, gc1)
+
+ let gc2 = _Node(offset: gc0.offset &+ 2, level: gc0.level)
+ let gc3 = _Node(offset: gc0.offset &+ 3, level: gc0.level)
+ let minB = minValue(gc2, gc3)
+
+ let min = minValue(minA, minB)
+ guard self[min] < value else {
+ return // We're done -- `node` is a good place for `value`.
+ }
+
+ initialize(node, to: extract(min))
+ node = min
+ gc0 = node.firstGrandchild()
+
+ let parent = min.parent()
+ if self[parent] < value {
+ swapAt(parent, with: &value)
+ }
+ }
+
+ // At this point, we don't have a full complement of grandchildren, but
+ // we haven't finished sinking the item.
+
+ let c0 = node.leftChild()
+ if c0.offset >= count {
+ return // No more descendants to consider.
+ }
+ let min = _minDescendant(c0: c0, gc0: gc0)
+ guard self[min] < value else {
+ return // We're done.
+ }
+
+ initialize(node, to: extract(min))
+ node = min
+
+ if min < gc0 { return }
+
+ // If `min` was a grandchild, check the parent.
+ let parent = min.parent()
+ if self[parent] < value {
+ initialize(node, to: extract(parent))
+ node = parent
+ }
+ }
+
+ /// Returns the node holding the minimal item amongst the children &
+ /// grandchildren of a node in the tree. The parent node is not specified;
+ /// instead, this function takes the nodes corresponding to its first child
+ /// (`c0`) and first grandchild (`gc0`).
+ ///
+ /// There must be at least one child, but there must not be a full complement
+ /// of 4 grandchildren. (Other cases are handled directly above.)
+ ///
+ /// This method is an implementation detail of `trickleDownMin`. Do not call
+ /// it directly.
+ @inlinable
+ internal func _minDescendant(c0: _Node, gc0: _Node) -> _Node {
+ assert(c0.offset < count)
+ assert(gc0.offset + 3 >= count)
+
+ if gc0.offset < count {
+ if gc0.offset &+ 2 < count {
+ // We have three grandchildren. We don't need to compare direct children.
+ let gc1 = _Node(offset: gc0.offset &+ 1, level: gc0.level)
+ let gc2 = _Node(offset: gc0.offset &+ 2, level: gc0.level)
+ return minValue(minValue(gc0, gc1), gc2)
+ }
+
+ let c1 = _Node(offset: c0.offset &+ 1, level: c0.level)
+ let m = minValue(c1, gc0)
+ if gc0.offset &+ 1 < count {
+ // Two grandchildren.
+ let gc1 = _Node(offset: gc0.offset &+ 1, level: gc0.level)
+ return minValue(m, gc1)
+ }
+
+ // One grandchild.
+ return m
+ }
+
+ let c1 = _Node(offset: c0.offset &+ 1, level: c0.level)
+ if c1.offset < count {
+ return minValue(c0, c1)
+ }
+
+ return c0
+ }
+
+ /// Sink the item at `node` to its correct position in the heap.
+ /// The given node must be maximum-ordered.
+ @inlinable
+ internal func trickleDownMax(_ node: _Node) {
+ assert(!node.isMinLevel)
+ var node = node
+ var value = extract(node)
+
+ _trickleDownMax(node: &node, value: &value)
+ initialize(node, to: value)
+ }
+
+ @inlinable @inline(__always)
+ internal func _trickleDownMax(node: inout _Node, value: inout Element) {
+ // See note on `_Node` in `_trickleDownMin` above.
+
+ var gc0 = node.firstGrandchild()
+ while gc0.offset &+ 3 < count {
+ // Invariant: buffer slot at `node` is uninitialized
+
+ // We have four grandchildren, so we don't need to compare children.
+ let gc1 = _Node(offset: gc0.offset &+ 1, level: gc0.level)
+ let maxA = maxValue(gc0, gc1)
+
+ let gc2 = _Node(offset: gc0.offset &+ 2, level: gc0.level)
+ let gc3 = _Node(offset: gc0.offset &+ 3, level: gc0.level)
+ let maxB = maxValue(gc2, gc3)
+
+ let max = maxValue(maxA, maxB)
+ guard value < self[max] else {
+ return // We're done -- `node` is a good place for `value`.
+ }
+
+ initialize(node, to: extract(max))
+ node = max
+ gc0 = node.firstGrandchild()
+
+ let parent = max.parent()
+ if value < self[parent] {
+ swapAt(parent, with: &value)
+ }
+ }
+
+ // At this point, we don't have a full complement of grandchildren, but
+ // we haven't finished sinking the item.
+
+ let c0 = node.leftChild()
+ if c0.offset >= count {
+ return // No more descendants to consider.
+ }
+ let max = _maxDescendant(c0: c0, gc0: gc0)
+ guard value < self[max] else {
+ return // We're done.
+ }
+
+ initialize(node, to: extract(max))
+ node = max
+
+ if max < gc0 { return }
+
+ // If `max` was a grandchild, check the parent.
+ let parent = max.parent()
+ if value < self[parent] {
+ initialize(node, to: extract(parent))
+ node = parent
+ }
+ }
+
+ /// Returns the node holding the maximal item amongst the children &
+ /// grandchildren of a node in the tree. The parent node is not specified;
+ /// instead, this function takes the nodes corresponding to its first child
+ /// (`c0`) and first grandchild (`gc0`).
+ ///
+ /// There must be at least one child, but there must not be a full complement
+ /// of 4 grandchildren. (Other cases are handled directly above.)
+ ///
+ /// This method is an implementation detail of `trickleDownMax`. Do not call
+ /// it directly.
+ @inlinable
+ internal func _maxDescendant(c0: _Node, gc0: _Node) -> _Node {
+ assert(c0.offset < count)
+ assert(gc0.offset + 3 >= count)
+
+ if gc0.offset < count {
+ if gc0.offset &+ 2 < count {
+ // We have three grandchildren. We don't need to compare direct children.
+ let gc1 = _Node(offset: gc0.offset &+ 1, level: gc0.level)
+ let gc2 = _Node(offset: gc0.offset &+ 2, level: gc0.level)
+ return maxValue(maxValue(gc0, gc1), gc2)
+ }
+
+ let c1 = _Node(offset: c0.offset &+ 1, level: c0.level)
+ let m = maxValue(c1, gc0)
+ if gc0.offset &+ 1 < count {
+ // Two grandchildren.
+ let gc1 = _Node(offset: gc0.offset &+ 1, level: gc0.level)
+ return maxValue(m, gc1)
+ }
+
+ // One grandchild.
+ return m
+ }
+
+ let c1 = _Node(offset: c0.offset &+ 1, level: c0.level)
+ if c1.offset < count {
+ return maxValue(c0, c1)
+ }
+
+ return c0
+ }
+}
+
+extension Heap._UnsafeHandle {
+ @inlinable
+ internal func heapify() {
+ let limit = count / 2 // The first offset without a left child
+ var level = _Node.level(forOffset: limit &- 1)
+ while level >= 0 {
+ let nodes = _Node.allNodes(onLevel: level, limit: limit)
+ if _Node.isMinLevel(level) {
+ nodes?._forEach { node in
+ trickleDownMin(node)
+ }
+ } else {
+ nodes?._forEach { node in
+ trickleDownMax(node)
+ }
+ }
+ level &-= 1
+ }
+ }
+}
diff --git a/Sources/PriorityQueueModule/Heap.swift b/Sources/PriorityQueueModule/Heap.swift
index c04e90e4..1f6f3d83 100644
--- a/Sources/PriorityQueueModule/Heap.swift
+++ b/Sources/PriorityQueueModule/Heap.swift
@@ -9,28 +9,37 @@
//
//===----------------------------------------------------------------------===//
-import Swift
-
/// A [Min-Max Heap](https://en.wikipedia.org/wiki/Min-max_heap) data structure.
///
-/// In a min-max heap, each node at an even level in the tree is less than all
-/// its descendants, while each node at an odd level in the tree is greater than
-/// all of its descendants.
+/// In a min-max heap, each node at an even level in the tree is less than or
+/// equal to all its descendants, while each node at an odd level in the tree is
+/// greater than or equal to all of its descendants.
///
-/// The implementation is based off [Atkinson et al. Min-Max Heaps and
-/// Generalized Priority Queues (1986)](http://akira.ruc.dk/~keld/teaching/algoritmedesign_f03/Artikler/02/Atkinson86.pdf).
+/// The implementation is based on [Atkinson et al. 1986]:
///
-/// M.D. Atkinson, J.-R. Sack, N. Santoro, T. Strothotte. October 1986.
-/// Min-Max Heaps and Generalized Priority Queues. Communications of the ACM.
-/// 29(10):996-1000.
+/// [Atkinson et al. 1986]: https://doi.org/10.1145/6617.6621
+///
+/// M.D. Atkinson, J.-R. Sack, N. Santoro, T. Strothotte.
+/// "Min-Max Heaps and Generalized Priority Queues."
+/// *Communications of the ACM*, vol. 29, no. 10, Oct. 1986., pp. 996-1000,
+/// doi:[10.1145/6617.6621](https://doi.org/10.1145/6617.6621)
+@frozen
public struct Heap {
@usableFromInline
- internal var _storage: [Element]
+ internal var _storage: ContiguousArray
+ /// Creates an empty heap.
+ @inlinable
+ public init() {
+ _storage = []
+ }
+}
+
+extension Heap {
/// A Boolean value indicating whether or not the heap is empty.
///
/// - Complexity: O(1)
- @inlinable
+ @inlinable @inline(__always)
public var isEmpty: Bool {
_storage.isEmpty
}
@@ -38,7 +47,7 @@ public struct Heap {
/// The number of elements in the heap.
///
/// - Complexity: O(1)
- @inlinable
+ @inlinable @inline(__always)
public var count: Int {
_storage.count
}
@@ -52,13 +61,7 @@ public struct Heap {
/// - Complexity: O(1)
@inlinable
public var unordered: [Element] {
- _storage
- }
-
- /// Creates an empty heap.
- @inlinable
- public init() {
- _storage = []
+ Array(_storage)
}
/// Inserts the given element into the heap.
@@ -67,7 +70,10 @@ public struct Heap {
@inlinable
public mutating func insert(_ element: Element) {
_storage.append(element)
- _bubbleUp(elementAt: _storage.endIndex - 1)
+
+ _update { handle in
+ handle.bubbleUp(_Node(offset: handle.count - 1))
+ }
_checkInvariants()
}
@@ -84,17 +90,17 @@ public struct Heap {
/// - Complexity: O(1)
@inlinable
public func max() -> Element? {
- switch _storage.count {
- case 0, 1, 2:
- // If count is 0, `last` will return `nil`
- // If count is 1, the last (and only) item is the max
- // If count is 2, the last item is the max (as it's the only item in the
- // first max level)
- return _storage.last
- default:
+ _storage.withUnsafeBufferPointer { buffer in
+ guard buffer.count > 2 else {
+ // If count is 0, `last` will return `nil`
+ // If count is 1, the last (and only) item is the max
+ // If count is 2, the last item is the max (as it's the only item in the
+ // first max level)
+ return buffer.last
+ }
// We have at least 3 items -- return the larger of the two in the first
// max level
- return Swift.max(_storage[1], _storage[2])
+ return Swift.max(buffer[1], buffer[2])
}
}
@@ -103,8 +109,20 @@ public struct Heap {
/// - Complexity: O(log `count`)
@inlinable
public mutating func popMin() -> Element? {
- defer { _checkInvariants() }
- return _remove(at: 0)
+ guard _storage.count > 0 else { return nil }
+
+ var removed = _storage.removeLast()
+
+ if _storage.count > 0 {
+ _update { handle in
+ let minNode = _Node.root
+ handle.swapAt(minNode, with: &removed)
+ handle.trickleDownMin(minNode)
+ }
+ }
+
+ _checkInvariants()
+ return removed
}
/// Removes and returns the element with the highest priority, if available.
@@ -112,19 +130,24 @@ public struct Heap {
/// - Complexity: O(log `count`)
@inlinable
public mutating func popMax() -> Element? {
- defer { _checkInvariants() }
- switch _storage.count {
- case 0, 1, 2:
- // If count is 0, `popLast` will return `nil`
- // If count is 1, the last (and only) item is the max
- // If count is 2, the last item is the max (as it's the only item in the
- // first max level)
- return _storage.popLast()
- default:
- // The max item is the larger of the two items in the first max level
- let maxIdx = _storage[2] > _storage[1] ? 2 : 1
- return _remove(at: maxIdx)
+ guard _storage.count > 2 else { return _storage.popLast() }
+
+ var removed = _storage.removeLast()
+
+ _update { handle in
+ if handle.count == 2 {
+ if handle[.leftMax] > removed {
+ handle.swapAt(.leftMax, with: &removed)
+ }
+ } else {
+ let maxNode = handle.maxValue(.rightMax, .leftMax)
+ handle.swapAt(maxNode, with: &removed)
+ handle.trickleDownMax(maxNode)
+ }
}
+
+ _checkInvariants()
+ return removed
}
/// Removes and returns the element with the lowest priority.
@@ -146,358 +169,6 @@ public struct Heap {
public mutating func removeMax() -> Element {
return popMax()!
}
-
- // MARK: -
-
- @inline(__always)
- @inlinable
- internal mutating func _bubbleUp(elementAt index: Int) {
- guard let parentIdx = _parentIndex(of: index) else {
- // We're already at the root -- can't go any further
- return
- }
-
- // Figure out if `index` is on an even or odd level
- let levelIsMin = _minMaxHeapIsMinLevel(index)
-
- if levelIsMin {
- if _storage[index] > _storage[parentIdx] {
- _swapAt(index, parentIdx)
- _bubbleUpMax(elementAt: parentIdx)
- } else {
- _bubbleUpMin(elementAt: index)
- }
- } else {
- if _storage[index] < _storage[parentIdx] {
- _swapAt(index, parentIdx)
- _bubbleUpMin(elementAt: parentIdx)
- } else {
- _bubbleUpMax(elementAt: index)
- }
- }
- }
-
- @inline(__always)
- @inlinable
- internal mutating func _bubbleUpMin(elementAt index: Int) {
- var index = index
-
- while let grandparentIdx = _grandparentIndex(of: index),
- _storage[index] < _storage[grandparentIdx] {
- _swapAt(index, grandparentIdx)
- index = grandparentIdx
- }
- }
-
- @inline(__always)
- @inlinable
- internal mutating func _bubbleUpMax(elementAt index: Int) {
- var index = index
-
- while let grandparentIdx = _grandparentIndex(of: index),
- _storage[index] > _storage[grandparentIdx] {
- _swapAt(index, grandparentIdx)
- index = grandparentIdx
- }
- }
-
- // MARK: -
-
- @discardableResult
- @inlinable
- internal mutating func _remove(at index: Int) -> Element? {
- guard _storage.count > index else {
- return nil
- }
-
- var removed = _storage.removeLast()
-
- if index < _storage.count {
- swap(&removed, &_storage[index])
- _trickleDown(elementAt: index)
- }
-
- return removed
- }
-
- // MARK: -
-
- @inline(__always)
- @inlinable
- internal mutating func _trickleDown(elementAt index: Int) {
- // Figure out if `index` is on an even or odd level
- let levelIsMin = _minMaxHeapIsMinLevel(index)
-
- if levelIsMin {
- _trickleDownMin(elementAt: index)
- } else {
- _trickleDownMax(elementAt: index)
- }
- }
-
- @inline(__always)
- @inlinable
- internal mutating func _trickleDownMin(elementAt index: Int) {
- var index = index
-
- while let (smallestDescendantIdx, isChild) =
- _indexOfLowestPriorityChildOrGrandchild(of: index) {
- if _storage[smallestDescendantIdx] < _storage[index] {
- _swapAt(smallestDescendantIdx, index)
-
- if isChild {
- return
- }
-
- // Smallest is a grandchild
- let parentIdx = _parentIndex(of: smallestDescendantIdx)!
- if _storage[smallestDescendantIdx] > _storage[parentIdx] {
- _swapAt(smallestDescendantIdx, parentIdx)
- }
-
- index = smallestDescendantIdx
- } else {
- return
- }
- }
- }
-
- @inline(__always)
- @inlinable
- internal mutating func _trickleDownMax(elementAt index: Int) {
- var index = index
-
- while let (largestDescendantIdx, isChild) =
- _indexOfHighestPriorityChildOrGrandchild(of: index) {
- if _storage[largestDescendantIdx] > _storage[index] {
- _swapAt(largestDescendantIdx, index)
-
- if isChild {
- return
- }
-
- // Largest is a grandchild
- let parentIdx = _parentIndex(of: largestDescendantIdx)!
- if _storage[largestDescendantIdx] < _storage[parentIdx] {
- _swapAt(largestDescendantIdx, parentIdx)
- }
-
- index = largestDescendantIdx
- } else {
- return
- }
- }
- }
-
- /// Returns the lowest priority child or grandchild of the element at the
- /// given index.
- ///
- /// Returns `nil` if the element has no descendants.
- ///
- /// - parameter index: The index of the element whose descendants should be
- /// compared.
- @inline(__always)
- @inlinable
- internal func _indexOfLowestPriorityChildOrGrandchild(
- of index: Int
- ) -> (index: Int, isChild: Bool)? {
- guard let leftChildIdx = _leftChildIndex(of: index) else {
- return nil
- }
-
- var result: (index: Int, isChild: Bool) = (leftChildIdx, true)
-
- guard let rightChildIdx = _rightChildIndex(of: index) else {
- return result
- }
-
- guard let firstGrandchildIdx = _firstGrandchildIndex(of: index),
- let lastGrandchildIdx = _lastGrandchildIndex(of: index)
- else {
- // We have no grandchildren -- compare the two children instead
- if _storage[rightChildIdx] < _storage[leftChildIdx] {
- result.index = rightChildIdx
- }
-
- return result
- }
-
- // If we have 4 grandchildren, we can skip comparing the children as the
- // heap invariants will ensure that the grandchildren will be smaller.
- // Otherwise, we need to do the comparison.
- if lastGrandchildIdx != firstGrandchildIdx + 3 {
- // Compare the two children
- if _storage[rightChildIdx] < _storage[leftChildIdx] {
- result.index = rightChildIdx
- }
- }
-
- // Iterate through the grandchildren
- for i in firstGrandchildIdx...lastGrandchildIdx {
- if _storage[i] < _storage[result.index] {
- result.index = i
- result.isChild = false
- }
- }
-
- return result
- }
-
- /// Returns the highest priority child or grandchild of the element at the
- /// given index.
- ///
- /// Returns `nil` if the element has no descendants.
- ///
- /// - parameter index: The index of the item whose descendants should be
- /// compared.
- @inline(__always)
- @inlinable
- internal func _indexOfHighestPriorityChildOrGrandchild(
- of index: Int
- ) -> (index: Int, isChild: Bool)? {
- guard let leftChildIdx = _leftChildIndex(of: index) else {
- return nil
- }
-
- var result: (index: Int, isChild: Bool) = (leftChildIdx, true)
-
- guard let rightChildIdx = _rightChildIndex(of: index) else {
- return result
- }
-
- guard let firstGrandchildIdx = _firstGrandchildIndex(of: index),
- let lastGrandchildIdx = _lastGrandchildIndex(of: index)
- else {
- // We have no grandchildren -- compare the two children instead
- if _storage[rightChildIdx] > _storage[leftChildIdx] {
- result.index = rightChildIdx
- }
-
- return result
- }
-
- // If we have 4 grandchildren, we can skip comparing the children as the
- // heap invariants will ensure that the grandchildren will be larger.
- // Otherwise, we need to do the comparison.
- if lastGrandchildIdx != firstGrandchildIdx + 3 {
- // Compare the two children
- if _storage[rightChildIdx] > _storage[leftChildIdx] {
- result.index = rightChildIdx
- }
- }
-
- // Iterate through the grandchildren
- for i in firstGrandchildIdx...lastGrandchildIdx {
- if _storage[i] > _storage[result.index] {
- result.index = i
- result.isChild = false
- }
- }
-
- return result
- }
-
- // MARK: - Helpers
-
- /// Returns `true` if `index` falls on a min level in a min-max heap.
- ///
- /// - Precondition: `index` must be non-negative.
- @inline(__always)
- @inlinable
- internal func _minMaxHeapIsMinLevel(_ index: Int) -> Bool {
- precondition(index >= 0)
-
- return (index + 1)._binaryLogarithm() & 0b1 == 0
- }
-
- /// Swaps the elements in the heap at the given indices.
- @inline(__always)
- @inlinable
- internal mutating func _swapAt(_ i: Int, _ j: Int) {
- let tmp = _storage[i]
- _storage[i] = _storage[j]
- _storage[j] = tmp
- }
-
- /// Returns the parent index of the given `index`
- /// or `nil` if the index has no parent (i.e. `index == 0`).
- @inline(__always)
- @inlinable
- internal func _parentIndex(of index: Int) -> Int? {
- guard index > 0 else {
- return nil
- }
-
- return (index - 1) / 2
- }
-
- /// Returns the grandparent index of the given `index`
- /// or `nil` if the index has no grandparent.
- @inline(__always)
- @inlinable
- internal func _grandparentIndex(of index: Int) -> Int? {
- guard index > 2 else {
- return nil
- }
-
- return (index - 3) / 4
- }
-
- /// Returns the first child index of the given `index`
- /// or `nil` if the index has no children.
- @inline(__always)
- @inlinable
- internal func _leftChildIndex(of index: Int) -> Int? {
- let childIdx = index * 2 + 1
- guard childIdx < _storage.count else {
- return nil
- }
-
- return childIdx
- }
-
- /// Returns the right child index of the given `index`
- /// or `nil` if the index has no right child.
- @inline(__always)
- @inlinable
- internal func _rightChildIndex(of index: Int) -> Int? {
- let childIdx = index * 2 + 2
- guard childIdx < _storage.count else {
- return nil
- }
-
- return childIdx
- }
-
- /// Returns the first grandchild index of the given `index`
- /// or `nil` if the index has no grandchildren.
- @inline(__always)
- @inlinable
- internal func _firstGrandchildIndex(of index: Int) -> Int? {
- let grandchildIdx = index * 4 + 3
- guard grandchildIdx < _storage.count else {
- return nil
- }
-
- return grandchildIdx
- }
-
- /// Returns the last valid grandchild index of the given `index`
- /// or `nil` if the index has no grandchildren.
- ///
- /// In cases where the given index only has one grandchild, the index
- /// returned by this function is the same as that returned by
- /// `_firstGrandchildIndex`.
- @inline(__always)
- @inlinable
- internal func _lastGrandchildIndex(of index: Int) -> Int? {
- guard _firstGrandchildIndex(of: index) != nil else {
- // There are no grandchildren of the node at `index`
- return nil
- }
-
- return Swift.min(index * 4 + 6, _storage.count - 1)
- }
}
// MARK: -
@@ -505,17 +176,20 @@ public struct Heap {
extension Heap {
/// Initializes a heap from a sequence.
///
- /// Utilizes [Floyd's linear-time heap construction algorithm](https://en.wikipedia.org/wiki/Heapsort#Floyd's_heap_construction).
- ///
- /// - Complexity: O(n), where `n` is the length of `elements`.
+ /// - Complexity: O(*n*), where *n* is the length of `elements`.
@inlinable
public init(_ elements: S) where S.Element == Element {
- _storage = Array(elements)
+ // This is Floyd's linear-time heap construction algorithm.
+ // (https://en.wikipedia.org/wiki/Heapsort#Floyd's_heap_construction).
+ //
+ // FIXME: See if a more cache friendly algorithm would be faster.
- for idx in (0 ..< (_storage.count / 2)).reversed() {
- _trickleDown(elementAt: idx)
+ _storage = ContiguousArray(elements)
+ guard _storage.count > 1 else { return }
+
+ _update { handle in
+ handle.heapify()
}
-
_checkInvariants()
}
@@ -523,9 +197,16 @@ extension Heap {
///
/// - Parameter newElements: The new elements to insert into the heap.
///
- /// - Complexity: O(n * log `count`), where `n` is the length of `newElements`.
+ /// - Complexity: O(*n* * log(`count`)), where *n* is the length of `newElements`.
@inlinable
- public mutating func insert(contentsOf newElements: S) where S.Element == Element {
+ public mutating func insert(
+ contentsOf newElements: S
+ ) where S.Element == Element {
+ if count == 0 {
+ self = Self(newElements)
+ return
+ }
+ _storage.reserveCapacity(count + newElements.underestimatedCount)
for element in newElements {
insert(element)
}
diff --git a/Sources/PriorityQueueModule/_Node.swift b/Sources/PriorityQueueModule/_Node.swift
new file mode 100644
index 00000000..02927814
--- /dev/null
+++ b/Sources/PriorityQueueModule/_Node.swift
@@ -0,0 +1,174 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+@usableFromInline @frozen
+internal struct _Node {
+ @usableFromInline
+ internal var offset: Int
+
+ @usableFromInline
+ internal var level: Int
+
+ @inlinable
+ internal init(offset: Int, level: Int) {
+ assert(offset >= 0)
+#if COLLECTIONS_INTERNAL_CHECKS
+ assert(level == Self.level(forOffset: offset))
+#endif
+ self.offset = offset
+ self.level = level
+ }
+
+ @inlinable
+ internal init(offset: Int) {
+ self.init(offset: offset, level: Self.level(forOffset: offset))
+ }
+}
+
+extension _Node: Comparable {
+ @inlinable @inline(__always)
+ internal static func ==(left: Self, right: Self) -> Bool {
+ left.offset == right.offset
+ }
+
+ @inlinable @inline(__always)
+ internal static func <(left: Self, right: Self) -> Bool {
+ left.offset < right.offset
+ }
+}
+
+extension _Node: CustomStringConvertible {
+ @usableFromInline
+ internal var description: String {
+ "(offset: \(offset), level: \(level))"
+ }
+}
+
+extension _Node {
+ @inlinable @inline(__always)
+ internal static func level(forOffset offset: Int) -> Int {
+ (offset &+ 1)._binaryLogarithm()
+ }
+
+ @inlinable @inline(__always)
+ internal static func firstNode(onLevel level: Int) -> _Node {
+ assert(level >= 0)
+ return _Node(offset: (1 &<< level) &- 1, level: level)
+ }
+
+ @inlinable @inline(__always)
+ internal static func lastNode(onLevel level: Int) -> _Node {
+ assert(level >= 0)
+ return _Node(offset: (1 &<< (level &+ 1)) &- 2, level: level)
+ }
+
+ @inlinable @inline(__always)
+ internal static func isMinLevel(_ level: Int) -> Bool {
+ level & 0b1 == 0
+ }
+}
+
+extension _Node {
+ /// The root node in the heap.
+ @inlinable @inline(__always)
+ internal static var root: Self {
+ Self.init(offset: 0, level: 0)
+ }
+
+ /// The first max node in the heap. (I.e., the left child of the root.)
+ @inlinable @inline(__always)
+ internal static var leftMax: Self {
+ Self.init(offset: 1, level: 1)
+ }
+
+ /// The second max node in the heap. (I.e., the right child of the root.)
+ @inlinable @inline(__always)
+ internal static var rightMax: Self {
+ Self.init(offset: 2, level: 1)
+ }
+
+ @inlinable @inline(__always)
+ internal var isMinLevel: Bool {
+ Self.isMinLevel(level)
+ }
+
+ @inlinable @inline(__always)
+ internal var isRoot: Bool {
+ offset == 0
+ }
+}
+
+extension _Node {
+ /// Returns the parent of this index, or `nil` if the index has no parent
+ /// (i.e. when this is the root index).
+ @inlinable @inline(__always)
+ internal func parent() -> Self {
+ assert(!isRoot)
+ return Self(offset: (offset &- 1) / 2, level: level &- 1)
+ }
+
+ /// Returns the grandparent of this index, or `nil` if the index has
+ /// no grandparent.
+ @inlinable @inline(__always)
+ internal func grandParent() -> Self? {
+ guard offset > 2 else { return nil }
+ return Self(offset: (offset &- 3) / 4, level: level &- 2)
+ }
+
+ /// Returns the left child of this node.
+ @inlinable @inline(__always)
+ internal func leftChild() -> Self {
+ Self(offset: offset &* 2 &+ 1, level: level &+ 1)
+ }
+
+ /// Returns the right child of this node.
+ @inlinable @inline(__always)
+ internal func rightChild() -> Self {
+ Self(offset: offset &* 2 &+ 2, level: level &+ 1)
+ }
+
+ @inlinable @inline(__always)
+ internal func firstGrandchild() -> Self {
+ Self(offset: offset &* 4 &+ 3, level: level &+ 2)
+ }
+
+ @inlinable @inline(__always)
+ internal func lastGrandchild() -> Self {
+ Self(offset: offset &* 4 &+ 6, level: level &+ 2)
+ }
+
+ @inlinable
+ internal static func allNodes(
+ onLevel level: Int,
+ limit: Int
+ ) -> ClosedRange? {
+ let first = Self.firstNode(onLevel: level)
+ guard first.offset < limit else { return nil }
+ var last = self.lastNode(onLevel: level)
+ if last.offset >= limit {
+ last = _Node(offset: limit &- 1, level: level)
+ }
+ return ClosedRange(uncheckedBounds: (first, last))
+ }
+}
+
+extension ClosedRange where Bound == _Node {
+ @inlinable @inline(__always)
+ internal func _forEach(_ body: (_Node) -> Void) {
+ assert(
+ isEmpty || _Node.level(forOffset: upperBound.offset) == lowerBound.level)
+ var node = self.lowerBound
+ while node.offset <= self.upperBound.offset {
+ body(node)
+ node.offset &+= 1
+ }
+ }
+}
diff --git a/Sources/CollectionsTestSupport/AssertionContexts/Assertions.swift b/Sources/_CollectionsTestSupport/AssertionContexts/Assertions.swift
similarity index 96%
rename from Sources/CollectionsTestSupport/AssertionContexts/Assertions.swift
rename to Sources/_CollectionsTestSupport/AssertionContexts/Assertions.swift
index 2172b920..ff2e6e4f 100644
--- a/Sources/CollectionsTestSupport/AssertionContexts/Assertions.swift
+++ b/Sources/_CollectionsTestSupport/AssertionContexts/Assertions.swift
@@ -188,6 +188,20 @@ public func expectEqual(
message, trapping: trapping, file: file, line: line)
}
+public func expectEqual(
+ _ left: (key: Key, value: Value), _ right: (key: Key, value: Value),
+ _ message: @autoclosure () -> String = "",
+ trapping: Bool = false,
+ file: StaticString = #file,
+ line: UInt = #line
+) {
+ if left == right { return }
+ _expectFailure(
+ "'\(left)' is not equal to '\(right)'",
+ message, trapping: trapping, file: file, line: line)
+}
+
+
public func expectEqual(
_ left: T?, _ right: T?,
_ message: @autoclosure () -> String = "",
diff --git a/Sources/CollectionsTestSupport/AssertionContexts/CollectionTestCase.swift b/Sources/_CollectionsTestSupport/AssertionContexts/CollectionTestCase.swift
similarity index 100%
rename from Sources/CollectionsTestSupport/AssertionContexts/CollectionTestCase.swift
rename to Sources/_CollectionsTestSupport/AssertionContexts/CollectionTestCase.swift
diff --git a/Sources/CollectionsTestSupport/AssertionContexts/Combinatorics.swift b/Sources/_CollectionsTestSupport/AssertionContexts/Combinatorics.swift
similarity index 94%
rename from Sources/CollectionsTestSupport/AssertionContexts/Combinatorics.swift
rename to Sources/_CollectionsTestSupport/AssertionContexts/Combinatorics.swift
index 9da7afc6..1c3aa0a7 100644
--- a/Sources/CollectionsTestSupport/AssertionContexts/Combinatorics.swift
+++ b/Sources/_CollectionsTestSupport/AssertionContexts/Combinatorics.swift
@@ -132,10 +132,12 @@ public func withSomeRanges(
/// - Parameters:
/// - `enabled`: if `false`, then no copies are made -- the values are passed to `body` with no processing.
/// - `value`: The collection value that is being tested.
+/// - `checker`: An optional function that is used to check the consistency of the hidden copy.
/// - `body`: A closure performing a mutation on `value`.
public func withHiddenCopies(
if enabled: Bool,
of value: inout S,
+ checker: (S) -> Void = { _ in },
file: StaticString = #file, line: UInt = #line,
_ body: (inout S) throws -> R
) rethrows -> R where S.Element: Equatable {
@@ -144,6 +146,7 @@ public func withHiddenCopies(
let expected = Array(value)
let result = try body(&value)
expectEqualElements(copy, expected, file: file, line: line)
+ checker(copy)
return result
}
@@ -156,6 +159,7 @@ public func withHiddenCopies(
/// - Parameters:
/// - `enabled`: if `false`, then no copies are made -- the values are passed to `body` with no processing.
/// - `value`: The collection value that is being tested.
+/// - `checker`: An optional function that is used to check the consistency of the hidden copy.
/// - `body`: A closure performing a mutation on `value`.
public func withHiddenCopies<
S: Sequence,
@@ -165,6 +169,7 @@ public func withHiddenCopies<
>(
if enabled: Bool,
of value: inout S,
+ checker: (S) -> Void = { _ in },
file: StaticString = #file, line: UInt = #line,
_ body: (inout S) throws -> R
) rethrows -> R where S.Element == (key: Key, value: Value) {
@@ -173,5 +178,6 @@ public func withHiddenCopies<
let expected = Array(value)
let result = try body(&value)
expectEqualElements(copy, expected, file: file, line: line)
+ checker(copy)
return result
}
diff --git a/Sources/CollectionsTestSupport/AssertionContexts/TestContext.swift b/Sources/_CollectionsTestSupport/AssertionContexts/TestContext.swift
similarity index 100%
rename from Sources/CollectionsTestSupport/AssertionContexts/TestContext.swift
rename to Sources/_CollectionsTestSupport/AssertionContexts/TestContext.swift
diff --git a/Sources/CollectionsTestSupport/ConformanceCheckers/CheckBidirectionalCollection.swift b/Sources/_CollectionsTestSupport/ConformanceCheckers/CheckBidirectionalCollection.swift
similarity index 100%
rename from Sources/CollectionsTestSupport/ConformanceCheckers/CheckBidirectionalCollection.swift
rename to Sources/_CollectionsTestSupport/ConformanceCheckers/CheckBidirectionalCollection.swift
diff --git a/Sources/CollectionsTestSupport/ConformanceCheckers/CheckCollection.swift b/Sources/_CollectionsTestSupport/ConformanceCheckers/CheckCollection.swift
similarity index 100%
rename from Sources/CollectionsTestSupport/ConformanceCheckers/CheckCollection.swift
rename to Sources/_CollectionsTestSupport/ConformanceCheckers/CheckCollection.swift
diff --git a/Sources/CollectionsTestSupport/ConformanceCheckers/CheckComparable.swift b/Sources/_CollectionsTestSupport/ConformanceCheckers/CheckComparable.swift
similarity index 100%
rename from Sources/CollectionsTestSupport/ConformanceCheckers/CheckComparable.swift
rename to Sources/_CollectionsTestSupport/ConformanceCheckers/CheckComparable.swift
diff --git a/Sources/CollectionsTestSupport/ConformanceCheckers/CheckEquatable.swift b/Sources/_CollectionsTestSupport/ConformanceCheckers/CheckEquatable.swift
similarity index 100%
rename from Sources/CollectionsTestSupport/ConformanceCheckers/CheckEquatable.swift
rename to Sources/_CollectionsTestSupport/ConformanceCheckers/CheckEquatable.swift
diff --git a/Sources/CollectionsTestSupport/ConformanceCheckers/CheckHashable.swift b/Sources/_CollectionsTestSupport/ConformanceCheckers/CheckHashable.swift
similarity index 100%
rename from Sources/CollectionsTestSupport/ConformanceCheckers/CheckHashable.swift
rename to Sources/_CollectionsTestSupport/ConformanceCheckers/CheckHashable.swift
diff --git a/Sources/CollectionsTestSupport/ConformanceCheckers/CheckSequence.swift b/Sources/_CollectionsTestSupport/ConformanceCheckers/CheckSequence.swift
similarity index 100%
rename from Sources/CollectionsTestSupport/ConformanceCheckers/CheckSequence.swift
rename to Sources/_CollectionsTestSupport/ConformanceCheckers/CheckSequence.swift
diff --git a/Sources/CollectionsTestSupport/MinimalTypes/MinimalBidirectionalCollection.swift b/Sources/_CollectionsTestSupport/MinimalTypes/MinimalBidirectionalCollection.swift
similarity index 100%
rename from Sources/CollectionsTestSupport/MinimalTypes/MinimalBidirectionalCollection.swift
rename to Sources/_CollectionsTestSupport/MinimalTypes/MinimalBidirectionalCollection.swift
diff --git a/Sources/CollectionsTestSupport/MinimalTypes/MinimalCollection.swift b/Sources/_CollectionsTestSupport/MinimalTypes/MinimalCollection.swift
similarity index 100%
rename from Sources/CollectionsTestSupport/MinimalTypes/MinimalCollection.swift
rename to Sources/_CollectionsTestSupport/MinimalTypes/MinimalCollection.swift
diff --git a/Sources/CollectionsTestSupport/MinimalTypes/MinimalDecoder.swift b/Sources/_CollectionsTestSupport/MinimalTypes/MinimalDecoder.swift
similarity index 100%
rename from Sources/CollectionsTestSupport/MinimalTypes/MinimalDecoder.swift
rename to Sources/_CollectionsTestSupport/MinimalTypes/MinimalDecoder.swift
diff --git a/Sources/CollectionsTestSupport/MinimalTypes/MinimalEncoder.swift b/Sources/_CollectionsTestSupport/MinimalTypes/MinimalEncoder.swift
similarity index 100%
rename from Sources/CollectionsTestSupport/MinimalTypes/MinimalEncoder.swift
rename to Sources/_CollectionsTestSupport/MinimalTypes/MinimalEncoder.swift
diff --git a/Sources/CollectionsTestSupport/MinimalTypes/MinimalIndex.swift b/Sources/_CollectionsTestSupport/MinimalTypes/MinimalIndex.swift
similarity index 100%
rename from Sources/CollectionsTestSupport/MinimalTypes/MinimalIndex.swift
rename to Sources/_CollectionsTestSupport/MinimalTypes/MinimalIndex.swift
diff --git a/Sources/CollectionsTestSupport/MinimalTypes/MinimalIterator.swift b/Sources/_CollectionsTestSupport/MinimalTypes/MinimalIterator.swift
similarity index 100%
rename from Sources/CollectionsTestSupport/MinimalTypes/MinimalIterator.swift
rename to Sources/_CollectionsTestSupport/MinimalTypes/MinimalIterator.swift
diff --git a/Sources/CollectionsTestSupport/MinimalTypes/MinimalMutableRandomAccessCollection.swift b/Sources/_CollectionsTestSupport/MinimalTypes/MinimalMutableRandomAccessCollection.swift
similarity index 100%
rename from Sources/CollectionsTestSupport/MinimalTypes/MinimalMutableRandomAccessCollection.swift
rename to Sources/_CollectionsTestSupport/MinimalTypes/MinimalMutableRandomAccessCollection.swift
diff --git a/Sources/CollectionsTestSupport/MinimalTypes/MinimalMutableRangeReplaceableRandomAccessCollection.swift b/Sources/_CollectionsTestSupport/MinimalTypes/MinimalMutableRangeReplaceableRandomAccessCollection.swift
similarity index 100%
rename from Sources/CollectionsTestSupport/MinimalTypes/MinimalMutableRangeReplaceableRandomAccessCollection.swift
rename to Sources/_CollectionsTestSupport/MinimalTypes/MinimalMutableRangeReplaceableRandomAccessCollection.swift
diff --git a/Sources/CollectionsTestSupport/MinimalTypes/MinimalRandomAccessCollection.swift b/Sources/_CollectionsTestSupport/MinimalTypes/MinimalRandomAccessCollection.swift
similarity index 100%
rename from Sources/CollectionsTestSupport/MinimalTypes/MinimalRandomAccessCollection.swift
rename to Sources/_CollectionsTestSupport/MinimalTypes/MinimalRandomAccessCollection.swift
diff --git a/Sources/CollectionsTestSupport/MinimalTypes/MinimalRangeReplaceableRandomAccessCollection.swift b/Sources/_CollectionsTestSupport/MinimalTypes/MinimalRangeReplaceableRandomAccessCollection.swift
similarity index 100%
rename from Sources/CollectionsTestSupport/MinimalTypes/MinimalRangeReplaceableRandomAccessCollection.swift
rename to Sources/_CollectionsTestSupport/MinimalTypes/MinimalRangeReplaceableRandomAccessCollection.swift
diff --git a/Sources/CollectionsTestSupport/MinimalTypes/MinimalSequence.swift b/Sources/_CollectionsTestSupport/MinimalTypes/MinimalSequence.swift
similarity index 100%
rename from Sources/CollectionsTestSupport/MinimalTypes/MinimalSequence.swift
rename to Sources/_CollectionsTestSupport/MinimalTypes/MinimalSequence.swift
diff --git a/Sources/CollectionsTestSupport/MinimalTypes/ResettableValue.swift b/Sources/_CollectionsTestSupport/MinimalTypes/ResettableValue.swift
similarity index 100%
rename from Sources/CollectionsTestSupport/MinimalTypes/ResettableValue.swift
rename to Sources/_CollectionsTestSupport/MinimalTypes/ResettableValue.swift
diff --git a/Sources/CollectionsTestSupport/MinimalTypes/StringConvertibleValue.swift b/Sources/_CollectionsTestSupport/MinimalTypes/StringConvertibleValue.swift
similarity index 100%
rename from Sources/CollectionsTestSupport/MinimalTypes/StringConvertibleValue.swift
rename to Sources/_CollectionsTestSupport/MinimalTypes/StringConvertibleValue.swift
diff --git a/Sources/CollectionsTestSupport/MinimalTypes/_CollectionState.swift b/Sources/_CollectionsTestSupport/MinimalTypes/_CollectionState.swift
similarity index 100%
rename from Sources/CollectionsTestSupport/MinimalTypes/_CollectionState.swift
rename to Sources/_CollectionsTestSupport/MinimalTypes/_CollectionState.swift
diff --git a/Sources/CollectionsTestSupport/MinimalTypes/_MinimalCollectionCore.swift b/Sources/_CollectionsTestSupport/MinimalTypes/_MinimalCollectionCore.swift
similarity index 100%
rename from Sources/CollectionsTestSupport/MinimalTypes/_MinimalCollectionCore.swift
rename to Sources/_CollectionsTestSupport/MinimalTypes/_MinimalCollectionCore.swift
diff --git a/Sources/CollectionsTestSupport/Utilities/Box.swift b/Sources/_CollectionsTestSupport/Utilities/Box.swift
similarity index 100%
rename from Sources/CollectionsTestSupport/Utilities/Box.swift
rename to Sources/_CollectionsTestSupport/Utilities/Box.swift
diff --git a/Sources/CollectionsTestSupport/Utilities/HashableBox.swift b/Sources/_CollectionsTestSupport/Utilities/HashableBox.swift
similarity index 100%
rename from Sources/CollectionsTestSupport/Utilities/HashableBox.swift
rename to Sources/_CollectionsTestSupport/Utilities/HashableBox.swift
diff --git a/Sources/CollectionsTestSupport/Utilities/LifetimeTracked.swift b/Sources/_CollectionsTestSupport/Utilities/LifetimeTracked.swift
similarity index 100%
rename from Sources/CollectionsTestSupport/Utilities/LifetimeTracked.swift
rename to Sources/_CollectionsTestSupport/Utilities/LifetimeTracked.swift
diff --git a/Sources/CollectionsTestSupport/Utilities/LifetimeTracker.swift b/Sources/_CollectionsTestSupport/Utilities/LifetimeTracker.swift
similarity index 100%
rename from Sources/CollectionsTestSupport/Utilities/LifetimeTracker.swift
rename to Sources/_CollectionsTestSupport/Utilities/LifetimeTracker.swift
diff --git a/Sources/CollectionsTestSupport/Utilities/SeedableRandomNumberGenerator.swift b/Sources/_CollectionsTestSupport/Utilities/SeedableRandomNumberGenerator.swift
similarity index 100%
rename from Sources/CollectionsTestSupport/Utilities/SeedableRandomNumberGenerator.swift
rename to Sources/_CollectionsTestSupport/Utilities/SeedableRandomNumberGenerator.swift
diff --git a/Tests/CollectionsTestSupportTests/MinimalTypeConformances.swift b/Tests/CollectionsTestSupportTests/MinimalTypeConformances.swift
index b9a80bf5..21e8534c 100644
--- a/Tests/CollectionsTestSupportTests/MinimalTypeConformances.swift
+++ b/Tests/CollectionsTestSupportTests/MinimalTypeConformances.swift
@@ -10,7 +10,7 @@
//===----------------------------------------------------------------------===//
import XCTest
-import CollectionsTestSupport
+import _CollectionsTestSupport
final class DequeTests: CollectionTestCase {
func testMinimalSequence() {
diff --git a/Tests/DequeTests/DequeInternals.swift b/Tests/DequeTests/DequeInternals.swift
index 67ab3c8d..1f4e165e 100644
--- a/Tests/DequeTests/DequeInternals.swift
+++ b/Tests/DequeTests/DequeInternals.swift
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
-import CollectionsTestSupport
+import _CollectionsTestSupport
@_spi(Testing) import DequeModule
internal struct DequeLayout: CustomStringConvertible {
diff --git a/Tests/DequeTests/DequeTests.swift b/Tests/DequeTests/DequeTests.swift
index e0e36de5..22227a6f 100644
--- a/Tests/DequeTests/DequeTests.swift
+++ b/Tests/DequeTests/DequeTests.swift
@@ -10,7 +10,7 @@
//===----------------------------------------------------------------------===//
import XCTest
-import CollectionsTestSupport
+import _CollectionsTestSupport
@_spi(Testing) import DequeModule
final class DequeTests: CollectionTestCase {
diff --git a/Tests/DequeTests/MutableCollectionTests.swift b/Tests/DequeTests/MutableCollectionTests.swift
index 992bda15..1d5ea85d 100644
--- a/Tests/DequeTests/MutableCollectionTests.swift
+++ b/Tests/DequeTests/MutableCollectionTests.swift
@@ -10,7 +10,7 @@
//===----------------------------------------------------------------------===//
import XCTest
-import CollectionsTestSupport
+import _CollectionsTestSupport
@_spi(Testing) import DequeModule
final class MutableCollectiontests: CollectionTestCase {
diff --git a/Tests/DequeTests/RangeReplaceableCollectionTests.swift b/Tests/DequeTests/RangeReplaceableCollectionTests.swift
index ebee6aff..e6271019 100644
--- a/Tests/DequeTests/RangeReplaceableCollectionTests.swift
+++ b/Tests/DequeTests/RangeReplaceableCollectionTests.swift
@@ -10,7 +10,7 @@
//===----------------------------------------------------------------------===//
import XCTest
-import CollectionsTestSupport
+import _CollectionsTestSupport
@_spi(Testing) import DequeModule
/// Exhaustive tests for `Deque`'s implementations for `RangeReplaceableCollection`
diff --git a/Tests/OrderedCollectionsTests/HashTable/BitsetTests.swift b/Tests/OrderedCollectionsTests/HashTable/BitsetTests.swift
index 20a48fbd..9c0da263 100644
--- a/Tests/OrderedCollectionsTests/HashTable/BitsetTests.swift
+++ b/Tests/OrderedCollectionsTests/HashTable/BitsetTests.swift
@@ -11,7 +11,7 @@
#if DEBUG // These unit tests need access to OrderedSet internals
import XCTest
-import CollectionsTestSupport
+import _CollectionsTestSupport
@_spi(Testing) @testable import OrderedCollections
class BitsetTests: CollectionTestCase {
diff --git a/Tests/OrderedCollectionsTests/HashTable/HashTableTests.swift b/Tests/OrderedCollectionsTests/HashTable/HashTableTests.swift
index 213d9bd0..e3289a5b 100644
--- a/Tests/OrderedCollectionsTests/HashTable/HashTableTests.swift
+++ b/Tests/OrderedCollectionsTests/HashTable/HashTableTests.swift
@@ -11,7 +11,7 @@
#if DEBUG // These unit tests need access to OrderedSet internals
import XCTest
-import CollectionsTestSupport
+import _CollectionsTestSupport
@_spi(Testing) @testable import OrderedCollections
class HashTableTests: CollectionTestCase {
diff --git a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift
index c940cdd6..0e46b9c0 100644
--- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift
+++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift
@@ -12,7 +12,7 @@
import XCTest
@_spi(Testing) import OrderedCollections
-import CollectionsTestSupport
+import _CollectionsTestSupport
class OrderedDictionaryTests: CollectionTestCase {
func test_empty() {
@@ -192,7 +192,7 @@ class OrderedDictionaryTests: CollectionTestCase {
func test_counts() {
withEvery("count", in: 0 ..< 30) { count in
withLifetimeTracking { tracker in
- let (d, _, _) = tracker.orderedDictionary(keys: 0 ..< count)
+ let (d, _) = tracker.orderedDictionary(keys: 0 ..< count)
expectEqual(d.isEmpty, count == 0)
expectEqual(d.count, count)
expectEqual(d.underestimatedCount, count)
@@ -203,9 +203,9 @@ class OrderedDictionaryTests: CollectionTestCase {
func test_index_forKey() {
withEvery("count", in: 0 ..< 30) { count in
withLifetimeTracking { tracker in
- let (d, keys, _) = tracker.orderedDictionary(keys: 0 ..< count)
+ let (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
withEvery("offset", in: 0 ..< count) { offset in
- expectEqual(d.index(forKey: keys[offset]), offset)
+ expectEqual(d.index(forKey: reference[offset].key), offset)
}
expectNil(d.index(forKey: tracker.instance(for: -1)))
expectNil(d.index(forKey: tracker.instance(for: count)))
@@ -213,25 +213,12 @@ class OrderedDictionaryTests: CollectionTestCase {
}
}
- func test_subscript_offset() {
- withEvery("count", in: 0 ..< 30) { count in
- withLifetimeTracking { tracker in
- let (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< count)
- withEvery("offset", in: 0 ..< count) { offset in
- let item = d[offset: offset]
- expectEqual(item.key, keys[offset])
- expectEqual(item.value, values[offset])
- }
- }
- }
- }
-
func test_subscript_getter() {
withEvery("count", in: 0 ..< 30) { count in
withLifetimeTracking { tracker in
- let (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< count)
+ let (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
withEvery("offset", in: 0 ..< count) { offset in
- expectEqual(d[keys[offset]], values[offset])
+ expectEqual(d[reference[offset].key], reference[offset].value)
}
expectNil(d[tracker.instance(for: -1)])
expectNil(d[tracker.instance(for: count)])
@@ -244,16 +231,12 @@ class OrderedDictionaryTests: CollectionTestCase {
withEvery("offset", in: 0 ..< count) { offset in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- var (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< count)
+ var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
let replacement = tracker.instance(for: -1)
- withHiddenCopies(if: isShared, of: &d) { d in
- d[keys[offset]] = replacement
- values[offset] = replacement
- withEvery("i", in: 0 ..< count) { i in
- let (k, v) = d[offset: i]
- expectEqual(k, keys[i])
- expectEqual(v, values[i])
- }
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
+ d[reference[offset].key] = replacement
+ reference[offset].value = replacement
+ expectEqualElements(d, reference)
}
}
}
@@ -266,16 +249,11 @@ class OrderedDictionaryTests: CollectionTestCase {
withEvery("offset", in: 0 ..< count) { offset in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- var (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< count)
- withHiddenCopies(if: isShared, of: &d) { d in
- d[keys[offset]] = nil
- keys.remove(at: offset)
- values.remove(at: offset)
- withEvery("i", in: 0 ..< count - 1) { i in
- let (k, v) = d[offset: i]
- expectEqual(k, keys[i])
- expectEqual(v, values[i])
- }
+ var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
+ d[reference[offset].key] = nil
+ reference.remove(at: offset)
+ expectEqualElements(d, reference)
}
}
}
@@ -289,15 +267,12 @@ class OrderedDictionaryTests: CollectionTestCase {
withLifetimeTracking { tracker in
let keys = tracker.instances(for: 0 ..< count)
let values = tracker.instances(for: (0 ..< count).map { 100 + $0 })
+ let reference = zip(keys, values).map { (key: $0.0, value: $0.1) }
var d: OrderedDictionary, LifetimeTracked> = [:]
withEvery("offset", in: 0 ..< count) { offset in
- withHiddenCopies(if: isShared, of: &d) { d in
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
d[keys[offset]] = values[offset]
- withEvery("i", in: 0 ... offset) { i in
- let (k, v) = d[offset: i]
- expectEqual(k, keys[i])
- expectEqual(v, values[i])
- }
+ expectEqualElements(d, reference.prefix(offset + 1))
}
}
}
@@ -309,16 +284,12 @@ class OrderedDictionaryTests: CollectionTestCase {
withEvery("count", in: 0 ..< 30) { count in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- var (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< count)
+ var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
let key = tracker.instance(for: -1)
- withHiddenCopies(if: isShared, of: &d) { d in
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
d[key] = nil
}
- withEvery("i", in: 0 ..< count) { i in
- let (k, v) = d[offset: i]
- expectEqual(k, keys[i])
- expectEqual(v, values[i])
- }
+ expectEqualElements(d, reference)
}
}
}
@@ -336,16 +307,12 @@ class OrderedDictionaryTests: CollectionTestCase {
withEvery("offset", in: 0 ..< count) { offset in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- var (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< count)
+ var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
let replacement = tracker.instance(for: -1)
- withHiddenCopies(if: isShared, of: &d) { d in
- mutate(&d[keys[offset]]) { $0 = replacement }
- values[offset] = replacement
- withEvery("i", in: 0 ..< count) { i in
- let (k, v) = d[offset: i]
- expectEqual(k, keys[i])
- expectEqual(v, values[i])
- }
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
+ mutate(&d[reference[offset].key]) { $0 = replacement }
+ reference[offset].value = replacement
+ expectEqualElements(d, reference)
}
}
}
@@ -358,20 +325,14 @@ class OrderedDictionaryTests: CollectionTestCase {
withEvery("offset", in: 0 ..< count) { offset in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- var (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< count)
- withHiddenCopies(if: isShared, of: &d) { d in
- let key = keys[offset]
+ var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
+ let key = reference[offset].key
mutate(&d[key]) { v in
- expectEqual(v, values[offset])
+ expectEqual(v, reference[offset].value)
v = nil
}
- keys.remove(at: offset)
- values.remove(at: offset)
- withEvery("i", in: 0 ..< count - 1) { i in
- let (k, v) = d[offset: i]
- expectEqual(k, keys[i])
- expectEqual(v, values[i])
- }
+ reference.remove(at: offset)
}
}
}
@@ -385,19 +346,16 @@ class OrderedDictionaryTests: CollectionTestCase {
withLifetimeTracking { tracker in
let keys = tracker.instances(for: 0 ..< count)
let values = tracker.instances(for: (0 ..< count).map { 100 + $0 })
+ let reference = zip(keys, values).map { (key: $0.0, value: $0.1) }
var d: OrderedDictionary, LifetimeTracked> = [:]
withEvery("offset", in: 0 ..< count) { offset in
- withHiddenCopies(if: isShared, of: &d) { d in
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
mutate(&d[keys[offset]]) { v in
expectNil(v)
v = values[offset]
}
expectEqual(d.count, offset + 1)
- withEvery("i", in: 0 ... offset) { i in
- let (k, v) = d[offset: i]
- expectEqual(k, keys[i])
- expectEqual(v, values[i])
- }
+ expectEqualElements(d, reference.prefix(offset + 1))
}
}
}
@@ -409,19 +367,15 @@ class OrderedDictionaryTests: CollectionTestCase {
withEvery("count", in: 0 ..< 30) { count in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- var (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< count)
+ var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
let key = tracker.instance(for: -1)
- withHiddenCopies(if: isShared, of: &d) { d in
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
mutate(&d[key]) { v in
expectNil(v)
v = nil
}
}
- withEvery("i", in: 0 ..< count) { i in
- let (k, v) = d[offset: i]
- expectEqual(k, keys[i])
- expectEqual(v, values[i])
- }
+ expectEqualElements(d, reference)
}
}
}
@@ -431,11 +385,11 @@ class OrderedDictionaryTests: CollectionTestCase {
withEvery("count", in: 0 ..< 30) { count in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- let (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< count)
+ let (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
let fallback = tracker.instance(for: -1)
withEvery("offset", in: 0 ..< count) { offset in
- let key = keys[offset]
- expectEqual(d[key, default: fallback], values[offset])
+ let key = reference[offset].key
+ expectEqual(d[key, default: fallback], reference[offset].value)
}
expectEqual(
d[tracker.instance(for: -1), default: fallback],
@@ -453,21 +407,17 @@ class OrderedDictionaryTests: CollectionTestCase {
withEvery("offset", in: 0 ..< count) { offset in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- var (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< count)
+ var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
let replacement = tracker.instance(for: -1)
let fallback = tracker.instance(for: -1)
- withHiddenCopies(if: isShared, of: &d) { d in
- let key = keys[offset]
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
+ let key = reference[offset].key
mutate(&d[key, default: fallback]) { v in
- expectEqual(v, values[offset])
+ expectEqual(v, reference[offset].value)
v = replacement
}
- values[offset] = replacement
- withEvery("i", in: 0 ..< count) { i in
- let (k, v) = d[offset: i]
- expectEqual(k, keys[i])
- expectEqual(v, values[i])
- }
+ reference[offset].value = replacement
+ expectEqualElements(d, reference)
}
}
}
@@ -481,21 +431,18 @@ class OrderedDictionaryTests: CollectionTestCase {
withLifetimeTracking { tracker in
let keys = tracker.instances(for: 0 ..< count)
let values = tracker.instances(for: (0 ..< count).map { 100 + $0 })
+ let reference = zip(keys, values).map { (key: $0.0, value: $0.1) }
var d: OrderedDictionary, LifetimeTracked> = [:]
let fallback = tracker.instance(for: -1)
withEvery("offset", in: 0 ..< count) { offset in
- withHiddenCopies(if: isShared, of: &d) { d in
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
let key = keys[offset]
mutate(&d[key, default: fallback]) { v in
expectEqual(v, fallback)
v = values[offset]
}
expectEqual(d.count, offset + 1)
- withEvery("i", in: 0 ... offset) { i in
- let (k, v) = d[offset: i]
- expectEqual(k, keys[i])
- expectEqual(v, values[i])
- }
+ expectEqualElements(d, reference.prefix(offset + 1))
}
}
}
@@ -508,18 +455,14 @@ class OrderedDictionaryTests: CollectionTestCase {
withEvery("offset", in: 0 ..< count) { offset in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- var (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< count)
+ var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
let replacement = tracker.instance(for: -1)
- withHiddenCopies(if: isShared, of: &d) { d in
- let key = keys[offset]
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
+ let key = reference[offset].key
let old = d.updateValue(replacement, forKey: key)
- expectEqual(old, values[offset])
- values[offset] = replacement
- withEvery("i", in: 0 ..< count) { i in
- let (k, v) = d[offset: i]
- expectEqual(k, keys[i])
- expectEqual(v, values[i])
- }
+ expectEqual(old, reference[offset].value)
+ reference[offset].value = replacement
+ expectEqualElements(d, reference)
}
}
}
@@ -533,18 +476,15 @@ class OrderedDictionaryTests: CollectionTestCase {
withLifetimeTracking { tracker in
let keys = tracker.instances(for: 0 ..< count)
let values = tracker.instances(for: (0 ..< count).map { 100 + $0 })
+ let reference = zip(keys, values).map { (key: $0.0, value: $0.1) }
var d: OrderedDictionary, LifetimeTracked> = [:]
withEvery("offset", in: 0 ..< count) { offset in
- withHiddenCopies(if: isShared, of: &d) { d in
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
let key = keys[offset]
let old = d.updateValue(values[offset], forKey: key)
expectNil(old)
expectEqual(d.count, offset + 1)
- withEvery("i", in: 0 ... offset) { i in
- let (k, v) = d[offset: i]
- expectEqual(k, keys[i])
- expectEqual(v, values[i])
- }
+ expectEqualElements(d, reference.prefix(offset + 1))
}
}
}
@@ -557,20 +497,16 @@ class OrderedDictionaryTests: CollectionTestCase {
withEvery("offset", in: 0 ..< count) { offset in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- var (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< count)
+ var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
let replacement = tracker.instance(for: -1)
- withHiddenCopies(if: isShared, of: &d) { d in
- let key = keys[offset]
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
+ let key = reference[offset].key
let (old, index) =
d.updateValue(replacement, forKey: key, insertingAt: 0)
- expectEqual(old, values[offset])
+ expectEqual(old, reference[offset].value)
expectEqual(index, offset)
- values[offset] = replacement
- withEvery("i", in: 0 ..< count) { i in
- let (k, v) = d[offset: i]
- expectEqual(k, keys[i])
- expectEqual(v, values[i])
- }
+ reference[offset].value = replacement
+ expectEqualElements(d, reference)
}
}
}
@@ -584,9 +520,10 @@ class OrderedDictionaryTests: CollectionTestCase {
withLifetimeTracking { tracker in
let keys = tracker.instances(for: 0 ..< count)
let values = tracker.instances(for: (0 ..< count).map { 100 + $0 })
+ let reference = zip(keys, values).map { (key: $0.0, value: $0.1) }
var d: OrderedDictionary, LifetimeTracked> = [:]
withEvery("offset", in: 0 ..< count) { offset in
- withHiddenCopies(if: isShared, of: &d) { d in
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
let key = keys[count - 1 - offset]
let value = values[count - 1 - offset]
let (old, index) =
@@ -594,11 +531,7 @@ class OrderedDictionaryTests: CollectionTestCase {
expectNil(old)
expectEqual(index, 0)
expectEqual(d.count, offset + 1)
- withEvery("i", in: 0 ... offset) { i in
- let (k, v) = d[offset: i]
- expectEqual(k, keys[count - 1 - offset + i])
- expectEqual(v, values[count - 1 - offset + i])
- }
+ expectEqualElements(d, reference.suffix(offset + 1))
}
}
}
@@ -606,26 +539,22 @@ class OrderedDictionaryTests: CollectionTestCase {
}
}
- func test_modifyValue_forKey_default_closure_update() {
+ func test_updateValue_forKey_default_closure_update() {
withEvery("count", in: 0 ..< 30) { count in
withEvery("offset", in: 0 ..< count) { offset in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- var (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< count)
+ var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
let replacement = tracker.instance(for: -1)
let fallback = tracker.instance(for: -2)
- withHiddenCopies(if: isShared, of: &d) { d in
- let key = keys[offset]
- d.modifyValue(forKey: key, default: fallback) { value in
- expectEqual(value, values[offset])
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
+ let key = reference[offset].key
+ d.updateValue(forKey: key, default: fallback) { value in
+ expectEqual(value, reference[offset].value)
value = replacement
}
- values[offset] = replacement
- withEvery("i", in: 0 ..< count) { i in
- let (k, v) = d[offset: i]
- expectEqual(k, keys[i])
- expectEqual(v, values[i])
- }
+ reference[offset].value = replacement
+ expectEqualElements(d, reference)
}
}
}
@@ -633,27 +562,24 @@ class OrderedDictionaryTests: CollectionTestCase {
}
}
- func test_modifyValue_forKey_default_closure_insert() {
+ func test_updateValue_forKey_default_closure_insert() {
withEvery("count", in: 0 ..< 30) { count in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
let keys = tracker.instances(for: 0 ..< count)
let values = tracker.instances(for: (0 ..< count).map { 100 + $0 })
+ let reference = zip(keys, values).map { (key: $0.0, value: $0.1) }
var d: OrderedDictionary, LifetimeTracked> = [:]
let fallback = tracker.instance(for: -2)
withEvery("offset", in: 0 ..< count) { offset in
- withHiddenCopies(if: isShared, of: &d) { d in
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
let key = keys[offset]
- d.modifyValue(forKey: key, default: fallback) { value in
+ d.updateValue(forKey: key, default: fallback) { value in
expectEqual(value, fallback)
value = values[offset]
}
expectEqual(d.count, offset + 1)
- withEvery("i", in: 0 ... offset) { i in
- let (k, v) = d[offset: i]
- expectEqual(k, keys[i])
- expectEqual(v, values[i])
- }
+ expectEqualElements(d, reference.prefix(offset + 1))
}
}
}
@@ -661,27 +587,22 @@ class OrderedDictionaryTests: CollectionTestCase {
}
}
- func test_modifyValue_forKey_insertingDefault_at_closure_update() {
+ func test_updateValue_forKey_insertingDefault_at_closure_update() {
withEvery("count", in: 0 ..< 30) { count in
withEvery("offset", in: 0 ..< count) { offset in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- var (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< count)
+ var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
let replacement = tracker.instance(for: -1)
let fallback = tracker.instance(for: -2)
- withHiddenCopies(if: isShared, of: &d) { d in
- let key = keys[offset]
- let value = values[offset]
- d.modifyValue(forKey: key, insertingDefault: fallback, at: 0) { v in
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
+ let (key, value) = reference[offset]
+ d.updateValue(forKey: key, insertingDefault: fallback, at: 0) { v in
expectEqual(v, value)
v = replacement
}
- values[offset] = replacement
- withEvery("i", in: 0 ..< count) { i in
- let (k, v) = d[offset: i]
- expectEqual(k, keys[i])
- expectEqual(v, values[i])
- }
+ reference[offset].value = replacement
+ expectEqualElements(d, reference)
}
}
}
@@ -689,28 +610,24 @@ class OrderedDictionaryTests: CollectionTestCase {
}
}
- func test_modifyValue_forKey_insertingDefault_at_closure_insert() {
+ func test_updateValue_forKey_insertingDefault_at_closure_insert() {
withEvery("count", in: 0 ..< 30) { count in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
let keys = tracker.instances(for: 0 ..< count)
let values = tracker.instances(for: (0 ..< count).map { 100 + $0 })
+ let reference = zip(keys, values).map { (key: $0.0, value: $0.1) }
var d: OrderedDictionary, LifetimeTracked> = [:]
let fallback = tracker.instance(for: -2)
withEvery("offset", in: 0 ..< count) { offset in
- withHiddenCopies(if: isShared, of: &d) { d in
- let key = keys[count - 1 - offset]
- let value = values[count - 1 - offset]
- d.modifyValue(forKey: key, insertingDefault: fallback, at: 0) { v in
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
+ let (key, value) = reference[count - 1 - offset]
+ d.updateValue(forKey: key, insertingDefault: fallback, at: 0) { v in
expectEqual(v, fallback)
v = value
}
expectEqual(d.count, offset + 1)
- withEvery("i", in: 0 ... offset) { i in
- let (k, v) = d[offset: i]
- expectEqual(k, keys[count - 1 - offset + i])
- expectEqual(v, values[count - 1 - offset + i])
- }
+ expectEqualElements(d, reference.suffix(offset + 1))
}
}
}
@@ -723,19 +640,13 @@ class OrderedDictionaryTests: CollectionTestCase {
withEvery("offset", in: 0 ..< count) { offset in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- var (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< count)
- withHiddenCopies(if: isShared, of: &d) { d in
- let key = keys.remove(at: offset)
- let expected = values.remove(at: offset)
+ var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
+ let (key, value) = reference.remove(at: offset)
let actual = d.removeValue(forKey: key)
- expectEqual(actual, expected)
+ expectEqual(actual, value)
- expectEqual(d.count, values.count)
- withEvery("i", in: 0 ..< values.count) { i in
- let (k, v) = d[offset: i]
- expectEqual(k, keys[i])
- expectEqual(v, values[i])
- }
+ expectEqualElements(d, reference)
expectNil(d.removeValue(forKey: key))
}
}
@@ -1039,14 +950,13 @@ class OrderedDictionaryTests: CollectionTestCase {
withEvery("j", in: 0 ..< count) { j in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- var (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< count)
- keys.swapAt(i, j)
- values.swapAt(i, j)
- withHiddenCopies(if: isShared, of: &d) { d in
+ var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
+ reference.swapAt(i, j)
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
d.swapAt(i, j)
- expectEqualElements(d.values, values)
- expectEqual(d[keys[i]], values[i])
- expectEqual(d[keys[j]], values[j])
+ expectEqualElements(d, reference)
+ expectEqual(d[reference[i].key], reference[i].value)
+ expectEqual(d[reference[j].key], reference[j].value)
}
}
}
@@ -1061,14 +971,13 @@ class OrderedDictionaryTests: CollectionTestCase {
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
var rng = RepeatableRandomNumberGenerator(seed: seed)
- var (d, keys, values) = tracker.orderedDictionary(
+ var (d, reference) = tracker.orderedDictionary(
keys: (0 ..< count).shuffled(using: &rng))
- var items = Array(zip(keys, values))
- let expectedPivot = items.partition { $0.0.payload < count / 2 }
- withHiddenCopies(if: isShared, of: &d) { d in
+ let expectedPivot = reference.partition { $0.key.payload < count / 2 }
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
let actualPivot = d.partition { $0.key.payload < count / 2 }
expectEqual(actualPivot, expectedPivot)
- expectEqualElements(d, items)
+ expectEqualElements(d, reference)
}
}
}
@@ -1082,13 +991,12 @@ class OrderedDictionaryTests: CollectionTestCase {
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
var rng = RepeatableRandomNumberGenerator(seed: seed)
- var (d, keys, values) = tracker.orderedDictionary(
+ var (d, reference) = tracker.orderedDictionary(
keys: (0 ..< count).shuffled(using: &rng))
- var items = Array(zip(keys, values))
- items.sort(by: { $0.0 < $1.0 })
- withHiddenCopies(if: isShared, of: &d) { d in
+ reference.sort(by: { $0.key < $1.key })
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
d.sort()
- expectEqualElements(d, items)
+ expectEqualElements(d, reference)
}
}
}
@@ -1102,13 +1010,12 @@ class OrderedDictionaryTests: CollectionTestCase {
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
var rng = RepeatableRandomNumberGenerator(seed: seed)
- var (d, keys, values) = tracker.orderedDictionary(
+ var (d, reference) = tracker.orderedDictionary(
keys: (0 ..< count).shuffled(using: &rng))
- var items = Array(zip(keys, values))
- items.sort(by: { $0.0 > $1.0 })
- withHiddenCopies(if: isShared, of: &d) { d in
+ reference.sort(by: { $0.key > $1.key })
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
d.sort(by: { $0.key > $1.key })
- expectEqualElements(d, items)
+ expectEqualElements(d, reference)
}
}
}
@@ -1124,7 +1031,7 @@ class OrderedDictionaryTests: CollectionTestCase {
uniqueKeys: 0 ..< count,
values: 100 ..< 100 + count)
var items = (0 ..< count).map { (key: $0, value: 100 + $0) }
- withHiddenCopies(if: isShared, of: &d) { d in
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
expectEqualElements(d, items)
var rng1 = RepeatableRandomNumberGenerator(seed: seed)
@@ -1165,12 +1072,11 @@ class OrderedDictionaryTests: CollectionTestCase {
withEvery("count", in: 0 ..< 30) { count in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- var (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< count)
- var items = Array(zip(keys, values))
- withHiddenCopies(if: isShared, of: &d) { d in
- items.reverse()
+ var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
+ reference.reverse()
d.reverse()
- expectEqualElements(d, items)
+ expectEqualElements(d, reference)
}
}
}
@@ -1181,8 +1087,8 @@ class OrderedDictionaryTests: CollectionTestCase {
withEvery("count", in: 0 ..< 30) { count in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- var (d, _, _) = tracker.orderedDictionary(keys: 0 ..< count)
- withHiddenCopies(if: isShared, of: &d) { d in
+ var (d, _) = tracker.orderedDictionary(keys: 0 ..< count)
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
d.removeAll()
expectEqual(d.keys.__unstable.scale, 0)
expectEqualElements(d, [])
@@ -1196,9 +1102,9 @@ class OrderedDictionaryTests: CollectionTestCase {
withEvery("count", in: 0 ..< 30) { count in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- var (d, _, _) = tracker.orderedDictionary(keys: 0 ..< count)
+ var (d, _) = tracker.orderedDictionary(keys: 0 ..< count)
let origScale = d.keys.__unstable.scale
- withHiddenCopies(if: isShared, of: &d) { d in
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
d.removeAll(keepingCapacity: true)
expectEqual(d.keys.__unstable.scale, origScale)
expectEqualElements(d, [])
@@ -1213,16 +1119,13 @@ class OrderedDictionaryTests: CollectionTestCase {
withEvery("offset", in: 0 ..< count) { offset in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- var (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< count)
- withHiddenCopies(if: isShared, of: &d) { d in
+ var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
let actual = d.remove(at: offset)
- let expectedKey = keys.remove(at: offset)
- let expectedValue = values.remove(at: offset)
- expectEqual(actual.key, expectedKey)
- expectEqual(actual.value, expectedValue)
- expectEqualElements(
- d,
- zip(keys, values).map { (key: $0.0, value: $0.1) })
+ let expectedItem = reference.remove(at: offset)
+ expectEqual(actual.key, expectedItem.key)
+ expectEqual(actual.value, expectedItem.value)
+ expectEqualElements(d, reference)
}
}
}
@@ -1235,14 +1138,11 @@ class OrderedDictionaryTests: CollectionTestCase {
withEveryRange("range", in: 0 ..< count) { range in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- var (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< count)
- withHiddenCopies(if: isShared, of: &d) { d in
+ var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
d.removeSubrange(range)
- keys.removeSubrange(range)
- values.removeSubrange(range)
- expectEqualElements(
- d,
- zip(keys, values).map { (key: $0.0, value: $0.1) })
+ reference.removeSubrange(range)
+ expectEqualElements(d, reference)
}
}
}
@@ -1270,17 +1170,14 @@ class OrderedDictionaryTests: CollectionTestCase {
func test_removeLast() {
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- var (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< 30)
+ var (d, reference) = tracker.orderedDictionary(keys: 0 ..< 30)
withEvery("i", in: 0 ..< d.count) { i in
- withHiddenCopies(if: isShared, of: &d) { d in
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
let actual = d.removeLast()
- let expectedKey = keys.removeLast()
- let expectedValue = values.removeLast()
- expectEqual(actual.key, expectedKey)
- expectEqual(actual.value, expectedValue)
- expectEqualElements(
- d,
- zip(keys, values).map { (key: $0.0, value: $0.1) })
+ let ref = reference.removeLast()
+ expectEqual(actual.key, ref.key)
+ expectEqual(actual.value, ref.value)
+ expectEqualElements(d, reference)
}
}
}
@@ -1290,17 +1187,14 @@ class OrderedDictionaryTests: CollectionTestCase {
func test_removeFirst() {
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- var (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< 30)
+ var (d, reference) = tracker.orderedDictionary(keys: 0 ..< 30)
withEvery("i", in: 0 ..< d.count) { i in
- withHiddenCopies(if: isShared, of: &d) { d in
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
let actual = d.removeFirst()
- let expectedKey = keys.removeFirst()
- let expectedValue = values.removeFirst()
- expectEqual(actual.key, expectedKey)
- expectEqual(actual.value, expectedValue)
- expectEqualElements(
- d,
- zip(keys, values).map { (key: $0.0, value: $0.1) })
+ let expected = reference.removeFirst()
+ expectEqual(actual.key, expected.key)
+ expectEqual(actual.value, expected.value)
+ expectEqualElements(d, reference)
}
}
}
@@ -1312,14 +1206,11 @@ class OrderedDictionaryTests: CollectionTestCase {
withEvery("suffix", in: 0 ..< count) { suffix in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- var (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< count)
- withHiddenCopies(if: isShared, of: &d) { d in
+ var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
d.removeLast(suffix)
- keys.removeLast(suffix)
- values.removeLast(suffix)
- expectEqualElements(
- d,
- zip(keys, values).map { (key: $0.0, value: $0.1) })
+ reference.removeLast(suffix)
+ expectEqualElements(d, reference)
}
}
}
@@ -1332,14 +1223,11 @@ class OrderedDictionaryTests: CollectionTestCase {
withEvery("prefix", in: 0 ..< count) { prefix in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- var (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< count)
- withHiddenCopies(if: isShared, of: &d) { d in
+ var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
d.removeFirst(prefix)
- keys.removeFirst(prefix)
- values.removeFirst(prefix)
- expectEqualElements(
- d,
- zip(keys, values).map { (key: $0.0, value: $0.1) })
+ reference.removeFirst(prefix)
+ expectEqualElements(d, reference)
}
}
}
@@ -1352,12 +1240,11 @@ class OrderedDictionaryTests: CollectionTestCase {
withEvery("n", in: [2, 3, 4]) { n in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- var (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< count)
- var items = zip(keys, values).map { (key: $0.0, value: $0.1) }
- withHiddenCopies(if: isShared, of: &d) { d in
+ var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
d.removeAll(where: { !$0.key.payload.isMultiple(of: n) })
- items.removeAll(where: { !$0.key.payload.isMultiple(of: n) })
- expectEqualElements(d, items)
+ reference.removeAll(where: { !$0.key.payload.isMultiple(of: n) })
+ expectEqualElements(d, reference)
}
}
}
@@ -1368,11 +1255,10 @@ class OrderedDictionaryTests: CollectionTestCase {
func test_Sequence() {
withEvery("count", in: 0 ..< 30) { count in
withLifetimeTracking { tracker in
- let (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< count)
- let items = zip(keys, values).map { (key: $0.0, value: $0.1) }
+ let (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
checkSequence(
{ d },
- expectedContents: items,
+ expectedContents: reference,
by: { $0.key == $1.0 && $0.value == $1.1 })
}
}
diff --git a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Utils.swift b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Utils.swift
index 37db3faa..a79c993b 100644
--- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Utils.swift
+++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Utils.swift
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
-import CollectionsTestSupport
+import _CollectionsTestSupport
import OrderedCollections
extension LifetimeTracker {
@@ -17,8 +17,7 @@ extension LifetimeTracker {
keys: Keys
) -> (
dictionary: OrderedDictionary, LifetimeTracked>,
- keys: [LifetimeTracked],
- values: [LifetimeTracked]
+ expected: [(key: LifetimeTracked, value: LifetimeTracked)]
)
where Keys.Element == Int
{
@@ -26,6 +25,6 @@ extension LifetimeTracker {
let keys = self.instances(for: k)
let values = self.instances(for: k.map { $0 + 100 })
let dictionary = OrderedDictionary(uniqueKeys: keys, values: values)
- return (dictionary, keys, values)
+ return (dictionary, (0 ..< k.count).map { (key: keys[$0], value: values[$0]) })
}
}
diff --git a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Elements Tests.swift b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Elements Tests.swift
index 1bfc2410..ae07e1e6 100644
--- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Elements Tests.swift
+++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Elements Tests.swift
@@ -12,15 +12,14 @@
import XCTest
@_spi(Testing) import OrderedCollections
-import CollectionsTestSupport
+import _CollectionsTestSupport
class OrderedDictionaryElementsTests: CollectionTestCase {
func test_elements_getter() {
withEvery("count", in: 0 ..< 30) { count in
withLifetimeTracking { tracker in
- let (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< count)
- let items = zip(keys, values).map { (key: $0.0, value: $0.1) }
- expectEqualElements(d.elements, items)
+ let (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
+ expectEqualElements(d.elements, reference)
}
}
}
@@ -28,15 +27,14 @@ class OrderedDictionaryElementsTests: CollectionTestCase {
func test_elements_modify() {
withEvery("count", in: 0 ..< 30) { count in
withLifetimeTracking { tracker in
- var (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< count)
- let items = zip(keys, values).map { (key: $0.0, value: $0.1) }
+ var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
var d2 = OrderedDictionary, LifetimeTracked>()
swap(&d.elements, &d2.elements)
expectEqualElements(d, [])
- expectEqualElements(d2, items)
+ expectEqualElements(d2, reference)
}
}
}
@@ -44,14 +42,19 @@ class OrderedDictionaryElementsTests: CollectionTestCase {
func test_keys_values() {
withEvery("count", in: 0 ..< 30) { count in
withLifetimeTracking { tracker in
- var (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< count)
-
+ var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
+ let keys = reference.map { $0.key }
+ var values = reference.map { $0.value }
expectEqualElements(d.elements.keys, keys)
expectEqualElements(d.elements.values, values)
values.reverse()
d.elements.values.reverse()
+
+ for i in 0 ..< count { reference[i].value = values[i] }
expectEqualElements(d.elements.values, values)
+ expectEqualElements(d.elements, reference)
+ expectEqualElements(d, reference)
}
}
}
@@ -59,9 +62,9 @@ class OrderedDictionaryElementsTests: CollectionTestCase {
func test_index_forKey() {
withEvery("count", in: 0 ..< 30) { count in
withLifetimeTracking { tracker in
- let (d, keys, _) = tracker.orderedDictionary(keys: 0 ..< count)
+ let (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
withEvery("offset", in: 0 ..< count) { offset in
- expectEqual(d.elements.index(forKey: keys[offset]), offset)
+ expectEqual(d.elements.index(forKey: reference[offset].key), offset)
}
expectNil(d.elements.index(forKey: tracker.instance(for: -1)))
expectNil(d.elements.index(forKey: tracker.instance(for: count)))
@@ -72,10 +75,9 @@ class OrderedDictionaryElementsTests: CollectionTestCase {
func test_RandomAccessCollection() {
withEvery("count", in: 0 ..< 30) { count in
withLifetimeTracking { tracker in
- let (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< count)
- let items = zip(keys, values).map { (key: $0.0, value: $0.1) }
+ let (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
checkBidirectionalCollection(
- d.elements, expectedContents: items,
+ d.elements, expectedContents: reference,
by: { $0 == $1 })
}
}
@@ -144,16 +146,15 @@ class OrderedDictionaryElementsTests: CollectionTestCase {
withEvery("j", in: 0 ..< count) { j in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- var (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< count)
- keys.swapAt(i, j)
- values.swapAt(i, j)
- withHiddenCopies(if: isShared, of: &d) { d in
+ var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
+ reference.swapAt(i, j)
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
d.elements.swapAt(i, j)
expectEquivalentElements(
- d, zip(keys, values),
- by: { $0.key == $1.0 && $0.value == $1.1 })
- expectEqual(d[keys[i]], values[i])
- expectEqual(d[keys[j]], values[j])
+ d, reference,
+ by: { $0.key == $1.key && $0.value == $1.value })
+ expectEqual(d[reference[i].key], reference[i].value)
+ expectEqual(d[reference[j].key], reference[j].value)
}
}
}
@@ -168,14 +169,13 @@ class OrderedDictionaryElementsTests: CollectionTestCase {
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
var rng = RepeatableRandomNumberGenerator(seed: seed)
- var (d, keys, values) = tracker.orderedDictionary(
+ var (d, reference) = tracker.orderedDictionary(
keys: (0 ..< count).shuffled(using: &rng))
- var items = Array(zip(keys, values))
- let expectedPivot = items.partition { $0.0.payload < count / 2 }
- withHiddenCopies(if: isShared, of: &d) { d in
+ let expectedPivot = reference.partition { $0.key.payload < count / 2 }
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
let actualPivot = d.elements.partition { $0.key.payload < count / 2 }
expectEqual(actualPivot, expectedPivot)
- expectEqualElements(d, items)
+ expectEqualElements(d, reference)
}
}
}
@@ -189,13 +189,12 @@ class OrderedDictionaryElementsTests: CollectionTestCase {
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
var rng = RepeatableRandomNumberGenerator(seed: seed)
- var (d, keys, values) = tracker.orderedDictionary(
+ var (d, reference) = tracker.orderedDictionary(
keys: (0 ..< count).shuffled(using: &rng))
- var items = Array(zip(keys, values))
- items.sort(by: { $0.0 < $1.0 })
- withHiddenCopies(if: isShared, of: &d) { d in
+ reference.sort(by: { $0.key < $1.key })
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
d.elements.sort()
- expectEqualElements(d, items)
+ expectEqualElements(d, reference)
}
}
}
@@ -209,13 +208,12 @@ class OrderedDictionaryElementsTests: CollectionTestCase {
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
var rng = RepeatableRandomNumberGenerator(seed: seed)
- var (d, keys, values) = tracker.orderedDictionary(
+ var (d, reference) = tracker.orderedDictionary(
keys: (0 ..< count).shuffled(using: &rng))
- var items = Array(zip(keys, values))
- items.sort(by: { $0.0 > $1.0 })
- withHiddenCopies(if: isShared, of: &d) { d in
+ reference.sort(by: { $0.key > $1.key })
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
d.elements.sort(by: { $0.key > $1.key })
- expectEqualElements(d, items)
+ expectEqualElements(d, reference)
}
}
}
@@ -231,7 +229,7 @@ class OrderedDictionaryElementsTests: CollectionTestCase {
uniqueKeys: 0 ..< count,
values: 100 ..< 100 + count)
var items = (0 ..< count).map { (key: $0, value: 100 + $0) }
- withHiddenCopies(if: isShared, of: &d) { d in
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
expectEqualElements(d.elements, items)
var rng1 = RepeatableRandomNumberGenerator(seed: seed)
@@ -272,12 +270,11 @@ class OrderedDictionaryElementsTests: CollectionTestCase {
withEvery("count", in: 0 ..< 30) { count in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- var (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< count)
- var items = Array(zip(keys, values))
- withHiddenCopies(if: isShared, of: &d) { d in
- items.reverse()
+ var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
+ reference.reverse()
d.elements.reverse()
- expectEqualElements(d, items)
+ expectEqualElements(d, reference)
}
}
}
@@ -288,8 +285,8 @@ class OrderedDictionaryElementsTests: CollectionTestCase {
withEvery("count", in: 0 ..< 30) { count in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- var (d, _, _) = tracker.orderedDictionary(keys: 0 ..< count)
- withHiddenCopies(if: isShared, of: &d) { d in
+ var (d, _) = tracker.orderedDictionary(keys: 0 ..< count)
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
d.elements.removeAll()
expectEqual(d.keys.__unstable.scale, 0)
expectEqualElements(d, [])
@@ -303,9 +300,9 @@ class OrderedDictionaryElementsTests: CollectionTestCase {
withEvery("count", in: 0 ..< 30) { count in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- var (d, _, _) = tracker.orderedDictionary(keys: 0 ..< count)
+ var (d, _) = tracker.orderedDictionary(keys: 0 ..< count)
let origScale = d.keys.__unstable.scale
- withHiddenCopies(if: isShared, of: &d) { d in
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
d.elements.removeAll(keepingCapacity: true)
expectEqual(d.keys.__unstable.scale, origScale)
expectEqualElements(d, [])
@@ -320,16 +317,13 @@ class OrderedDictionaryElementsTests: CollectionTestCase {
withEvery("offset", in: 0 ..< count) { offset in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- var (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< count)
- withHiddenCopies(if: isShared, of: &d) { d in
+ var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
let actual = d.elements.remove(at: offset)
- let expectedKey = keys.remove(at: offset)
- let expectedValue = values.remove(at: offset)
- expectEqual(actual.key, expectedKey)
- expectEqual(actual.value, expectedValue)
- expectEqualElements(
- d,
- zip(keys, values).map { (key: $0.0, value: $0.1) })
+ let expected = reference.remove(at: offset)
+ expectEqual(actual.key, expected.key)
+ expectEqual(actual.value, expected.value)
+ expectEqualElements(d, reference)
}
}
}
@@ -342,14 +336,11 @@ class OrderedDictionaryElementsTests: CollectionTestCase {
withEveryRange("range", in: 0 ..< count) { range in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- var (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< count)
- withHiddenCopies(if: isShared, of: &d) { d in
+ var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
d.elements.removeSubrange(range)
- keys.removeSubrange(range)
- values.removeSubrange(range)
- expectEqualElements(
- d,
- zip(keys, values).map { (key: $0.0, value: $0.1) })
+ reference.removeSubrange(range)
+ expectEqualElements(d, reference)
}
}
}
@@ -377,17 +368,14 @@ class OrderedDictionaryElementsTests: CollectionTestCase {
func test_removeLast() {
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- var (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< 30)
+ var (d, reference) = tracker.orderedDictionary(keys: 0 ..< 30)
withEvery("i", in: 0 ..< d.count) { i in
- withHiddenCopies(if: isShared, of: &d) { d in
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
let actual = d.elements.removeLast()
- let expectedKey = keys.removeLast()
- let expectedValue = values.removeLast()
- expectEqual(actual.key, expectedKey)
- expectEqual(actual.value, expectedValue)
- expectEqualElements(
- d,
- zip(keys, values).map { (key: $0.0, value: $0.1) })
+ let expected = reference.removeLast()
+ expectEqual(actual.key, expected.key)
+ expectEqual(actual.value, expected.value)
+ expectEqualElements(d, reference)
}
}
}
@@ -397,17 +385,14 @@ class OrderedDictionaryElementsTests: CollectionTestCase {
func test_removeFirst() {
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- var (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< 30)
+ var (d, reference) = tracker.orderedDictionary(keys: 0 ..< 30)
withEvery("i", in: 0 ..< d.count) { i in
- withHiddenCopies(if: isShared, of: &d) { d in
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
let actual = d.elements.removeFirst()
- let expectedKey = keys.removeFirst()
- let expectedValue = values.removeFirst()
- expectEqual(actual.key, expectedKey)
- expectEqual(actual.value, expectedValue)
- expectEqualElements(
- d,
- zip(keys, values).map { (key: $0.0, value: $0.1) })
+ let expected = reference.removeFirst()
+ expectEqual(actual.key, expected.key)
+ expectEqual(actual.value, expected.value)
+ expectEqualElements(d, reference)
}
}
}
@@ -419,14 +404,11 @@ class OrderedDictionaryElementsTests: CollectionTestCase {
withEvery("suffix", in: 0 ..< count) { suffix in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- var (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< count)
- withHiddenCopies(if: isShared, of: &d) { d in
+ var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
d.elements.removeLast(suffix)
- keys.removeLast(suffix)
- values.removeLast(suffix)
- expectEqualElements(
- d,
- zip(keys, values).map { (key: $0.0, value: $0.1) })
+ reference.removeLast(suffix)
+ expectEqualElements(d, reference)
}
}
}
@@ -439,14 +421,11 @@ class OrderedDictionaryElementsTests: CollectionTestCase {
withEvery("prefix", in: 0 ..< count) { prefix in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- var (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< count)
- withHiddenCopies(if: isShared, of: &d) { d in
+ var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
d.elements.removeFirst(prefix)
- keys.removeFirst(prefix)
- values.removeFirst(prefix)
- expectEqualElements(
- d,
- zip(keys, values).map { (key: $0.0, value: $0.1) })
+ reference.removeFirst(prefix)
+ expectEqualElements(d, reference)
}
}
}
@@ -459,12 +438,11 @@ class OrderedDictionaryElementsTests: CollectionTestCase {
withEvery("n", in: [2, 3, 4]) { n in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- var (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< count)
- var items = zip(keys, values).map { (key: $0.0, value: $0.1) }
- withHiddenCopies(if: isShared, of: &d) { d in
+ var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
d.elements.removeAll(where: { !$0.key.payload.isMultiple(of: n) })
- items.removeAll(where: { !$0.key.payload.isMultiple(of: n) })
- expectEqualElements(d, items)
+ reference.removeAll(where: { !$0.key.payload.isMultiple(of: n) })
+ expectEqualElements(d, reference)
}
}
}
@@ -475,10 +453,10 @@ class OrderedDictionaryElementsTests: CollectionTestCase {
func test_slice_keys() {
withEvery("count", in: 0 ..< 30) { count in
withLifetimeTracking { tracker in
- let (d, keys, _) = tracker.orderedDictionary(keys: 0 ..< count)
+ let (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
withEveryRange("range", in: 0 ..< count) { range in
expectEqual(d.elements[range].keys, d.keys[range])
- expectEqualElements(d.elements[range].keys, keys[range])
+ expectEqualElements(d.elements[range].keys, reference[range].map { $0.key })
}
}
}
@@ -487,10 +465,10 @@ class OrderedDictionaryElementsTests: CollectionTestCase {
func test_slice_values() {
withEvery("count", in: 0 ..< 30) { count in
withLifetimeTracking { tracker in
- let (d, _, values) = tracker.orderedDictionary(keys: 0 ..< count)
+ let (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
withEveryRange("range", in: 0 ..< count) { range in
expectEqualElements(d.elements[range].values, d.values[range])
- expectEqualElements(d.elements[range].values, values[range])
+ expectEqualElements(d.elements[range].values, reference[range].map { $0.value })
}
}
}
@@ -500,9 +478,9 @@ class OrderedDictionaryElementsTests: CollectionTestCase {
withEvery("count", in: 0 ..< 30) { count in
withEveryRange("range", in: 0 ..< count) { range in
withLifetimeTracking { tracker in
- let (d, keys, _) = tracker.orderedDictionary(keys: 0 ..< count)
+ let (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
withEvery("offset", in: 0 ..< count) { offset in
- let actual = d.elements[range].index(forKey: keys[offset])
+ let actual = d.elements[range].index(forKey: reference[offset].key)
let expected = range.contains(offset) ? offset : nil
expectEqual(actual, expected)
}
diff --git a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Values Tests.swift b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Values Tests.swift
index c80a5fb4..d10c1528 100644
--- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Values Tests.swift
+++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Values Tests.swift
@@ -12,7 +12,7 @@
import XCTest
@_spi(Testing) import OrderedCollections
-import CollectionsTestSupport
+import _CollectionsTestSupport
class OrderedDictionaryValueTests: CollectionTestCase {
func test_values_getter() {
@@ -39,13 +39,13 @@ class OrderedDictionaryValueTests: CollectionTestCase {
withEvery("offset", in: 0 ..< count) { offset in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- var (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< count)
+ var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
let replacement = tracker.instance(for: -1)
- withHiddenCopies(if: isShared, of: &d) { d in
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
d.values[offset] = replacement
- values[offset] = replacement
- expectEqualElements(d.values, values)
- expectEqual(d[keys[offset]], values[offset])
+ reference[offset].value = replacement
+ expectEqualElements(d.values, reference.map { $0.value })
+ expectEqual(d[reference[offset].key], reference[offset].value)
}
}
}
@@ -68,16 +68,18 @@ class OrderedDictionaryValueTests: CollectionTestCase {
withEvery("count", in: 0 ..< 30) { count in
withEvery("offset", in: 0 ..< count) { offset in
withLifetimeTracking { tracker in
- var (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< count)
- // Discard `values` and recreate it from scratch to make sure its
- // elements are uniquely referenced.
- values = tracker.instances(for: values.lazy.map { $0.payload })
+ var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
+ // Discard reference values and recreate them from scratch to make
+ // sure values are all uniquely referenced.
+ for i in 0 ..< count {
+ reference[i].value = tracker.instance(for: reference[i].value.payload)
+ }
- checkMutation(&values[offset], tracker: tracker, delta: 10)
+ checkMutation(&reference[offset].value, tracker: tracker, delta: 10)
checkMutation(&d.values[offset], tracker: tracker, delta: 10)
- expectEqualElements(d.values, values)
- expectEqual(d[keys[offset]], values[offset])
+ expectEqualElements(d.values, reference.map { $0.value })
+ expectEqual(d[reference[offset].key], reference[offset].value)
}
}
}
@@ -89,13 +91,15 @@ class OrderedDictionaryValueTests: CollectionTestCase {
withEvery("j", in: 0 ..< count) { j in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- var (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< count)
- values.swapAt(i, j)
- withHiddenCopies(if: isShared, of: &d) { d in
+ var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
+ let t = reference[i].value
+ reference[i].value = reference[j].value
+ reference[j].value = t
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
d.values.swapAt(i, j)
- expectEqualElements(d.values, values)
- expectEqual(d[keys[i]], values[i])
- expectEqual(d[keys[j]], values[j])
+ expectEqualElements(d.values, reference.map { $0.value })
+ expectEqual(d[reference[i].key], reference[i].value)
+ expectEqual(d[reference[j].key], reference[j].value)
}
}
}
@@ -110,15 +114,16 @@ class OrderedDictionaryValueTests: CollectionTestCase {
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
var rng = RepeatableRandomNumberGenerator(seed: seed)
- var (d, keys, values) = tracker.orderedDictionary(
+ var (d, reference) = tracker.orderedDictionary(
keys: (0 ..< count).shuffled(using: &rng))
+ var values = reference.map { $0.value }
let expectedPivot = values.partition { $0.payload < 100 + count / 2 }
- withHiddenCopies(if: isShared, of: &d) { d in
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
let actualPivot = d.values.partition { $0.payload < 100 + count / 2 }
expectEqual(actualPivot, expectedPivot)
expectEqualElements(d.values, values)
withEvery("i", in: 0 ..< count) { i in
- expectEqual(d[keys[i]], values[i])
+ expectEqual(d[reference[i].key], values[i])
}
}
}
@@ -131,15 +136,15 @@ class OrderedDictionaryValueTests: CollectionTestCase {
withEvery("count", in: 0 ..< 30) { count in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- var (d, _, values) = tracker.orderedDictionary(keys: 0 ..< count)
+ var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
typealias R = [LifetimeTracked]
let actual =
- withHiddenCopies(if: isShared, of: &d) { d -> R in
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d -> R in
d.values.withUnsafeBufferPointer { buffer -> R in
Array(buffer)
}
}
- expectEqualElements(actual, values)
+ expectEqualElements(actual, reference.map { $0.value })
}
}
}
@@ -149,11 +154,11 @@ class OrderedDictionaryValueTests: CollectionTestCase {
withEvery("count", in: 0 ..< 30) { count in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- var (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< count)
+ var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
let replacement = tracker.instances(for: (0 ..< count).map { -$0 })
typealias R = [LifetimeTracked]
let actual =
- withHiddenCopies(if: isShared, of: &d) { d -> R in
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d -> R in
d.values.withUnsafeMutableBufferPointer { buffer -> R in
let result = Array(buffer)
expectEqual(buffer.count, replacement.count, trapping: true)
@@ -163,10 +168,10 @@ class OrderedDictionaryValueTests: CollectionTestCase {
return result
}
}
- expectEqualElements(actual, values)
+ expectEqualElements(actual, reference.map { $0.value })
expectEqualElements(d.values, replacement)
withEvery("i", in: 0 ..< count) { i in
- expectEqual(d[keys[i]], replacement[i])
+ expectEqual(d[reference[i].key], replacement[i])
}
}
}
@@ -177,11 +182,11 @@ class OrderedDictionaryValueTests: CollectionTestCase {
withEvery("count", in: 0 ..< 30) { count in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
- var (d, keys, values) = tracker.orderedDictionary(keys: 0 ..< count)
+ var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
let replacement = tracker.instances(for: (0 ..< count).map { -$0 })
typealias R = [LifetimeTracked]
let actual =
- withHiddenCopies(if: isShared, of: &d) { d -> R? in
+ withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d -> R? in
d.values.withContiguousMutableStorageIfAvailable { buffer -> R in
let result = Array(buffer)
expectEqual(buffer.count, replacement.count, trapping: true)
@@ -192,10 +197,10 @@ class OrderedDictionaryValueTests: CollectionTestCase {
}
}
if let actual = actual {
- expectEqualElements(actual, values)
+ expectEqualElements(actual, reference.map { $0.value })
expectEqualElements(d.values, replacement)
withEvery("i", in: 0 ..< count) { i in
- expectEqual(d[keys[i]], replacement[i])
+ expectEqual(d[reference[i].key], replacement[i])
}
} else {
expectFailure("OrderedDictionary.Value isn't contiguous?")
@@ -204,6 +209,4 @@ class OrderedDictionaryValueTests: CollectionTestCase {
}
}
}
-
-
}
diff --git a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSet Diffing Tests.swift b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSet Diffing Tests.swift
index 59d86b98..1f06a148 100644
--- a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSet Diffing Tests.swift
+++ b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSet Diffing Tests.swift
@@ -11,7 +11,7 @@
import XCTest
import OrderedCollections
-import CollectionsTestSupport
+import _CollectionsTestSupport
class MeasuringHashable: Hashable {
static var equalityChecks = 0
diff --git a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSet.UnorderedView Tests.swift b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSet.UnorderedView Tests.swift
index 63fe2e45..b9021ca6 100644
--- a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSet.UnorderedView Tests.swift
+++ b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSet.UnorderedView Tests.swift
@@ -11,7 +11,7 @@
import XCTest
@_spi(Testing) import OrderedCollections
-import CollectionsTestSupport
+import _CollectionsTestSupport
class OrderedSetUnorderedViewTests: CollectionTestCase {
func test_unordered_insert() {
diff --git a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetInternals.swift b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetInternals.swift
index 0215248a..397db56d 100644
--- a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetInternals.swift
+++ b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetInternals.swift
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
-import CollectionsTestSupport
+import _CollectionsTestSupport
@_spi(Testing) import OrderedCollections
struct OrderedSetLayout: Hashable, CustomStringConvertible {
diff --git a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift
index b0f7e7f3..f2161dc3 100644
--- a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift
+++ b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift
@@ -11,7 +11,7 @@
import XCTest
@_spi(Testing) import OrderedCollections
-import CollectionsTestSupport
+import _CollectionsTestSupport
class OrderedSetTests: CollectionTestCase {
func test_init_uncheckedUniqueElements_concrete() {
@@ -356,7 +356,7 @@ class OrderedSetTests: CollectionTestCase {
let count = layout.count
withEvery("offset", in: 0 ... count) { offset in
var set = OrderedSet(layout: layout)
- withHiddenCopies(if: isShared, of: &set) { set in
+ withHiddenCopies(if: isShared, of: &set, checker: { $0._checkInvariants() }) { set in
let i = set.index(set.startIndex, offsetBy: offset)
let (inserted, index) = set.insert(count, at: i)
expectTrue(inserted)
@@ -511,7 +511,7 @@ class OrderedSetTests: CollectionTestCase {
let count = layout.count
withEvery("a", in: 0 ..< count) { a in
var set = OrderedSet(layout: layout)
- withHiddenCopies(if: isShared, of: &set) { set in
+ withHiddenCopies(if: isShared, of: &set, checker: { $0._checkInvariants() }) { set in
let b = count - a - 1
let ai = set._index(at: a)
let bi = set._index(at: b)
@@ -535,7 +535,7 @@ class OrderedSetTests: CollectionTestCase {
withEvery("isShared", in: [false, true]) { isShared in
let count = layout.count
var set = OrderedSet(layout: layout)
- withHiddenCopies(if: isShared, of: &set) { set in
+ withHiddenCopies(if: isShared, of: &set, checker: { $0._checkInvariants() }) { set in
let pivot = set.partition(by: { $0.isMultiple(of: 2) })
withEvery("item", in: 0 ..< count) { item in
expectNotNil(set.firstIndex(of: item)) { index in
@@ -559,7 +559,7 @@ class OrderedSetTests: CollectionTestCase {
withEvery("isShared", in: [false, true]) { isShared in
let count = layout.count
var set = OrderedSet(layout: layout)
- withHiddenCopies(if: isShared, of: &set) { set in
+ withHiddenCopies(if: isShared, of: &set, checker: { $0._checkInvariants() }) { set in
do {
let pivot = set.partition(by: { _ in false })
expectEqual(pivot, set.endIndex)
@@ -585,7 +585,7 @@ class OrderedSetTests: CollectionTestCase {
var rng = RepeatableRandomNumberGenerator(seed: seed)
let contents = (0 ..< count).shuffled(using: &rng)
var set = OrderedSet(layout: layout, contents: contents)
- withHiddenCopies(if: isShared, of: &set) { set in
+ withHiddenCopies(if: isShared, of: &set, checker: { $0._checkInvariants() }) { set in
set.sort()
expectEqualElements(set, 0 ..< count)
@@ -605,7 +605,7 @@ class OrderedSetTests: CollectionTestCase {
let count = layout.count
var contents = Array(0 ..< count)
var set = OrderedSet(layout: layout, contents: 0 ..< count)
- withHiddenCopies(if: isShared, of: &set) { set in
+ withHiddenCopies(if: isShared, of: &set, checker: { $0._checkInvariants() }) { set in
var rng1 = RepeatableRandomNumberGenerator(seed: seed)
contents.shuffle(using: &rng1)
@@ -637,7 +637,7 @@ class OrderedSetTests: CollectionTestCase {
let count = layout.count
var contents = Array(0 ..< count)
var set = OrderedSet(layout: layout, contents: 0 ..< count)
- withHiddenCopies(if: isShared, of: &set) { set in
+ withHiddenCopies(if: isShared, of: &set, checker: { $0._checkInvariants() }) { set in
contents.reverse()
set.reverse()
expectEqualElements(set, contents)
@@ -651,7 +651,7 @@ class OrderedSetTests: CollectionTestCase {
withEvery("offset", in: 0 ..< layout.count) { offset in
withEvery("isShared", in: [false, true]) { isShared in
var set = OrderedSet(layout: layout)
- withHiddenCopies(if: isShared, of: &set) { set in
+ withHiddenCopies(if: isShared, of: &set, checker: { $0._checkInvariants() }) { set in
let count = layout.count
let index = set._index(at: offset)
let old = set.remove(at: index)
@@ -698,7 +698,7 @@ class OrderedSetTests: CollectionTestCase {
withEvery("item", in: 0 ..< layout.count) { item in
withEvery("isShared", in: [false, true]) { isShared in
var set = OrderedSet(layout: layout)
- withHiddenCopies(if: isShared, of: &set) { set in
+ withHiddenCopies(if: isShared, of: &set, checker: { $0._checkInvariants() }) { set in
let count = layout.count
let old = set.remove(item)
expectEqual(old, item)
@@ -738,7 +738,7 @@ class OrderedSetTests: CollectionTestCase {
var set = OrderedSet(layout: layout)
let low = offsetRange.lowerBound
let high = offsetRange.upperBound
- withHiddenCopies(if: isShared, of: &set) { set in
+ withHiddenCopies(if: isShared, of: &set, checker: { $0._checkInvariants() }) { set in
let count = layout.count
let removedRange = set._indexRange(at: low ..< high)
set.removeSubrange(removedRange)
diff --git a/Tests/PriorityQueueTests/HeapTests.swift b/Tests/PriorityQueueTests/HeapTests.swift
index 12b6b03b..341645fd 100644
--- a/Tests/PriorityQueueTests/HeapTests.swift
+++ b/Tests/PriorityQueueTests/HeapTests.swift
@@ -10,7 +10,7 @@
//===----------------------------------------------------------------------===//
import XCTest
-@testable import PriorityQueueModule
+import PriorityQueueModule
final class HeapTests: XCTestCase {
func test_isEmpty() {
@@ -89,9 +89,12 @@ final class HeapTests: XCTestCase {
heap.insert(contentsOf: sequence(first: 1, next: addTwo(_:)).prefix(20))
XCTAssertEqual(heap.count, 40)
- for (idx, i) in heap.ascending.enumerated() {
- XCTAssertEqual(idx, i)
+ var i = 0
+ while let min = heap.popMin() {
+ XCTAssertEqual(min, i)
+ i += 1
}
+ XCTAssertEqual(i, 40)
}
func test_min() {
@@ -348,24 +351,6 @@ final class HeapTests: XCTestCase {
// MARK: -
- func test_levelCalculation() {
- // Check alternating min and max levels in the heap
- let q = Heap()
- var isMin = true
- for exp in 0...12 {
- // Check [2^exp, 2^(exp + 1))
- for i in Int(pow(2, Double(exp)) - 1)..((0...50).shuffled())
-
- var increment = 0
- for val in heap.ascending {
- XCTAssertEqual(increment, val)
- increment += 1
- }
-
- increment = 50
- for val in heap.descending {
- XCTAssertEqual(increment, val)
- increment -= 1
- }
- }
}
diff --git a/Tests/PriorityQueueTests/NodeTests.swift b/Tests/PriorityQueueTests/NodeTests.swift
new file mode 100644
index 00000000..1ebab465
--- /dev/null
+++ b/Tests/PriorityQueueTests/NodeTests.swift
@@ -0,0 +1,30 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the Swift Collections open source project
+//
+// Copyright (c) 2021 Apple Inc. and the Swift project authors
+// Licensed under Apache License v2.0 with Runtime Library Exception
+//
+// See https://swift.org/LICENSE.txt for license information
+//
+//===----------------------------------------------------------------------===//
+
+#if DEBUG // These unit tests need access to PriorityQueueModule internals
+import XCTest
+@testable import PriorityQueueModule
+
+class NodeTests: XCTestCase {
+ func test_levelCalculation() {
+ // Check alternating min and max levels in the heap
+ var isMin = true
+ for exp in 0...12 {
+ // Check [2^exp, 2^(exp + 1))
+ for offset in Int(pow(2, Double(exp)) - 1).. _Node {
diff --git a/Tests/SortedCollectionsTests/SortedDictionary/SortedDictionary Tests.swift b/Tests/SortedCollectionsTests/SortedDictionary/SortedDictionary Tests.swift
index 10bd69ae..4d3dbd4d 100644
--- a/Tests/SortedCollectionsTests/SortedDictionary/SortedDictionary Tests.swift
+++ b/Tests/SortedCollectionsTests/SortedDictionary/SortedDictionary Tests.swift
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
-import CollectionsTestSupport
+import _CollectionsTestSupport
@_spi(Testing) @testable import SortedCollections
final class SortedDictionaryTests: CollectionTestCase {
diff --git a/Tests/SortedCollectionsTests/SortedDictionary/SortedDictionary Utils.swift b/Tests/SortedCollectionsTests/SortedDictionary/SortedDictionary Utils.swift
index 8a6c34e2..63ab3f0b 100644
--- a/Tests/SortedCollectionsTests/SortedDictionary/SortedDictionary Utils.swift
+++ b/Tests/SortedCollectionsTests/SortedDictionary/SortedDictionary Utils.swift
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
-import CollectionsTestSupport
+import _CollectionsTestSupport
import SortedCollections
extension LifetimeTracker {
diff --git a/Tests/SortedCollectionsTests/SortedSet/SortedSet Tests.swift b/Tests/SortedCollectionsTests/SortedSet/SortedSet Tests.swift
index 7ee5c7b0..378479e5 100644
--- a/Tests/SortedCollectionsTests/SortedSet/SortedSet Tests.swift
+++ b/Tests/SortedCollectionsTests/SortedSet/SortedSet Tests.swift
@@ -11,7 +11,7 @@
import XCTest
@_spi(Testing) import SortedCollections
-import CollectionsTestSupport
+import _CollectionsTestSupport
class SortedSetTests: CollectionTestCase {
func test_init_sortedElements() {
diff --git a/Utils/run-benchmarks.sh b/Utils/run-benchmarks.sh
index 4f262ad9..d38bc7e6 100755
--- a/Utils/run-benchmarks.sh
+++ b/Utils/run-benchmarks.sh
@@ -2,7 +2,7 @@
set -eu
-srcroot="$(dirname "$0")/.."
+srcroot="$(dirname "$0")/../Benchmarks"
results="batch.results"
command="${1:-help}"
@@ -12,7 +12,7 @@ run() {
local flags
flags="-c release"
flags="$flags -Xswiftc -Xllvm -Xswiftc -align-module-to-page-size"
- swift run --package-path "$srcroot" $flags swift-collections-benchmark "$@"
+ swift run --package-path "$srcroot" $flags benchmark "$@"
}
case "$command" in
diff --git a/Utils/run-full-tests.sh b/Utils/run-full-tests.sh
new file mode 100755
index 00000000..98df0c61
--- /dev/null
+++ b/Utils/run-full-tests.sh
@@ -0,0 +1,145 @@
+#!/bin/sh
+#===----------------------------------------------------------------------
+#
+# 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
+#
+#===----------------------------------------------------------------------
+
+# Build & test this package in as many configurations as possible.
+# It is a good idea to run this script before each release to uncover
+# potential problems not covered by the usual CI runs.
+#
+# Note that this is not a fully automated solution -- some manual editing will
+# sometimes be required when e.g. testing the package on older Xcode releases.
+
+set -eu
+
+cd "$(dirname $0)/.."
+
+build_dir="$(mktemp -d "/tmp/$(basename $0).XXXXX")"
+
+bold_on="$(tput bold)"
+bold_off="$(tput sgr0)"
+
+red_on="$(tput setaf 1)"
+red_off="$(tput sgr0)"
+
+spm_flags=""
+
+if [ "$(uname)" = "Darwin" ]; then
+ swift="xcrun swift"
+else
+ swift="swift"
+ spm_flags="$spm_flags -j 1"
+
+ if $swift --version | grep 'Swift version 5\.3\.' > /dev/null; then
+ spm_flags="$spm_flags --enable-test-discovery"
+ fi
+fi
+
+echo "Build output logs are saved in $bold_on$build_dir$bold_off"
+$swift --version
+
+_count=0
+try() {
+ label="$1"
+ shift
+ _count=$(($_count + 1))
+ count="$(printf "%02d" $_count)"
+ output="$build_dir/$count.$label.log"
+ echo "$bold_on[$count $label]$bold_off $@"
+ start="$(date +%s)"
+ if "$@" >"$output" 2>&1; then
+ end="$(date +%s)"
+ echo " Completed in $(($end - $start))s"
+ else
+ end="$(date +%s)"
+ echo " ${red_on}${bold_on}Failed in $(($end - $start))s.${bold_off}${red_off}" \
+ "${red_on}See $output for full console output.${red_off}"
+ tail -10 "$output" | sed 's/^/ /'
+ fi
+}
+
+# Build using SPM
+try "spm.debug" $swift test -c debug $spm_flags --build-path "$build_dir/spm.debug"
+try "spm.release" $swift test -c release $spm_flags --build-path "$build_dir/spm.release"
+
+# Build with CMake
+cmake_build_dir="$build_dir/cmake"
+try "cmake.generate" cmake -S . -B "$cmake_build_dir" -G Ninja
+try "cmake.build-with-ninja" ninja -C "$cmake_build_dir"
+
+# Build using xcodebuild
+try_xcodebuild() {
+ label="$1"
+ destination="$2"
+ shift 2
+
+ try "$label" \
+ xcrun xcodebuild -scheme swift-collections-Package \
+ -configuration Release \
+ -destination "$destination" \
+ -derivedDataPath "$build_dir/xcodebuild" \
+ "$@"
+}
+
+if [ "$(uname)" = "Darwin" ]; then
+ # Build using xcodebuild
+ try_xcodebuild "xcodebuild.build.macOS" "generic/platform=macOS" build
+ try_xcodebuild "xcodebuild.build.macCatalyst" "generic/platform=macOS,variant=Mac Catalyst" build
+ try_xcodebuild "xcodebuild.build.iOS" "generic/platform=iOS" build
+ try_xcodebuild "xcodebuild.build.iOS-simulator" "generic/platform=iOS Simulator" build
+ try_xcodebuild "xcodebuild.build.watchOS" "generic/platform=watchOS" build
+ try_xcodebuild "xcodebuild.build.watchOS-simulator" "generic/platform=watchOS Simulator" build
+ try_xcodebuild "xcodebuild.build.tvOS" "generic/platform=tvOS" build
+ try_xcodebuild "xcodebuild.build.tvOS-simulator" "generic/platform=tvOS Simulator" build
+
+ try_xcodebuild "xcodebuild.test.macOS" "platform=macOS" test
+ try_xcodebuild "xcodebuild.test.macCatalyst" "platform=macOS,variant=Mac Catalyst" test
+ try_xcodebuild "xcodebuild.test.iOS-simulator" "platform=iOS Simulator,name=iPhone 12" test
+ try_xcodebuild "xcodebuild.test.watchOS-simulator" "platform=watchOS Simulator,name=Apple Watch Series 6 - 44mm" test
+ try_xcodebuild "xcodebuild.test.tvOS-simulator" "platform=tvOS Simulator,name=Apple TV 4K (at 1080p) (2nd generation)" test
+fi
+
+# Build benchmarks
+cd Benchmarks
+try "benchmarks.debug" $swift run -c debug $spm_flags --build-path "$build_dir/benchmarks.debug" benchmark --help
+try "benchmarks.release" $swift run -c release $spm_flags --build-path "$build_dir/benchmarks.release" benchmark --help
+cd ..
+if [ "$(uname)" = "Darwin" ]; then
+ # FIXME: This should just work on Linux, too
+ try "run-benchmarks" ./Utils/run-benchmarks.sh run --max-size 128 "$build_dir/benchmark.results" --cycles 3
+fi
+
+# Build with custom configurations
+try "spm.internal-checks" $swift test -c debug -Xswiftc -DCOLLECTIONS_INTERNAL_CHECKS $spm_flags --build-path "$build_dir/spm.internal-checks"
+try "spm.deterministic-hashing" $swift test -c debug -Xswiftc -DCOLLECTIONS_DETERMINISTIC_HASHING $spm_flags --build-path "$build_dir/spm.deterministic-hashing"
+try "spm.internal-checks+deterministic-hashing" $swift test -c debug -Xswiftc -DCOLLECTIONS_INTERNAL_CHECKS -Xswiftc -DCOLLECTIONS_DETERMINISTIC_HASHING $spm_flags --build-path "$build_dir/spm.internal-checks+deterministic-hashing"
+
+# Some people like to build their dependencies in warnings-as-errors mode.
+# (This won't work with tests on Linux as we have some tests for deprecated APIs that will produce a warning there.)
+try "spm.warnings-as-errors.debug" $swift build -c debug -Xswiftc -warnings-as-errors $spm_flags --build-path "$build_dir/spm.warnings-as-errors"
+try "spm.warnings-as-errors.release" $swift build -c release -Xswiftc -warnings-as-errors $spm_flags --build-path "$build_dir/spm.warnings-as-errors"
+
+# Build with library evolution enabled. (This configuration is
+# unsupported, but let's make some effort not to break it.)
+if [ "$(uname)" = "Darwin" ]; then
+ try "spm.library-evolution" \
+ $swift build \
+ -c release \
+ $spm_flags \
+ --build-path "$build_dir/spm.library-evolution" \
+ -Xswiftc -enable-library-evolution
+ try "xcodebuild.library-evolution" \
+ xcodebuild -scheme swift-collections-Package \
+ -destination "generic/platform=macOS" \
+ -destination "generic/platform=iOS" \
+ BUILD_LIBRARY_FOR_DISTRIBUTION=YES
+fi
+
+$swift package clean
diff --git a/Utils/swift-collections.xcworkspace/contents.xcworkspacedata b/Utils/swift-collections.xcworkspace/contents.xcworkspacedata
new file mode 100644
index 00000000..8beb57f1
--- /dev/null
+++ b/Utils/swift-collections.xcworkspace/contents.xcworkspacedata
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
diff --git a/swift-collections.xcworkspace/xcshareddata/IDETemplateMacros.plist b/Utils/swift-collections.xcworkspace/xcshareddata/IDETemplateMacros.plist
similarity index 100%
rename from swift-collections.xcworkspace/xcshareddata/IDETemplateMacros.plist
rename to Utils/swift-collections.xcworkspace/xcshareddata/IDETemplateMacros.plist
diff --git a/swift-collections.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/Utils/swift-collections.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
similarity index 100%
rename from swift-collections.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
rename to Utils/swift-collections.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
diff --git a/swift-collections.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Utils/swift-collections.xcworkspace/xcshareddata/swiftpm/Package.resolved
similarity index 100%
rename from swift-collections.xcworkspace/xcshareddata/swiftpm/Package.resolved
rename to Utils/swift-collections.xcworkspace/xcshareddata/swiftpm/Package.resolved
diff --git a/cmake/modules/SwiftSupport.cmake b/cmake/modules/SwiftSupport.cmake
index 9b08d5e7..d3d40591 100644
--- a/cmake/modules/SwiftSupport.cmake
+++ b/cmake/modules/SwiftSupport.cmake
@@ -17,7 +17,7 @@ See https://swift.org/LICENSE.txt for license information
function(get_swift_host_arch result_var_name)
if("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "x86_64")
set("${result_var_name}" "x86_64" PARENT_SCOPE)
- elseif ("${CMAKE_SYSTEM_PROCESSOR}" MATCHES "AArch64|arm64")
+ elseif ("${CMAKE_SYSTEM_PROCESSOR}" MATCHES "AArch64|aarch64|arm64")
if(CMAKE_SYSTEM_NAME MATCHES Darwin)
set("${result_var_name}" "arm64" PARENT_SCOPE)
else()
diff --git a/swift-collections.xcworkspace/contents.xcworkspacedata b/swift-collections.xcworkspace/contents.xcworkspacedata
deleted file mode 100644
index 030db5a6..00000000
--- a/swift-collections.xcworkspace/contents.xcworkspacedata
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
-
-
-
-
-