From f73d5e95a8aef64795805f54159579a1a08f8a6d Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 13 Aug 2021 14:14:26 -0700 Subject: [PATCH 01/54] Add reference benchmarks for bit vector implementations (#79) * [benchmark] Reorganize C++/Foundation benchmarks into separate files * [benchmark] Add reference benchmarks for std::vector and CFBitVector * Fix thinko breaking non-Darwin builds --- Benchmarks/Benchmarks/Cpp/CppBenchmarks.swift | 44 ++ .../Benchmarks/Cpp/CppDequeBenchmarks.swift | 170 +++++ .../Cpp/CppPriorityQueueBenchmarks.swift | 96 +++ .../Cpp/CppUnorderedMapBenchmarks.swift | 153 ++++ .../Cpp/CppUnorderedSetBenchmarks.swift | 122 +++ .../Benchmarks/Cpp/CppVectorBenchmarks.swift | 188 +++++ .../Cpp/CppVectorBoolBenchmarks.swift | 237 ++++++ Benchmarks/Benchmarks/CppBenchmarks.swift | 710 ------------------ .../CFBinaryHeapBenchmarks.swift} | 2 +- .../Foundation/CFBitVectorBenchmarks.swift | 161 ++++ .../Foundation/FoundationBenchmarks.swift | 19 + .../include/VectorBoolBenchmarks.h | 67 ++ .../CppBenchmarks/include/module.modulemap | 1 + .../src/VectorBoolBenchmarks.cpp | 147 ++++ Benchmarks/Libraries/BitSet.json | 78 ++ 15 files changed, 1484 insertions(+), 711 deletions(-) create mode 100644 Benchmarks/Benchmarks/Cpp/CppBenchmarks.swift create mode 100644 Benchmarks/Benchmarks/Cpp/CppDequeBenchmarks.swift create mode 100644 Benchmarks/Benchmarks/Cpp/CppPriorityQueueBenchmarks.swift create mode 100644 Benchmarks/Benchmarks/Cpp/CppUnorderedMapBenchmarks.swift create mode 100644 Benchmarks/Benchmarks/Cpp/CppUnorderedSetBenchmarks.swift create mode 100644 Benchmarks/Benchmarks/Cpp/CppVectorBenchmarks.swift create mode 100644 Benchmarks/Benchmarks/Cpp/CppVectorBoolBenchmarks.swift delete mode 100644 Benchmarks/Benchmarks/CppBenchmarks.swift rename Benchmarks/Benchmarks/{FoundationBenchmarks.swift => Foundation/CFBinaryHeapBenchmarks.swift} (98%) create mode 100644 Benchmarks/Benchmarks/Foundation/CFBitVectorBenchmarks.swift create mode 100644 Benchmarks/Benchmarks/Foundation/FoundationBenchmarks.swift create mode 100644 Benchmarks/CppBenchmarks/include/VectorBoolBenchmarks.h create mode 100644 Benchmarks/CppBenchmarks/src/VectorBoolBenchmarks.cpp create mode 100644 Benchmarks/Libraries/BitSet.json diff --git a/Benchmarks/Benchmarks/Cpp/CppBenchmarks.swift b/Benchmarks/Benchmarks/Cpp/CppBenchmarks.swift new file mode 100644 index 00000000..145a1afe --- /dev/null +++ b/Benchmarks/Benchmarks/Cpp/CppBenchmarks.swift @@ -0,0 +1,44 @@ +//===----------------------------------------------------------------------===// +// +// 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() + } +} 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/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) - } -} - - -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() - } - } - } -} 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 7fbcf933..82844245 100644 --- a/Benchmarks/CppBenchmarks/include/module.modulemap +++ b/Benchmarks/CppBenchmarks/include/module.modulemap @@ -6,5 +6,6 @@ module CppBenchmarks { header "UnorderedSetBenchmarks.h" header "UnorderedMapBenchmarks.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" + ] + }, + ] + } + ] + +} From 0d73c74c9fbdd809638b155355c8424356f560a2 Mon Sep 17 00:00:00 2001 From: Tyler Stromberg Date: Fri, 13 Aug 2021 18:31:33 -0700 Subject: [PATCH 02/54] Fix Markdown link in README (#77) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1ef75646..d65bbc1d 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ 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. +- [`Heap`](Documentation/Heap.md), a min-max heap backed by an array. [Deque]: Documentation/Deque.md [OrderedSet]: Documentation/OrderedSet.md From 69d4867984e0fad6fbb201682e0d40afad6bddcf Mon Sep 17 00:00:00 2001 From: ejmarchant Date: Mon, 16 Aug 2021 21:37:05 +0100 Subject: [PATCH 03/54] Fix documentation for types conforming to ExpressibleByArrayLiteral or ExpressibleByDictionaryLiteral (#82) --- .../DequeModule/Deque+ExpressibleByArrayLiteral.swift | 6 +++--- ...eredDictionary+ExpressibleByDictionaryLiteral.swift | 9 +++------ .../OrderedSet+ExpressibleByArrayLiteral.swift | 10 +++++----- .../Heap+ExpressibleByArrayLiteral.swift | 2 +- 4 files changed, 12 insertions(+), 15 deletions(-) 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/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/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/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) } From cd339541686c6841a0482cc8dd78c810cf86874c Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 16 Aug 2021 22:28:55 -0700 Subject: [PATCH 04/54] [Heap] Performance tweaks (#78) * [Heap] Don't always inline large functions * [docs] Use a stable link to the Atkinson article (The original link was pointing to course materials at a random university.) * Remove stray import * Revert "[Heap] Don't always inline large functions" This reverts commit 07ffd6591f2a790f6b84b668c06a188325d4eaf2. * [Heap] Enable code coverage collection in Xcode scheme * [Heap] Speed up invariant checking * [Heap] Precalculate levels for each offset `_Node` is a new struct that consists of a storage offset (the old index) along with its level in the tree. The level can be incrementally calculated, saving some time vs counting bits whenever it's needed. * [Heap] Switch to using unsafe buffer pointers Introduce `Heap._UnsafeHandle` (a thin wrapper around an unsafe buffer pointer) and rebase most heap algorithms on top of that instead of array operations. This simplifies things by reducing (hopefully) unnecessary index validation, resulting in some measurable performance improvements. * [Heap] Stop force-inlining bubbleUp; mark it releasenone Not inlining such a large function speeds things up by leaving some headroom for the optimizer to make better inlining decisions elsewhere. (Force inlining this resulted in the compiler not inlining the closure passed to `_update` instead, which isn't a great tradeoff. To speed things up, mark `bubbleUp` with `@_effects(releasenone)`. This may be questionable (because it calls `Element.<`), but it results in better codegen, making `insert` match the performance of `std::priority_queue`. * [Heap] Rework removals * [Heap] Remove dead code * [Heap] Switch to using _ContiguousArray as storage * [Heap] insert(contentsOf:): add fast path for count == 0 case * [Heap] Perf pass on trickleDown code paths This improves popMin/popMax (and the sequence initializer) by reviewing trickleDown and optimizing things: - Replace swapAt with a scheme where we keep a hold in the storage buffer - Slightly shorten min/max dependency chain in primary sink loop In exchange, we get even less readable code. * [Heap] bubbleUp: remove @_effects attribute This reintroduces retain/release operations for the empty array until https://github.com/apple/swift/pull/38898 lands. Mitigate the performance costs of this by refactoring code to reduce the size of the inlined bubbleUpMin/Max invocations. * [Heap] Finetune Heap.insert --- .../xcschemes/PriorityQueueModule.xcscheme | 3 +- .../PriorityQueueModule/Heap+Invariants.swift | 93 +--- .../Heap+UnsafeHandle.swift | 371 ++++++++++++++ Sources/PriorityQueueModule/Heap.swift | 484 +++--------------- Sources/PriorityQueueModule/_Node.swift | 174 +++++++ Tests/PriorityQueueTests/HeapTests.swift | 11 +- 6 files changed, 660 insertions(+), 476 deletions(-) create mode 100644 Sources/PriorityQueueModule/Heap+UnsafeHandle.swift create mode 100644 Sources/PriorityQueueModule/_Node.swift 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/Sources/PriorityQueueModule/Heap+Invariants.swift b/Sources/PriorityQueueModule/Heap+Invariants.swift index 3396df5a..61999115 100644 --- a/Sources/PriorityQueueModule/Heap+Invariants.swift +++ b/Sources/PriorityQueueModule/Heap+Invariants.swift @@ -14,78 +14,41 @@ 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+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..b40727b3 100644 --- a/Sources/PriorityQueueModule/Heap.swift +++ b/Sources/PriorityQueueModule/Heap.swift @@ -9,28 +9,36 @@ // //===----------------------------------------------------------------------===// -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. /// -/// 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 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 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) 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 +46,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 +60,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 +69,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 +89,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 +108,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 +129,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 +168,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 +175,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 +196,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/Tests/PriorityQueueTests/HeapTests.swift b/Tests/PriorityQueueTests/HeapTests.swift index 12b6b03b..880e0c8a 100644 --- a/Tests/PriorityQueueTests/HeapTests.swift +++ b/Tests/PriorityQueueTests/HeapTests.swift @@ -350,18 +350,13 @@ final class HeapTests: XCTestCase { 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).. Date: Tue, 17 Aug 2021 19:54:30 +0100 Subject: [PATCH 05/54] Fix typos: missing subscript parameters (#81) * Fix typos: missing subscript parameters * Fix typos: more missing subscript parameters * Improve symbol documentation --- .../OrderedDictionary+Elements+SubSequence.swift | 13 +++++++------ .../OrderedDictionary+Elements.swift | 4 ++-- .../OrderedDictionary/OrderedDictionary.swift | 2 +- 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements+SubSequence.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements+SubSequence.swift index 542defb3..86135cc5 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. diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift index a04799ad..cf872e83 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. diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift index 3b322743..648b0c6c 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift @@ -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. From 1eea663318a42ce696cc6ca2f4f336fc7f8254f4 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 17 Aug 2021 13:46:10 -0700 Subject: [PATCH 06/54] [Heap] Update implementation details section in docs (#84) - Use a persistent DOI-based link rather than linking to ephemeral course material. - Replace the example heap (borrowed from Wikipedia) with a better one. --- Documentation/Heap.md | 27 +++++++++++++------------- Sources/PriorityQueueModule/Heap.swift | 10 +++++----- 2 files changed, 19 insertions(+), 18 deletions(-) diff --git a/Documentation/Heap.md b/Documentation/Heap.md index 8a37ec52..959d749e 100644 --- a/Documentation/Heap.md +++ b/Documentation/Heap.md @@ -134,29 +134,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/Sources/PriorityQueueModule/Heap.swift b/Sources/PriorityQueueModule/Heap.swift index b40727b3..cd1c3f8e 100644 --- a/Sources/PriorityQueueModule/Heap.swift +++ b/Sources/PriorityQueueModule/Heap.swift @@ -11,13 +11,13 @@ /// 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 on [Atkinson 1986]: +/// The implementation is based on [Atkinson et al. 1986]: /// -/// [Atkinson 1986]: https://doi.org/10.1145/6617.6621 +/// [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." From 413ff5596ce30ce8f6b7d1cbacc8272751702599 Mon Sep 17 00:00:00 2001 From: Saleem Abdulrasool Date: Tue, 17 Aug 2021 19:03:49 -0700 Subject: [PATCH 07/54] Update CMakeLists.txt Update source list of priority queue implementation after #78 --- Sources/PriorityQueueModule/CMakeLists.txt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Sources/PriorityQueueModule/CMakeLists.txt b/Sources/PriorityQueueModule/CMakeLists.txt index 1ddcd8e2..a79783d2 100644 --- a/Sources/PriorityQueueModule/CMakeLists.txt +++ b/Sources/PriorityQueueModule/CMakeLists.txt @@ -8,10 +8,12 @@ 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+OrderedViews.swift + Heap+UnsafeHandle.swift) set_target_properties(PriorityQueueModule PROPERTIES INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY}) From 0d1ca3240c141a569303bbd28a3d36310d474026 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 19 Aug 2021 11:42:14 -0700 Subject: [PATCH 08/54] Stop depending on swift-collections-benchmark (#86) * Stop depending on swift-collections-benchmark Instead, move the benchmark suite into its own private nested package, under `Benchmarks/`. The recommended way to build & run benchmarks is via the `Utils/run-benchmarks.sh` script, which continues to work as before with this change. * Delete top-level Package.resolved file --- .gitignore | 2 + .../swift-collections-benchmark.xcscheme | 111 ------------------ .../Package.resolved | 4 +- Benchmarks/Package.swift | 47 ++++++++ .../main.swift | 0 Package.swift | 32 +---- Utils/run-benchmarks.sh | 4 +- 7 files changed, 54 insertions(+), 146 deletions(-) delete mode 100644 .swiftpm/xcode/xcshareddata/xcschemes/swift-collections-benchmark.xcscheme rename Package.resolved => Benchmarks/Package.resolved (89%) create mode 100644 Benchmarks/Package.swift rename Benchmarks/{swift-collections-benchmark => benchmark-tool}/main.swift (100%) 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/swift-collections-benchmark.xcscheme b/.swiftpm/xcode/xcshareddata/xcschemes/swift-collections-benchmark.xcscheme deleted file mode 100644 index 2285c9c1..00000000 --- a/.swiftpm/xcode/xcshareddata/xcschemes/swift-collections-benchmark.xcscheme +++ /dev/null @@ -1,111 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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/Package.swift b/Package.swift index ace16942..b596b6ea 100644 --- a/Package.swift +++ b/Package.swift @@ -56,10 +56,6 @@ let package = Package( .library(name: "OrderedCollections", targets: ["OrderedCollections"]), .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", @@ -88,31 +84,6 @@ let package = Package( 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", @@ -142,6 +113,5 @@ let package = Package( name: "PriorityQueueTests", dependencies: ["PriorityQueueModule"], swiftSettings: settings), - ], - cxxLanguageStandard: .cxx1z + ] ) 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 From 53a870dd0b71fe0c1fe0d35b67de932e39d87279 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 19 Aug 2021 15:42:17 -0700 Subject: [PATCH 09/54] =?UTF-8?q?[OrderedDictionary]=20modifyValue=20?= =?UTF-8?q?=E2=86=92=20updateValue=20(#91)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [OrderedDictionary] modifyValue → updateValue * Update CMakeLists.txt --- Documentation/OrderedDictionary.md | 4 +- Sources/OrderedCollections/CMakeLists.txt | 7 ++-- .../OrderedDictionary+Deprecations.swift | 37 +++++++++++++++++++ .../OrderedDictionary+Initializers.swift | 2 +- .../OrderedDictionary/OrderedDictionary.swift | 16 ++++---- .../OrderedDictionary Tests.swift | 16 ++++---- 6 files changed, 60 insertions(+), 22 deletions(-) create mode 100644 Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Deprecations.swift 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/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+Deprecations.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Deprecations.swift new file mode 100644 index 00000000..654418e2 --- /dev/null +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Deprecations.swift @@ -0,0 +1,37 @@ +//===----------------------------------------------------------------------===// +// +// 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 { + @available(*, deprecated, renamed: "updateValue(forKey:default:with:)") + @inlinable + public mutating func modifyValue( + forKey key: Key, + default defaultValue: @autoclosure () -> Value, + _ body: (inout Value) throws -> R + ) rethrows -> R { + try self.updateValue(forKey: key, default: defaultValue(), with: body) + } + + @available(*, deprecated, 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 { + try self.updateValue( + forKey: key, + insertingDefault: defaultValue(), + at: index, + with: body) + } +} diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Initializers.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Initializers.swift index 1d27adaa..fb8c26c3 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) } } diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift index 648b0c6c..d30a4335 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 /// } /// } @@ -641,7 +641,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 +660,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 +687,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 +706,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/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift index c940cdd6..9b8ffde7 100644 --- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift @@ -606,7 +606,7 @@ 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 @@ -616,7 +616,7 @@ class OrderedDictionaryTests: CollectionTestCase { 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 + d.updateValue(forKey: key, default: fallback) { value in expectEqual(value, values[offset]) value = replacement } @@ -633,7 +633,7 @@ 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 @@ -644,7 +644,7 @@ class OrderedDictionaryTests: CollectionTestCase { withEvery("offset", in: 0 ..< count) { offset in withHiddenCopies(if: isShared, of: &d) { 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] } @@ -661,7 +661,7 @@ 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 @@ -672,7 +672,7 @@ class OrderedDictionaryTests: CollectionTestCase { 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 + d.updateValue(forKey: key, insertingDefault: fallback, at: 0) { v in expectEqual(v, value) v = replacement } @@ -689,7 +689,7 @@ 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 @@ -701,7 +701,7 @@ class OrderedDictionaryTests: CollectionTestCase { 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 + d.updateValue(forKey: key, insertingDefault: fallback, at: 0) { v in expectEqual(v, fallback) v = value } From 1de0da557950d2457a104b096593529f3e5c2866 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 19 Aug 2021 18:54:00 -0700 Subject: [PATCH 10/54] Add Benchmarks package to workspace (#93) --- swift-collections.xcworkspace/contents.xcworkspacedata | 3 +++ 1 file changed, 3 insertions(+) diff --git a/swift-collections.xcworkspace/contents.xcworkspacedata b/swift-collections.xcworkspace/contents.xcworkspacedata index 030db5a6..ebc3e9df 100644 --- a/swift-collections.xcworkspace/contents.xcworkspacedata +++ b/swift-collections.xcworkspace/contents.xcworkspacedata @@ -4,6 +4,9 @@ + + From 4d695b9ccf07c4615ab779bf4e7c5ec3d5a97c83 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 19 Aug 2021 18:56:31 -0700 Subject: [PATCH 11/54] [OrderedDictionary] Deprecate `subscript(offset:)` for now (#92) * [OrderedDictionary] Deprecate index(forKey:), subscript(offset:) and friends for now * [OrderedDictionary] Update tests * Update benchmarks * Un-deprecate index(forKey:) --- .../AssertionContexts/Assertions.swift | 14 + .../OrderedDictionary+Deprecations.swift | 25 +- ...deredDictionary+Elements+SubSequence.swift | 2 +- .../OrderedDictionary/OrderedDictionary.swift | 14 - .../OrderedDictionary Tests.swift | 345 +++++++----------- .../OrderedDictionary Utils.swift | 5 +- .../OrderedDictionary+Elements Tests.swift | 158 ++++---- .../OrderedDictionary+Values Tests.swift | 59 +-- 8 files changed, 261 insertions(+), 361 deletions(-) diff --git a/Sources/CollectionsTestSupport/AssertionContexts/Assertions.swift b/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/OrderedCollections/OrderedDictionary/OrderedDictionary+Deprecations.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Deprecations.swift index 654418e2..04fbaa76 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Deprecations.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Deprecations.swift @@ -10,7 +10,27 @@ //===----------------------------------------------------------------------===// extension OrderedDictionary { - @available(*, deprecated, renamed: "updateValue(forKey:default:with:)") + /// 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) + @available(*, deprecated, // since 0.0.6 + message: "Please use `elements[offset]`") + @inlinable + @inline(__always) + public subscript(offset offset: Int) -> Element { + (_keys[offset], _values[offset]) + } +} + +extension OrderedDictionary { + // Deprecated since 0.0.6 + @available(*, deprecated, // since 0.0.6 + renamed: "updateValue(forKey:default:with:)") @inlinable public mutating func modifyValue( forKey key: Key, @@ -20,7 +40,8 @@ extension OrderedDictionary { try self.updateValue(forKey: key, default: defaultValue(), with: body) } - @available(*, deprecated, renamed: "updateValue(forKey:insertingDefault:at:with:)") + @available(*, deprecated, // since 0.0.6 + renamed: "updateValue(forKey:insertingDefault:at:with:)") @inlinable public mutating func modifyValue( forKey key: Key, diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements+SubSequence.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements+SubSequence.swift index 86135cc5..706f28a3 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements+SubSequence.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements+SubSequence.swift @@ -290,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.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift index d30a4335..08833e03 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift @@ -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 { diff --git a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift index 9b8ffde7..9b353ff8 100644 --- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift @@ -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,14 +213,14 @@ class OrderedDictionaryTests: CollectionTestCase { } } + @available(*, deprecated) func test_subscript_offset() { 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 let item = d[offset: offset] - expectEqual(item.key, keys[offset]) - expectEqual(item.value, values[offset]) + expectEqual(item, reference[offset]) } } } @@ -229,9 +229,9 @@ class OrderedDictionaryTests: CollectionTestCase { 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 +244,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]) - } + d[reference[offset].key] = replacement + reference[offset].value = replacement + expectEqualElements(d, reference) } } } @@ -266,16 +262,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) + var (d, reference) = 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]) - } + d[reference[offset].key] = nil + reference.remove(at: offset) + expectEqualElements(d, reference) } } } @@ -289,15 +280,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 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 +297,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 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 +320,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]) - } + mutate(&d[reference[offset].key]) { $0 = replacement } + reference[offset].value = replacement + expectEqualElements(d, reference) } } } @@ -358,20 +338,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) withHiddenCopies(if: isShared, of: &d) { d in - let key = keys[offset] + 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,6 +359,7 @@ 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 @@ -393,11 +368,7 @@ class OrderedDictionaryTests: CollectionTestCase { 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,7 +380,7 @@ 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 mutate(&d[key]) { v in @@ -417,11 +388,7 @@ class OrderedDictionaryTests: CollectionTestCase { 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 +398,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 +420,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] + 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,6 +444,7 @@ 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 @@ -491,11 +455,7 @@ class OrderedDictionaryTests: CollectionTestCase { 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 +468,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] + 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,6 +489,7 @@ 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 @@ -540,11 +497,7 @@ class OrderedDictionaryTests: CollectionTestCase { 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 +510,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] + 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,6 +533,7 @@ 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 @@ -594,11 +544,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)) } } } @@ -611,21 +557,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: -2) withHiddenCopies(if: isShared, of: &d) { d in - let key = keys[offset] + let key = reference[offset].key d.updateValue(forKey: key, default: fallback) { value in - expectEqual(value, values[offset]) + 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) } } } @@ -639,6 +581,7 @@ 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: -2) withEvery("offset", in: 0 ..< count) { offset in @@ -649,11 +592,7 @@ class OrderedDictionaryTests: CollectionTestCase { 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)) } } } @@ -666,22 +605,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: -2) withHiddenCopies(if: isShared, of: &d) { d in - let key = keys[offset] - let value = values[offset] + 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) } } } @@ -695,22 +629,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: -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] + 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 +653,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) + var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) withHiddenCopies(if: isShared, of: &d) { d in - let key = keys.remove(at: offset) - let expected = values.remove(at: offset) + 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 +963,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) + var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) + reference.swapAt(i, j) withHiddenCopies(if: isShared, of: &d) { 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 +984,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 } + let expectedPivot = reference.partition { $0.key.payload < count / 2 } withHiddenCopies(if: isShared, of: &d) { d in let actualPivot = d.partition { $0.key.payload < count / 2 } expectEqual(actualPivot, expectedPivot) - expectEqualElements(d, items) + expectEqualElements(d, reference) } } } @@ -1082,13 +1004,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 }) + reference.sort(by: { $0.key < $1.key }) withHiddenCopies(if: isShared, of: &d) { d in d.sort() - expectEqualElements(d, items) + expectEqualElements(d, reference) } } } @@ -1102,13 +1023,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 }) + reference.sort(by: { $0.key > $1.key }) withHiddenCopies(if: isShared, of: &d) { d in d.sort(by: { $0.key > $1.key }) - expectEqualElements(d, items) + expectEqualElements(d, reference) } } } @@ -1165,12 +1085,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)) + var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) withHiddenCopies(if: isShared, of: &d) { d in - items.reverse() + reference.reverse() d.reverse() - expectEqualElements(d, items) + expectEqualElements(d, reference) } } } @@ -1181,7 +1100,7 @@ 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) withHiddenCopies(if: isShared, of: &d) { d in d.removeAll() expectEqual(d.keys.__unstable.scale, 0) @@ -1196,7 +1115,7 @@ 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 d.removeAll(keepingCapacity: true) @@ -1213,16 +1132,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) + var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) withHiddenCopies(if: isShared, of: &d) { 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 +1151,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) + var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) withHiddenCopies(if: isShared, of: &d) { 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 +1183,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 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 +1200,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 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 +1219,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) + var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) withHiddenCopies(if: isShared, of: &d) { 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 +1236,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) + var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) withHiddenCopies(if: isShared, of: &d) { 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 +1253,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) } + var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) withHiddenCopies(if: isShared, of: &d) { 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 +1268,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..93b22a36 100644 --- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Utils.swift +++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Utils.swift @@ -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..a5105eee 100644 --- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Elements Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Elements Tests.swift @@ -18,9 +18,8 @@ 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) + var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) + reference.swapAt(i, j) withHiddenCopies(if: isShared, of: &d) { 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 } + let expectedPivot = reference.partition { $0.key.payload < count / 2 } withHiddenCopies(if: isShared, of: &d) { 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 }) + reference.sort(by: { $0.key < $1.key }) withHiddenCopies(if: isShared, of: &d) { 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 }) + reference.sort(by: { $0.key > $1.key }) withHiddenCopies(if: isShared, of: &d) { d in d.elements.sort(by: { $0.key > $1.key }) - expectEqualElements(d, items) + expectEqualElements(d, reference) } } } @@ -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)) + var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) withHiddenCopies(if: isShared, of: &d) { d in - items.reverse() + reference.reverse() d.elements.reverse() - expectEqualElements(d, items) + expectEqualElements(d, reference) } } } @@ -288,7 +285,7 @@ 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) withHiddenCopies(if: isShared, of: &d) { d in d.elements.removeAll() expectEqual(d.keys.__unstable.scale, 0) @@ -303,7 +300,7 @@ 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 d.elements.removeAll(keepingCapacity: true) @@ -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) + var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) withHiddenCopies(if: isShared, of: &d) { 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) + var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) withHiddenCopies(if: isShared, of: &d) { 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 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 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) + var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) withHiddenCopies(if: isShared, of: &d) { 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) + var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) withHiddenCopies(if: isShared, of: &d) { 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) } + var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) withHiddenCopies(if: isShared, of: &d) { 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..bed5a94d 100644 --- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Values Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Values Tests.swift @@ -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 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) + 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) { 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 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,7 +136,7 @@ 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 @@ -139,7 +144,7 @@ class OrderedDictionaryValueTests: CollectionTestCase { Array(buffer) } } - expectEqualElements(actual, values) + expectEqualElements(actual, reference.map { $0.value }) } } } @@ -149,7 +154,7 @@ 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 = @@ -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,7 +182,7 @@ 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 = @@ -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 { } } } - - } From 85a207063b44625d5d816ef765d6bc9acb60075c Mon Sep 17 00:00:00 2001 From: ejmarchant Date: Tue, 17 Aug 2021 19:54:30 +0100 Subject: [PATCH 12/54] Fix typos: missing subscript parameters (#81) * Fix typos: missing subscript parameters * Fix typos: more missing subscript parameters * Improve symbol documentation --- .../OrderedDictionary+Elements+SubSequence.swift | 13 +++++++------ .../OrderedDictionary+Elements.swift | 4 ++-- .../OrderedDictionary/OrderedDictionary.swift | 2 +- 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements+SubSequence.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements+SubSequence.swift index 542defb3..86135cc5 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. diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift index a04799ad..cf872e83 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. diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift index 3b322743..648b0c6c 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift @@ -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. From 5ff8c003b0a353ca5b49a8b1b557474b17fd5a2a Mon Sep 17 00:00:00 2001 From: ejmarchant Date: Mon, 16 Aug 2021 21:37:05 +0100 Subject: [PATCH 13/54] Fix documentation for types conforming to ExpressibleByArrayLiteral or ExpressibleByDictionaryLiteral (#82) # Conflicts: # Sources/PriorityQueueModule/Heap+ExpressibleByArrayLiteral.swift --- .../DequeModule/Deque+ExpressibleByArrayLiteral.swift | 6 +++--- ...eredDictionary+ExpressibleByDictionaryLiteral.swift | 9 +++------ .../OrderedSet+ExpressibleByArrayLiteral.swift | 10 +++++----- 3 files changed, 11 insertions(+), 14 deletions(-) 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/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/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. From 6b86e2cf4af03745c8ac607c7cccc61fcc8acb2a Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 19 Aug 2021 11:42:14 -0700 Subject: [PATCH 14/54] Stop depending on swift-collections-benchmark (#86) * Stop depending on swift-collections-benchmark Instead, move the benchmark suite into its own private nested package, under `Benchmarks/`. The recommended way to build & run benchmarks is via the `Utils/run-benchmarks.sh` script, which continues to work as before with this change. * Delete top-level Package.resolved file # Conflicts: # .swiftpm/xcode/xcshareddata/xcschemes/swift-collections-benchmark.xcscheme # Package.swift --- .gitignore | 2 + .../swift-collections-benchmark.xcscheme | 101 ------------------ .../Package.resolved | 4 +- Benchmarks/Package.swift | 47 ++++++++ .../main.swift | 0 Package.swift | 32 +----- Utils/run-benchmarks.sh | 4 +- 7 files changed, 54 insertions(+), 136 deletions(-) delete mode 100644 .swiftpm/xcode/xcshareddata/xcschemes/swift-collections-benchmark.xcscheme rename Package.resolved => Benchmarks/Package.resolved (89%) create mode 100644 Benchmarks/Package.swift rename Benchmarks/{swift-collections-benchmark => benchmark-tool}/main.swift (100%) 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/swift-collections-benchmark.xcscheme b/.swiftpm/xcode/xcshareddata/xcschemes/swift-collections-benchmark.xcscheme deleted file mode 100644 index 482d3d98..00000000 --- a/.swiftpm/xcode/xcshareddata/xcschemes/swift-collections-benchmark.xcscheme +++ /dev/null @@ -1,101 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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/Package.swift b/Package.swift index d5825439..a0b96a8a 100644 --- a/Package.swift +++ b/Package.swift @@ -55,10 +55,6 @@ let package = Package( .library(name: "DequeModule", targets: ["DequeModule"]), .library(name: "OrderedCollections", targets: ["OrderedCollections"]), ], - 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", @@ -86,31 +82,6 @@ let package = Package( dependencies: ["CollectionsTestSupport"], swiftSettings: settings), - // Benchmarking - .target( - name: "Benchmarks", - dependencies: [ - .product(name: "CollectionsBenchmark", package: "swift-collections-benchmark"), - "CppBenchmarks", - "Collections", - ], - 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", @@ -130,6 +101,5 @@ let package = Package( name: "OrderedCollectionsTests", dependencies: ["OrderedCollections", "CollectionsTestSupport"], swiftSettings: settings), - ], - cxxLanguageStandard: .cxx1z + ] ) 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 From 1e68069c98c16ecf367ee2079a607401d764edd3 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 19 Aug 2021 15:42:17 -0700 Subject: [PATCH 15/54] =?UTF-8?q?[OrderedDictionary]=20modifyValue=20?= =?UTF-8?q?=E2=86=92=20updateValue=20(#91)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [OrderedDictionary] modifyValue → updateValue * Update CMakeLists.txt --- Documentation/OrderedDictionary.md | 4 +- Sources/OrderedCollections/CMakeLists.txt | 7 ++-- .../OrderedDictionary+Deprecations.swift | 37 +++++++++++++++++++ .../OrderedDictionary+Initializers.swift | 2 +- .../OrderedDictionary/OrderedDictionary.swift | 16 ++++---- .../OrderedDictionary Tests.swift | 16 ++++---- 6 files changed, 60 insertions(+), 22 deletions(-) create mode 100644 Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Deprecations.swift 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/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+Deprecations.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Deprecations.swift new file mode 100644 index 00000000..654418e2 --- /dev/null +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Deprecations.swift @@ -0,0 +1,37 @@ +//===----------------------------------------------------------------------===// +// +// 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 { + @available(*, deprecated, renamed: "updateValue(forKey:default:with:)") + @inlinable + public mutating func modifyValue( + forKey key: Key, + default defaultValue: @autoclosure () -> Value, + _ body: (inout Value) throws -> R + ) rethrows -> R { + try self.updateValue(forKey: key, default: defaultValue(), with: body) + } + + @available(*, deprecated, 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 { + try self.updateValue( + forKey: key, + insertingDefault: defaultValue(), + at: index, + with: body) + } +} diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Initializers.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Initializers.swift index 1d27adaa..fb8c26c3 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) } } diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift index 648b0c6c..d30a4335 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 /// } /// } @@ -641,7 +641,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 +660,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 +687,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 +706,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/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift index c940cdd6..9b8ffde7 100644 --- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift @@ -606,7 +606,7 @@ 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 @@ -616,7 +616,7 @@ class OrderedDictionaryTests: CollectionTestCase { 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 + d.updateValue(forKey: key, default: fallback) { value in expectEqual(value, values[offset]) value = replacement } @@ -633,7 +633,7 @@ 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 @@ -644,7 +644,7 @@ class OrderedDictionaryTests: CollectionTestCase { withEvery("offset", in: 0 ..< count) { offset in withHiddenCopies(if: isShared, of: &d) { 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] } @@ -661,7 +661,7 @@ 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 @@ -672,7 +672,7 @@ class OrderedDictionaryTests: CollectionTestCase { 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 + d.updateValue(forKey: key, insertingDefault: fallback, at: 0) { v in expectEqual(v, value) v = replacement } @@ -689,7 +689,7 @@ 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 @@ -701,7 +701,7 @@ class OrderedDictionaryTests: CollectionTestCase { 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 + d.updateValue(forKey: key, insertingDefault: fallback, at: 0) { v in expectEqual(v, fallback) v = value } From 0bf9755eb6090ed7117bbd6108714ba430899442 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 19 Aug 2021 18:54:00 -0700 Subject: [PATCH 16/54] Add Benchmarks package to workspace (#93) --- swift-collections.xcworkspace/contents.xcworkspacedata | 3 +++ 1 file changed, 3 insertions(+) diff --git a/swift-collections.xcworkspace/contents.xcworkspacedata b/swift-collections.xcworkspace/contents.xcworkspacedata index 030db5a6..ebc3e9df 100644 --- a/swift-collections.xcworkspace/contents.xcworkspacedata +++ b/swift-collections.xcworkspace/contents.xcworkspacedata @@ -4,6 +4,9 @@ + + From 9d8719c8bebdc79740b6969c912ac706eb721d7a Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 19 Aug 2021 18:56:31 -0700 Subject: [PATCH 17/54] [OrderedDictionary] Deprecate `subscript(offset:)` for now (#92) * [OrderedDictionary] Deprecate index(forKey:), subscript(offset:) and friends for now * [OrderedDictionary] Update tests * Update benchmarks * Un-deprecate index(forKey:) --- .../AssertionContexts/Assertions.swift | 14 + .../OrderedDictionary+Deprecations.swift | 25 +- ...deredDictionary+Elements+SubSequence.swift | 2 +- .../OrderedDictionary/OrderedDictionary.swift | 14 - .../OrderedDictionary Tests.swift | 345 +++++++----------- .../OrderedDictionary Utils.swift | 5 +- .../OrderedDictionary+Elements Tests.swift | 158 ++++---- .../OrderedDictionary+Values Tests.swift | 59 +-- 8 files changed, 261 insertions(+), 361 deletions(-) diff --git a/Sources/CollectionsTestSupport/AssertionContexts/Assertions.swift b/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/OrderedCollections/OrderedDictionary/OrderedDictionary+Deprecations.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Deprecations.swift index 654418e2..04fbaa76 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Deprecations.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Deprecations.swift @@ -10,7 +10,27 @@ //===----------------------------------------------------------------------===// extension OrderedDictionary { - @available(*, deprecated, renamed: "updateValue(forKey:default:with:)") + /// 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) + @available(*, deprecated, // since 0.0.6 + message: "Please use `elements[offset]`") + @inlinable + @inline(__always) + public subscript(offset offset: Int) -> Element { + (_keys[offset], _values[offset]) + } +} + +extension OrderedDictionary { + // Deprecated since 0.0.6 + @available(*, deprecated, // since 0.0.6 + renamed: "updateValue(forKey:default:with:)") @inlinable public mutating func modifyValue( forKey key: Key, @@ -20,7 +40,8 @@ extension OrderedDictionary { try self.updateValue(forKey: key, default: defaultValue(), with: body) } - @available(*, deprecated, renamed: "updateValue(forKey:insertingDefault:at:with:)") + @available(*, deprecated, // since 0.0.6 + renamed: "updateValue(forKey:insertingDefault:at:with:)") @inlinable public mutating func modifyValue( forKey key: Key, diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements+SubSequence.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements+SubSequence.swift index 86135cc5..706f28a3 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements+SubSequence.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements+SubSequence.swift @@ -290,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.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift index d30a4335..08833e03 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift @@ -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 { diff --git a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift index 9b8ffde7..9b353ff8 100644 --- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift @@ -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,14 +213,14 @@ class OrderedDictionaryTests: CollectionTestCase { } } + @available(*, deprecated) func test_subscript_offset() { 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 let item = d[offset: offset] - expectEqual(item.key, keys[offset]) - expectEqual(item.value, values[offset]) + expectEqual(item, reference[offset]) } } } @@ -229,9 +229,9 @@ class OrderedDictionaryTests: CollectionTestCase { 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 +244,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]) - } + d[reference[offset].key] = replacement + reference[offset].value = replacement + expectEqualElements(d, reference) } } } @@ -266,16 +262,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) + var (d, reference) = 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]) - } + d[reference[offset].key] = nil + reference.remove(at: offset) + expectEqualElements(d, reference) } } } @@ -289,15 +280,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 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 +297,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 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 +320,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]) - } + mutate(&d[reference[offset].key]) { $0 = replacement } + reference[offset].value = replacement + expectEqualElements(d, reference) } } } @@ -358,20 +338,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) withHiddenCopies(if: isShared, of: &d) { d in - let key = keys[offset] + 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,6 +359,7 @@ 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 @@ -393,11 +368,7 @@ class OrderedDictionaryTests: CollectionTestCase { 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,7 +380,7 @@ 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 mutate(&d[key]) { v in @@ -417,11 +388,7 @@ class OrderedDictionaryTests: CollectionTestCase { 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 +398,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 +420,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] + 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,6 +444,7 @@ 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 @@ -491,11 +455,7 @@ class OrderedDictionaryTests: CollectionTestCase { 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 +468,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] + 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,6 +489,7 @@ 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 @@ -540,11 +497,7 @@ class OrderedDictionaryTests: CollectionTestCase { 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 +510,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] + 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,6 +533,7 @@ 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 @@ -594,11 +544,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)) } } } @@ -611,21 +557,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: -2) withHiddenCopies(if: isShared, of: &d) { d in - let key = keys[offset] + let key = reference[offset].key d.updateValue(forKey: key, default: fallback) { value in - expectEqual(value, values[offset]) + 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) } } } @@ -639,6 +581,7 @@ 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: -2) withEvery("offset", in: 0 ..< count) { offset in @@ -649,11 +592,7 @@ class OrderedDictionaryTests: CollectionTestCase { 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)) } } } @@ -666,22 +605,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: -2) withHiddenCopies(if: isShared, of: &d) { d in - let key = keys[offset] - let value = values[offset] + 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) } } } @@ -695,22 +629,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: -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] + 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 +653,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) + var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) withHiddenCopies(if: isShared, of: &d) { d in - let key = keys.remove(at: offset) - let expected = values.remove(at: offset) + 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 +963,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) + var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) + reference.swapAt(i, j) withHiddenCopies(if: isShared, of: &d) { 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 +984,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 } + let expectedPivot = reference.partition { $0.key.payload < count / 2 } withHiddenCopies(if: isShared, of: &d) { d in let actualPivot = d.partition { $0.key.payload < count / 2 } expectEqual(actualPivot, expectedPivot) - expectEqualElements(d, items) + expectEqualElements(d, reference) } } } @@ -1082,13 +1004,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 }) + reference.sort(by: { $0.key < $1.key }) withHiddenCopies(if: isShared, of: &d) { d in d.sort() - expectEqualElements(d, items) + expectEqualElements(d, reference) } } } @@ -1102,13 +1023,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 }) + reference.sort(by: { $0.key > $1.key }) withHiddenCopies(if: isShared, of: &d) { d in d.sort(by: { $0.key > $1.key }) - expectEqualElements(d, items) + expectEqualElements(d, reference) } } } @@ -1165,12 +1085,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)) + var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) withHiddenCopies(if: isShared, of: &d) { d in - items.reverse() + reference.reverse() d.reverse() - expectEqualElements(d, items) + expectEqualElements(d, reference) } } } @@ -1181,7 +1100,7 @@ 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) withHiddenCopies(if: isShared, of: &d) { d in d.removeAll() expectEqual(d.keys.__unstable.scale, 0) @@ -1196,7 +1115,7 @@ 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 d.removeAll(keepingCapacity: true) @@ -1213,16 +1132,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) + var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) withHiddenCopies(if: isShared, of: &d) { 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 +1151,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) + var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) withHiddenCopies(if: isShared, of: &d) { 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 +1183,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 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 +1200,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 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 +1219,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) + var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) withHiddenCopies(if: isShared, of: &d) { 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 +1236,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) + var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) withHiddenCopies(if: isShared, of: &d) { 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 +1253,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) } + var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) withHiddenCopies(if: isShared, of: &d) { 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 +1268,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..93b22a36 100644 --- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Utils.swift +++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Utils.swift @@ -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..a5105eee 100644 --- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Elements Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Elements Tests.swift @@ -18,9 +18,8 @@ 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) + var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) + reference.swapAt(i, j) withHiddenCopies(if: isShared, of: &d) { 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 } + let expectedPivot = reference.partition { $0.key.payload < count / 2 } withHiddenCopies(if: isShared, of: &d) { 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 }) + reference.sort(by: { $0.key < $1.key }) withHiddenCopies(if: isShared, of: &d) { 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 }) + reference.sort(by: { $0.key > $1.key }) withHiddenCopies(if: isShared, of: &d) { d in d.elements.sort(by: { $0.key > $1.key }) - expectEqualElements(d, items) + expectEqualElements(d, reference) } } } @@ -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)) + var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) withHiddenCopies(if: isShared, of: &d) { d in - items.reverse() + reference.reverse() d.elements.reverse() - expectEqualElements(d, items) + expectEqualElements(d, reference) } } } @@ -288,7 +285,7 @@ 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) withHiddenCopies(if: isShared, of: &d) { d in d.elements.removeAll() expectEqual(d.keys.__unstable.scale, 0) @@ -303,7 +300,7 @@ 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 d.elements.removeAll(keepingCapacity: true) @@ -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) + var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) withHiddenCopies(if: isShared, of: &d) { 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) + var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) withHiddenCopies(if: isShared, of: &d) { 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 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 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) + var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) withHiddenCopies(if: isShared, of: &d) { 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) + var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) withHiddenCopies(if: isShared, of: &d) { 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) } + var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) withHiddenCopies(if: isShared, of: &d) { 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..bed5a94d 100644 --- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Values Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Values Tests.swift @@ -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 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) + 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) { 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 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,7 +136,7 @@ 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 @@ -139,7 +144,7 @@ class OrderedDictionaryValueTests: CollectionTestCase { Array(buffer) } } - expectEqualElements(actual, values) + expectEqualElements(actual, reference.map { $0.value }) } } } @@ -149,7 +154,7 @@ 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 = @@ -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,7 +182,7 @@ 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 = @@ -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 { } } } - - } From 215ed903864e1d51948ea18807de570c96755318 Mon Sep 17 00:00:00 2001 From: Edward Marchant Date: Fri, 27 Aug 2021 09:59:48 +0100 Subject: [PATCH 18/54] Documentation: Remove in-place mutation comments --- .../OrderedDictionary/OrderedDictionary+Deprecations.swift | 3 +-- .../OrderedDictionary/OrderedDictionary+Elements.swift | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Deprecations.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Deprecations.swift index 04fbaa76..c57b4fec 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Deprecations.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Deprecations.swift @@ -10,8 +10,7 @@ //===----------------------------------------------------------------------===// extension OrderedDictionary { - /// Accesses the element at the specified index. This can be used to - /// perform in-place mutations on dictionary values. + /// 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 diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift index cf872e83..d0507640 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift @@ -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`. From 56b82b1b7f0212cf0ceaee4dc010d605adef80f3 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 30 Aug 2021 13:25:58 -0700 Subject: [PATCH 19/54] Freeze some types for consistency with their inlinable initializers Note: @frozen does *not* mean that we actually consider these struct types frozen. Their layout may arbitrarily change between even minor releases. --- Sources/DequeModule/Deque+Collection.swift | 1 + Sources/DequeModule/Deque._Storage.swift | 1 + Sources/DequeModule/Deque._UnsafeHandle.swift | 1 + Sources/DequeModule/_DequeBuffer.swift | 1 + Sources/DequeModule/_UnsafeWrappedBuffer.swift | 2 ++ .../OrderedSet/OrderedSet+UnorderedView.swift | 1 + 6 files changed, 7 insertions(+) diff --git a/Sources/DequeModule/Deque+Collection.swift b/Sources/DequeModule/Deque+Collection.swift index d8884662..e1614b6a 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 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/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 From 0e9e7f13e4c2170b2086dbffd1d16c6397d3d50f Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 30 Aug 2021 13:25:58 -0700 Subject: [PATCH 20/54] Freeze some types for consistency with their inlinable initializers Note: @frozen does *not* mean that we actually consider these struct types frozen. Their layout may arbitrarily change between even minor releases. --- Sources/DequeModule/Deque+Collection.swift | 1 + Sources/DequeModule/Deque._Storage.swift | 1 + Sources/DequeModule/Deque._UnsafeHandle.swift | 1 + Sources/DequeModule/_DequeBuffer.swift | 1 + Sources/DequeModule/_UnsafeWrappedBuffer.swift | 2 ++ .../OrderedSet/OrderedSet+UnorderedView.swift | 1 + 6 files changed, 7 insertions(+) diff --git a/Sources/DequeModule/Deque+Collection.swift b/Sources/DequeModule/Deque+Collection.swift index d8884662..e1614b6a 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 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/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 From 837a273befc55752ad3b06a994b44ae1d6980cde Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 30 Aug 2021 15:15:47 -0700 Subject: [PATCH 21/54] Also freeze Heap types --- Sources/PriorityQueueModule/Heap+OrderedViews.swift | 2 ++ Sources/PriorityQueueModule/Heap.swift | 1 + 2 files changed, 3 insertions(+) diff --git a/Sources/PriorityQueueModule/Heap+OrderedViews.swift b/Sources/PriorityQueueModule/Heap+OrderedViews.swift index bf6536c8..18b6c53f 100644 --- a/Sources/PriorityQueueModule/Heap+OrderedViews.swift +++ b/Sources/PriorityQueueModule/Heap+OrderedViews.swift @@ -12,6 +12,7 @@ extension Heap { /// A view of a `Heap`'s elements, as a `Sequence` from the smallest to /// largest element. + @frozen public struct AscendingView: Sequence, IteratorProtocol { @usableFromInline internal var _base: Heap @@ -30,6 +31,7 @@ extension Heap { /// A view of a `Heap`'s elements, as a `Sequence` from the largest to /// smallest element. + @frozen public struct DescendingView: Sequence, IteratorProtocol { @usableFromInline internal var _base: Heap diff --git a/Sources/PriorityQueueModule/Heap.swift b/Sources/PriorityQueueModule/Heap.swift index cd1c3f8e..1f6f3d83 100644 --- a/Sources/PriorityQueueModule/Heap.swift +++ b/Sources/PriorityQueueModule/Heap.swift @@ -23,6 +23,7 @@ /// "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: ContiguousArray From 5762a3a50cd0ed880f6c5069edf4afa1b9f14cad Mon Sep 17 00:00:00 2001 From: ejmarchant Date: Mon, 30 Aug 2021 23:32:50 +0100 Subject: [PATCH 22/54] Follow stdlib's leading underscore rule (#95) --- .../OrderedDictionary+Elements+SubSequence.swift | 10 +++++----- .../OrderedSet/OrderedSet+RandomAccessCollection.swift | 2 +- .../OrderedSet/OrderedSet+SubSequence.swift | 6 +++--- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements+SubSequence.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements+SubSequence.swift index 706f28a3..ee7ccc1e 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements+SubSequence.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements+SubSequence.swift @@ -96,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 @@ -118,7 +118,7 @@ extension OrderedDictionary.Elements.SubSequence: Sequence { @inlinable @inline(__always) public func makeIterator() -> Iterator { - Iterator(self) + Iterator(_base: self) } } 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. From 751ae1b08be15df7c21077ad6ba235ee93ed6d74 Mon Sep 17 00:00:00 2001 From: Edward Marchant Date: Fri, 27 Aug 2021 09:59:48 +0100 Subject: [PATCH 23/54] Documentation: Remove in-place mutation comments --- .../OrderedDictionary/OrderedDictionary+Deprecations.swift | 3 +-- .../OrderedDictionary/OrderedDictionary+Elements.swift | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Deprecations.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Deprecations.swift index 04fbaa76..c57b4fec 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Deprecations.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Deprecations.swift @@ -10,8 +10,7 @@ //===----------------------------------------------------------------------===// extension OrderedDictionary { - /// Accesses the element at the specified index. This can be used to - /// perform in-place mutations on dictionary values. + /// 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 diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift index cf872e83..d0507640 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift @@ -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`. From 4c22d000656d9a9765da875fef1503f6b9755a88 Mon Sep 17 00:00:00 2001 From: ejmarchant Date: Mon, 30 Aug 2021 23:32:50 +0100 Subject: [PATCH 24/54] Follow stdlib's leading underscore rule (#95) --- .../OrderedDictionary+Elements+SubSequence.swift | 10 +++++----- .../OrderedSet/OrderedSet+RandomAccessCollection.swift | 2 +- .../OrderedSet/OrderedSet+SubSequence.swift | 6 +++--- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements+SubSequence.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements+SubSequence.swift index 706f28a3..ee7ccc1e 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements+SubSequence.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements+SubSequence.swift @@ -96,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 @@ -118,7 +118,7 @@ extension OrderedDictionary.Elements.SubSequence: Sequence { @inlinable @inline(__always) public func makeIterator() -> Iterator { - Iterator(self) + Iterator(_base: self) } } 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. From 01f11048418adef880202def4d7deaf66de8b773 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 1 Sep 2021 20:01:50 -0700 Subject: [PATCH 25/54] Move development .xcworkspace under Utils/ This (undocumented) workspace allows benchmark developers to work on the collection benchmarks and the benchmarking infrastructure within Xcode, with minimal pain. Moving it under Utils/ makes it easier to build the package with the xcodebuild utility; it also makes it (hopefully) clear that the workspace isn't source stable. --- .../contents.xcworkspacedata | 13 +++++++++++++ .../xcshareddata/IDETemplateMacros.plist | 0 .../xcshareddata/IDEWorkspaceChecks.plist | 0 .../xcshareddata/swiftpm/Package.resolved | 0 .../contents.xcworkspacedata | 13 ------------- 5 files changed, 13 insertions(+), 13 deletions(-) create mode 100644 Utils/swift-collections.xcworkspace/contents.xcworkspacedata rename {swift-collections.xcworkspace => Utils/swift-collections.xcworkspace}/xcshareddata/IDETemplateMacros.plist (100%) rename {swift-collections.xcworkspace => Utils/swift-collections.xcworkspace}/xcshareddata/IDEWorkspaceChecks.plist (100%) rename {swift-collections.xcworkspace => Utils/swift-collections.xcworkspace}/xcshareddata/swiftpm/Package.resolved (100%) delete mode 100644 swift-collections.xcworkspace/contents.xcworkspacedata 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/swift-collections.xcworkspace/contents.xcworkspacedata b/swift-collections.xcworkspace/contents.xcworkspacedata deleted file mode 100644 index ebc3e9df..00000000 --- a/swift-collections.xcworkspace/contents.xcworkspacedata +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - From f1f48d569aa3628c719a68fb174d7350a773a001 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 3 Sep 2021 15:57:09 -0700 Subject: [PATCH 26/54] =?UTF-8?q?[test]=20CollectionsTestSupport=20?= =?UTF-8?q?=E2=86=92=20=5FCollectionsTestSupport?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The underscored module name makes it clear that this isn't public API. --- Package.swift | 8 ++++---- .../AssertionContexts/Assertions.swift | 0 .../AssertionContexts/CollectionTestCase.swift | 0 .../AssertionContexts/Combinatorics.swift | 0 .../AssertionContexts/TestContext.swift | 0 .../CheckBidirectionalCollection.swift | 0 .../ConformanceCheckers/CheckCollection.swift | 0 .../ConformanceCheckers/CheckComparable.swift | 0 .../ConformanceCheckers/CheckEquatable.swift | 0 .../ConformanceCheckers/CheckHashable.swift | 0 .../ConformanceCheckers/CheckSequence.swift | 0 .../MinimalTypes/MinimalBidirectionalCollection.swift | 0 .../MinimalTypes/MinimalCollection.swift | 0 .../MinimalTypes/MinimalDecoder.swift | 0 .../MinimalTypes/MinimalEncoder.swift | 0 .../MinimalTypes/MinimalIndex.swift | 0 .../MinimalTypes/MinimalIterator.swift | 0 .../MinimalMutableRandomAccessCollection.swift | 0 ...malMutableRangeReplaceableRandomAccessCollection.swift | 0 .../MinimalTypes/MinimalRandomAccessCollection.swift | 0 .../MinimalRangeReplaceableRandomAccessCollection.swift | 0 .../MinimalTypes/MinimalSequence.swift | 0 .../MinimalTypes/ResettableValue.swift | 0 .../MinimalTypes/StringConvertibleValue.swift | 0 .../MinimalTypes/_CollectionState.swift | 0 .../MinimalTypes/_MinimalCollectionCore.swift | 0 .../Utilities/Box.swift | 0 .../Utilities/HashableBox.swift | 0 .../Utilities/LifetimeTracked.swift | 0 .../Utilities/LifetimeTracker.swift | 0 .../Utilities/SeedableRandomNumberGenerator.swift | 0 .../MinimalTypeConformances.swift | 2 +- Tests/DequeTests/DequeInternals.swift | 2 +- Tests/DequeTests/DequeTests.swift | 2 +- Tests/DequeTests/MutableCollectionTests.swift | 2 +- Tests/DequeTests/RangeReplaceableCollectionTests.swift | 2 +- Tests/OrderedCollectionsTests/HashTable/BitsetTests.swift | 2 +- .../HashTable/HashTableTests.swift | 2 +- .../OrderedDictionary/OrderedDictionary Tests.swift | 2 +- .../OrderedDictionary/OrderedDictionary Utils.swift | 2 +- .../OrderedDictionary+Elements Tests.swift | 2 +- .../OrderedDictionary+Values Tests.swift | 2 +- .../OrderedSet/OrderedSet Diffing Tests.swift | 2 +- .../OrderedSet/OrderedSet.UnorderedView Tests.swift | 2 +- .../OrderedSet/OrderedSetInternals.swift | 2 +- .../OrderedSet/OrderedSetTests.swift | 2 +- 46 files changed, 19 insertions(+), 19 deletions(-) rename Sources/{CollectionsTestSupport => _CollectionsTestSupport}/AssertionContexts/Assertions.swift (100%) rename Sources/{CollectionsTestSupport => _CollectionsTestSupport}/AssertionContexts/CollectionTestCase.swift (100%) rename Sources/{CollectionsTestSupport => _CollectionsTestSupport}/AssertionContexts/Combinatorics.swift (100%) rename Sources/{CollectionsTestSupport => _CollectionsTestSupport}/AssertionContexts/TestContext.swift (100%) rename Sources/{CollectionsTestSupport => _CollectionsTestSupport}/ConformanceCheckers/CheckBidirectionalCollection.swift (100%) rename Sources/{CollectionsTestSupport => _CollectionsTestSupport}/ConformanceCheckers/CheckCollection.swift (100%) rename Sources/{CollectionsTestSupport => _CollectionsTestSupport}/ConformanceCheckers/CheckComparable.swift (100%) rename Sources/{CollectionsTestSupport => _CollectionsTestSupport}/ConformanceCheckers/CheckEquatable.swift (100%) rename Sources/{CollectionsTestSupport => _CollectionsTestSupport}/ConformanceCheckers/CheckHashable.swift (100%) rename Sources/{CollectionsTestSupport => _CollectionsTestSupport}/ConformanceCheckers/CheckSequence.swift (100%) rename Sources/{CollectionsTestSupport => _CollectionsTestSupport}/MinimalTypes/MinimalBidirectionalCollection.swift (100%) rename Sources/{CollectionsTestSupport => _CollectionsTestSupport}/MinimalTypes/MinimalCollection.swift (100%) rename Sources/{CollectionsTestSupport => _CollectionsTestSupport}/MinimalTypes/MinimalDecoder.swift (100%) rename Sources/{CollectionsTestSupport => _CollectionsTestSupport}/MinimalTypes/MinimalEncoder.swift (100%) rename Sources/{CollectionsTestSupport => _CollectionsTestSupport}/MinimalTypes/MinimalIndex.swift (100%) rename Sources/{CollectionsTestSupport => _CollectionsTestSupport}/MinimalTypes/MinimalIterator.swift (100%) rename Sources/{CollectionsTestSupport => _CollectionsTestSupport}/MinimalTypes/MinimalMutableRandomAccessCollection.swift (100%) rename Sources/{CollectionsTestSupport => _CollectionsTestSupport}/MinimalTypes/MinimalMutableRangeReplaceableRandomAccessCollection.swift (100%) rename Sources/{CollectionsTestSupport => _CollectionsTestSupport}/MinimalTypes/MinimalRandomAccessCollection.swift (100%) rename Sources/{CollectionsTestSupport => _CollectionsTestSupport}/MinimalTypes/MinimalRangeReplaceableRandomAccessCollection.swift (100%) rename Sources/{CollectionsTestSupport => _CollectionsTestSupport}/MinimalTypes/MinimalSequence.swift (100%) rename Sources/{CollectionsTestSupport => _CollectionsTestSupport}/MinimalTypes/ResettableValue.swift (100%) rename Sources/{CollectionsTestSupport => _CollectionsTestSupport}/MinimalTypes/StringConvertibleValue.swift (100%) rename Sources/{CollectionsTestSupport => _CollectionsTestSupport}/MinimalTypes/_CollectionState.swift (100%) rename Sources/{CollectionsTestSupport => _CollectionsTestSupport}/MinimalTypes/_MinimalCollectionCore.swift (100%) rename Sources/{CollectionsTestSupport => _CollectionsTestSupport}/Utilities/Box.swift (100%) rename Sources/{CollectionsTestSupport => _CollectionsTestSupport}/Utilities/HashableBox.swift (100%) rename Sources/{CollectionsTestSupport => _CollectionsTestSupport}/Utilities/LifetimeTracked.swift (100%) rename Sources/{CollectionsTestSupport => _CollectionsTestSupport}/Utilities/LifetimeTracker.swift (100%) rename Sources/{CollectionsTestSupport => _CollectionsTestSupport}/Utilities/SeedableRandomNumberGenerator.swift (100%) diff --git a/Package.swift b/Package.swift index a0b96a8a..52ecce53 100644 --- a/Package.swift +++ b/Package.swift @@ -68,7 +68,7 @@ let package = Package( // Testing support module .target( - name: "CollectionsTestSupport", + name: "_CollectionsTestSupport", dependencies: [], swiftSettings: settings, linkerSettings: [ @@ -79,7 +79,7 @@ let package = Package( ), .testTarget( name: "CollectionsTestSupportTests", - dependencies: ["CollectionsTestSupport"], + dependencies: ["_CollectionsTestSupport"], swiftSettings: settings), // Deque @@ -89,7 +89,7 @@ let package = Package( swiftSettings: settings), .testTarget( name: "DequeTests", - dependencies: ["DequeModule", "CollectionsTestSupport"], + dependencies: ["DequeModule", "_CollectionsTestSupport"], swiftSettings: settings), // OrderedSet, OrderedDictionary @@ -99,7 +99,7 @@ let package = Package( swiftSettings: settings), .testTarget( name: "OrderedCollectionsTests", - dependencies: ["OrderedCollections", "CollectionsTestSupport"], + dependencies: ["OrderedCollections", "_CollectionsTestSupport"], swiftSettings: settings), ] ) diff --git a/Sources/CollectionsTestSupport/AssertionContexts/Assertions.swift b/Sources/_CollectionsTestSupport/AssertionContexts/Assertions.swift similarity index 100% rename from Sources/CollectionsTestSupport/AssertionContexts/Assertions.swift rename to Sources/_CollectionsTestSupport/AssertionContexts/Assertions.swift 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 100% rename from Sources/CollectionsTestSupport/AssertionContexts/Combinatorics.swift rename to Sources/_CollectionsTestSupport/AssertionContexts/Combinatorics.swift 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 9b353ff8..1e6c37ef 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() { diff --git a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Utils.swift b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Utils.swift index 93b22a36..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 { diff --git a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Elements Tests.swift b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Elements Tests.swift index a5105eee..d46bace3 100644 --- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Elements Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Elements Tests.swift @@ -12,7 +12,7 @@ import XCTest @_spi(Testing) import OrderedCollections -import CollectionsTestSupport +import _CollectionsTestSupport class OrderedDictionaryElementsTests: CollectionTestCase { func test_elements_getter() { diff --git a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Values Tests.swift b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Values Tests.swift index bed5a94d..241c281a 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() { 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..bd37b11b 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() { From 6fbf99500669c77d2ab8b1b101f1f6e4e393f2b9 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 3 Sep 2021 15:58:19 -0700 Subject: [PATCH 27/54] [Utils] Add run-full-tests.sh script This script builds and tests the package a tiny fraction of the full support matrix. It's useful for prerelease testing. --- Utils/run-full-tests.sh | 128 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 128 insertions(+) create mode 100755 Utils/run-full-tests.sh diff --git a/Utils/run-full-tests.sh b/Utils/run-full-tests.sh new file mode 100755 index 00000000..c79a5364 --- /dev/null +++ b/Utils/run-full-tests.sh @@ -0,0 +1,128 @@ +#!/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. + +set -eu + +cd "$(dirname $0)/.." + +build_dir="$(mktemp -d "/tmp/$(basename $0).XXXXX")" +bold_on="$(tput bold)" +bold_off="$(tput sgr0)" + +spm_flags="" + +if [ "$(uname)" == "Darwin" ]; then + swift="xcrun swift" +else + swift="swift" + spm_flags="$spm_flags -j 1" +fi + +echo "Build output logs are saved in $bold_on$build_dir$bold_off" +swift --version + +report_failure() { + logs="$1" + echo " ${bold_on}Failed.${bold_off} See $logs for full console output." + tail -10 "$logs" + exit 1 +} + +_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)" + "$@" >"$output" 2>&1 || report_failure "$output" + end="$(date +%s)" + echo " Completed in $(($end - $start))s" +} + +# 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" + +if [ "$(uname)" = "Darwin" ]; then + # Build using xcodebuild + try "xcodebuild.build" \ + xcodebuild -scheme swift-collections-Package \ + -configuration Release \ + -destination "generic/platform=macOS" \ + -destination "generic/platform=macOS,variant=Mac Catalyst" \ + -destination "generic/platform=iOS" \ + -destination "generic/platform=iOS Simulator" \ + -destination "generic/platform=watchOS" \ + -destination "generic/platform=watchOS Simulator" \ + -destination "generic/platform=tvOS" \ + -destination "generic/platform=tvOS Simulator" \ + clean build + try "xcodebuild.test" \ + xcodebuild -scheme swift-collections-Package \ + -configuration Release \ + -destination "platform=macOS" \ + -destination "platform=macOS,variant=Mac Catalyst" \ + -destination "platform=iOS Simulator,name=iPhone 12" \ + -destination "platform=watchOS Simulator,name=Apple Watch Series 6 - 44mm" \ + -destination "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 From 9d4bb8cdf801f06ca4e3d1d1a4cf507ed8ad2f3b Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 3 Sep 2021 15:59:57 -0700 Subject: [PATCH 28/54] [OrderedDictionary] Remove deprecated API Mark the deprecated `subscript(offset:)` and `modifyValue(...)` APIs unavailable and replace their bodies with fatalError(). --- .../OrderedDictionary+Deprecations.swift | 23 ++++++++----------- .../OrderedDictionary Tests.swift | 13 ----------- 2 files changed, 9 insertions(+), 27 deletions(-) diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Deprecations.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Deprecations.swift index c57b4fec..a8e531d8 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Deprecations.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Deprecations.swift @@ -17,30 +17,29 @@ extension OrderedDictionary { /// `0` and less than `count`. /// /// - Complexity: O(1) - @available(*, deprecated, // since 0.0.6 - message: "Please use `elements[offset]`") + @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 { - (_keys[offset], _values[offset]) + fatalError() } } extension OrderedDictionary { - // Deprecated since 0.0.6 - @available(*, deprecated, // since 0.0.6 - renamed: "updateValue(forKey:default:with:)") + @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 { - try self.updateValue(forKey: key, default: defaultValue(), with: body) + fatalError() } - @available(*, deprecated, // since 0.0.6 - renamed: "updateValue(forKey:insertingDefault:at:with:)") + @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, @@ -48,10 +47,6 @@ extension OrderedDictionary { at index: Int, _ body: (inout Value) throws -> R ) rethrows -> R { - try self.updateValue( - forKey: key, - insertingDefault: defaultValue(), - at: index, - with: body) + fatalError() } } diff --git a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift index 1e6c37ef..34e7a7dd 100644 --- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift @@ -213,19 +213,6 @@ class OrderedDictionaryTests: CollectionTestCase { } } - @available(*, deprecated) - func test_subscript_offset() { - withEvery("count", in: 0 ..< 30) { count in - withLifetimeTracking { tracker in - let (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) - withEvery("offset", in: 0 ..< count) { offset in - let item = d[offset: offset] - expectEqual(item, reference[offset]) - } - } - } - } - func test_subscript_getter() { withEvery("count", in: 0 ..< 30) { count in withLifetimeTracking { tracker in From 9adbe3e87bfd2bba9730c390c7455d4df741ec70 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 3 Sep 2021 15:58:41 -0700 Subject: [PATCH 29/54] [docs] Add a release checklist --- Documentation/Internals/ReleaseChecklist.md | 58 +++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Documentation/Internals/ReleaseChecklist.md 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. From 4520853f49876e538855d07939ea0c6dcf371c96 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 3 Sep 2021 19:11:12 -0700 Subject: [PATCH 30/54] Update README for 1.0 --- Documentation/Internals/README.md | 119 +++++++++++++++++++ README.md | 182 ++++++++---------------------- 2 files changed, 165 insertions(+), 136 deletions(-) create mode 100644 Documentation/Internals/README.md 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/README.md b/README.md index 4f1d72a1..b01bc793 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ The package currently provides the following implementations: [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. +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 @@ -33,156 +33,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/Development/Internals/) 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. @@ -192,7 +106,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. @@ -201,7 +115,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. @@ -209,17 +123,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.) From 227710b76f7358cc6eb9fb9879e8407d2e26667a Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 3 Sep 2021 19:40:09 -0700 Subject: [PATCH 31/54] Update xcodebuild schemes --- .../swift-collections-Package.xcscheme | 91 ++++--------------- 1 file changed, 19 insertions(+), 72 deletions(-) diff --git a/.swiftpm/xcode/xcshareddata/xcschemes/swift-collections-Package.xcscheme b/.swiftpm/xcode/xcshareddata/xcschemes/swift-collections-Package.xcscheme index efc01154..ee12b5ed 100644 --- a/.swiftpm/xcode/xcshareddata/xcschemes/swift-collections-Package.xcscheme +++ b/.swiftpm/xcode/xcshareddata/xcschemes/swift-collections-Package.xcscheme @@ -48,62 +48,6 @@ ReferencedContainer = "container:"> - - - - - - - - - - - - - - - - + + + + - - - - - + - + From 8303a77bc2915be76777d6fc17b702146b6fb192 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 7 Sep 2021 14:51:02 -0700 Subject: [PATCH 32/54] [Utils] run-full-tests.sh: Add disclaimer about needing to tweak the script sometimes --- Utils/run-full-tests.sh | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Utils/run-full-tests.sh b/Utils/run-full-tests.sh index c79a5364..39d19335 100755 --- a/Utils/run-full-tests.sh +++ b/Utils/run-full-tests.sh @@ -13,6 +13,9 @@ # 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 From ead0916a2f4a0b3e8c601ad73ea16019916c2115 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 8 Sep 2021 11:47:47 -0700 Subject: [PATCH 33/54] [Heap] Disable heap tests in release builds (#100) These tests rely on @testable imports, which sadly won't work in optimized builds. --- Tests/PriorityQueueTests/HeapTests.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Tests/PriorityQueueTests/HeapTests.swift b/Tests/PriorityQueueTests/HeapTests.swift index 880e0c8a..ca326858 100644 --- a/Tests/PriorityQueueTests/HeapTests.swift +++ b/Tests/PriorityQueueTests/HeapTests.swift @@ -9,6 +9,7 @@ // //===----------------------------------------------------------------------===// +#if DEBUG import XCTest @testable import PriorityQueueModule @@ -419,3 +420,4 @@ final class HeapTests: XCTestCase { } } } +#endif From 1ae008a41098c134ac13caa3115c113a15d1a9e6 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 7 Sep 2021 14:53:08 -0700 Subject: [PATCH 34/54] [OrderedSet] Make _checkInvariants public and call it in more operations It seems useful to be able to manually call `_checkInvariants` while debugging a package issue. This is public as in `public`, not public as in Public API -- it's underscored. --- .../OrderedSet/OrderedSet+Invariants.swift | 2 +- ...rderedSet+Partial RangeReplaceableCollection.swift | 5 ++++- .../OrderedSet+Partial SetAlgebra+Operations.swift | 11 +++++++++-- .../OrderedSet/OrderedSet+Testing.swift | 3 +++ 4 files changed, 17 insertions(+), 4 deletions(-) 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+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() } } From e959a6452825f897040cb0ccd3d849f4f42c060f Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 8 Sep 2021 20:36:03 -0700 Subject: [PATCH 35/54] [OrderedDictionary] Add some more `_checkInvariants()` calls --- .../OrderedDictionary/OrderedDictionary+Codable.swift | 1 + .../OrderedDictionary/OrderedDictionary+Initializers.swift | 1 + .../OrderedDictionary+Partial MutableCollection.swift | 2 ++ ...OrderedDictionary+Partial RangeReplaceableCollection.swift | 1 + .../OrderedDictionary/OrderedDictionary.swift | 4 +++- 5 files changed, 8 insertions(+), 1 deletion(-) 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+Initializers.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Initializers.swift index fb8c26c3..568be28d 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Initializers.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Initializers.swift @@ -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 08833e03..1fe94039 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift @@ -350,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) { @@ -365,6 +365,7 @@ extension OrderedDictionary { case (nil, nil): // Noop break } + _checkInvariants() } _modify { let (index, bucket) = _keys._find(key) @@ -394,6 +395,7 @@ extension OrderedDictionary { case (nil, nil): // Noop break } + _checkInvariants() } yield &value From 96100d4b6ad61bbfbf549ee42dc73239325b353f Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 8 Sep 2021 21:10:01 -0700 Subject: [PATCH 36/54] [NFC] Cosmetic/doc updates --- .../OrderedSet/OrderedSet+Insertions.swift | 11 ++++++----- .../OrderedCollections/OrderedSet/OrderedSet.swift | 2 +- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Insertions.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Insertions.swift index e1037edf..3079a0ca 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() diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet.swift index 188d344c..ed850f0c 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet.swift @@ -250,7 +250,7 @@ public struct OrderedSet where Element: Hashable _ table: _HashTable? = nil ) { self.__storage = table?._storage - self._elements = ContiguousArray(_uniqueElements) + self._elements = _uniqueElements } @inlinable From e4f62c15208da97b605a89cd0a1c4feb8f3b1118 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 8 Sep 2021 21:31:14 -0700 Subject: [PATCH 37/54] [OrderedSet] Don't let the unchecked init create large sets with no hash table In debug builds, the `OrderedSet.init(uncheckedUniqueElements:)` initializer always created a set with no hash table, even if it had an element count >15. This is technically an invariant violation (caught by `_checkInvariants()`), although it generally only triggers (very) slow performance. (The set reverts to linear searching.) --- .../OrderedSet/OrderedSet+Initializers.swift | 27 +++++++++---------- 1 file changed, 12 insertions(+), 15 deletions(-) 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() } } From f69104b5071ef9a44112e3c4fef8904b5e8b6d73 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 8 Sep 2021 21:37:09 -0700 Subject: [PATCH 38/54] [OrderedSet] Don't set a default value for the primary initializer's second argument This will hopefully prevent issues like the one fixed in the previous commit from reoccurring in the future. --- Sources/OrderedCollections/OrderedSet/OrderedSet.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet.swift index ed850f0c..f39e0246 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet.swift @@ -247,7 +247,7 @@ public struct OrderedSet where Element: Hashable @inlinable internal init( _uniqueElements: ContiguousArray, - _ table: _HashTable? = nil + _ table: _HashTable? ) { self.__storage = table?._storage self._elements = _uniqueElements From c46c77f7f85f9efe83cc5cb8d54b32c538b06450 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 10 Sep 2021 12:59:43 -0700 Subject: [PATCH 39/54] Note that `Heap` hasn't been tagged yet & list other enhancements in progress --- README.md | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 364be758..083e937c 100644 --- a/README.md +++ b/README.md @@ -16,12 +16,20 @@ 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 +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 From 103008aca495f3b80a50713086d451b08cef9f50 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 10 Sep 2021 13:57:23 -0700 Subject: [PATCH 40/54] [run-full-tests.sh] Fix bashism: == vs = --- Utils/run-full-tests.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Utils/run-full-tests.sh b/Utils/run-full-tests.sh index 39d19335..a77341b3 100755 --- a/Utils/run-full-tests.sh +++ b/Utils/run-full-tests.sh @@ -27,7 +27,7 @@ bold_off="$(tput sgr0)" spm_flags="" -if [ "$(uname)" == "Darwin" ]; then +if [ "$(uname)" = "Darwin" ]; then swift="xcrun swift" else swift="swift" From 39a16a15cc8c7e11486015d2deb78468b4a64c85 Mon Sep 17 00:00:00 2001 From: Boris Buegling Date: Mon, 13 Sep 2021 15:54:29 -0700 Subject: [PATCH 41/54] [CMake] Match lowercase "aarch64" Seems like it is also possible for "aarch64" to be spelled lowercase, this fixes building on Ubuntu on arm at least. --- cmake/modules/SwiftSupport.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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() From 7f57a0ed1c8b1d44eacab95d3cfd57d87482b25a Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 14 Sep 2021 11:50:31 -0700 Subject: [PATCH 42/54] [OrderedSet][doc] Fix thinko --- Documentation/OrderedSet.md | 2 +- Sources/OrderedCollections/OrderedSet/OrderedSet.swift | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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/Sources/OrderedCollections/OrderedSet/OrderedSet.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet.swift index f39e0246..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 /// From cfb6dd1810c8a90fbe2f6bb877034acd781084c8 Mon Sep 17 00:00:00 2001 From: Sergey Petrenko Date: Thu, 7 Oct 2021 11:46:25 +0300 Subject: [PATCH 43/54] [Heap] Enable heap tests in optimized builds (#101) @testable import is replaced with @_spi(Testing) import. A test for _Node is moved to another file because this test needs access to internals of PriorityQueueModule and this test will not work in optimized builds. --- Tests/PriorityQueueTests/HeapTests.swift | 17 +------------- Tests/PriorityQueueTests/NodeTests.swift | 30 ++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 16 deletions(-) create mode 100644 Tests/PriorityQueueTests/NodeTests.swift diff --git a/Tests/PriorityQueueTests/HeapTests.swift b/Tests/PriorityQueueTests/HeapTests.swift index ca326858..3af1170e 100644 --- a/Tests/PriorityQueueTests/HeapTests.swift +++ b/Tests/PriorityQueueTests/HeapTests.swift @@ -9,9 +9,8 @@ // //===----------------------------------------------------------------------===// -#if DEBUG import XCTest -@testable import PriorityQueueModule +@_spi(Testing) import PriorityQueueModule final class HeapTests: XCTestCase { func test_isEmpty() { @@ -349,19 +348,6 @@ final class HeapTests: XCTestCase { // MARK: - - 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).. Date: Mon, 11 Oct 2021 13:04:22 -0700 Subject: [PATCH 44/54] PriorityQueueModule: remove `import Foundation` This removes an accidental dependency on Foundation. --- Sources/PriorityQueueModule/Heap+Invariants.swift | 1 - 1 file changed, 1 deletion(-) diff --git a/Sources/PriorityQueueModule/Heap+Invariants.swift b/Sources/PriorityQueueModule/Heap+Invariants.swift index 61999115..418bfe8c 100644 --- a/Sources/PriorityQueueModule/Heap+Invariants.swift +++ b/Sources/PriorityQueueModule/Heap+Invariants.swift @@ -10,7 +10,6 @@ //===----------------------------------------------------------------------===// import Swift -import Foundation extension Heap { #if COLLECTIONS_INTERNAL_CHECKS From 30e6eb11160ca241ff288908f1f0e8c714396cc0 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 11 Oct 2021 14:50:08 -0700 Subject: [PATCH 45/54] [Heap] Remove Heap's `ascending` and `descending` views These two do *very* non-trivial processing, so they don't at all work like views in the Standard Library. They also don't carry their weight -- they are simply lightweight wrappers around `popMin` and `popMax`, respectively. Let's get rid of them before we etch them in stone as public API. --- .../Heap+OrderedViews.swift | 62 ------------------- Tests/PriorityQueueTests/HeapTests.swift | 23 ++----- 2 files changed, 5 insertions(+), 80 deletions(-) delete mode 100644 Sources/PriorityQueueModule/Heap+OrderedViews.swift diff --git a/Sources/PriorityQueueModule/Heap+OrderedViews.swift b/Sources/PriorityQueueModule/Heap+OrderedViews.swift deleted file mode 100644 index 18b6c53f..00000000 --- a/Sources/PriorityQueueModule/Heap+OrderedViews.swift +++ /dev/null @@ -1,62 +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. - @frozen - 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. - @frozen - 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/Tests/PriorityQueueTests/HeapTests.swift b/Tests/PriorityQueueTests/HeapTests.swift index ca326858..9cf2b349 100644 --- a/Tests/PriorityQueueTests/HeapTests.swift +++ b/Tests/PriorityQueueTests/HeapTests.swift @@ -90,9 +90,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() { @@ -403,21 +406,5 @@ final class HeapTests: XCTestCase { XCTAssertEqual(heap.popMax(), 3) XCTAssertEqual(heap.popMax(), 1) } - - func test_sequenceConformance() { - let heap = Heap((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 - } - } } #endif From f41f2cae69dc6ffcc178227a0a46607561fa925c Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 11 Oct 2021 14:54:59 -0700 Subject: [PATCH 46/54] [Heap] Update docs --- Documentation/Heap.md | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/Documentation/Heap.md b/Documentation/Heap.md index 959d749e..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 From 8b3af12ece11ea7b0e748749c39a59c59269ca25 Mon Sep 17 00:00:00 2001 From: Sergey Petrenko <22587839+just-gull@users.noreply.github.com> Date: Tue, 12 Oct 2021 13:08:38 +0300 Subject: [PATCH 47/54] @_spi attributes are removed because they weren't necessary Co-authored-by: Karoy Lorentey --- Tests/PriorityQueueTests/HeapTests.swift | 2 +- Tests/PriorityQueueTests/NodeTests.swift | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Tests/PriorityQueueTests/HeapTests.swift b/Tests/PriorityQueueTests/HeapTests.swift index 3af1170e..4be275fa 100644 --- a/Tests/PriorityQueueTests/HeapTests.swift +++ b/Tests/PriorityQueueTests/HeapTests.swift @@ -10,7 +10,7 @@ //===----------------------------------------------------------------------===// import XCTest -@_spi(Testing) import PriorityQueueModule +import PriorityQueueModule final class HeapTests: XCTestCase { func test_isEmpty() { diff --git a/Tests/PriorityQueueTests/NodeTests.swift b/Tests/PriorityQueueTests/NodeTests.swift index 4020d9f4..1ebab465 100644 --- a/Tests/PriorityQueueTests/NodeTests.swift +++ b/Tests/PriorityQueueTests/NodeTests.swift @@ -11,7 +11,7 @@ #if DEBUG // These unit tests need access to PriorityQueueModule internals import XCTest -@_spi(Testing) @testable import PriorityQueueModule +@testable import PriorityQueueModule class NodeTests: XCTestCase { func test_levelCalculation() { From 276ddee5df4ea0f44c5edea0dbe726cb74682498 Mon Sep 17 00:00:00 2001 From: James Paolantonio Date: Fri, 22 Oct 2021 15:47:11 -0400 Subject: [PATCH 48/54] Fix link to package internal documentation --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 083e937c..712fb3ea 100644 --- a/README.md +++ b/README.md @@ -102,7 +102,7 @@ If you find something that looks like a bug, please open a [Bug Report][bugrepor ### Working on the package -We have some basic [documentation on package internals](./Documentation/Development/Internals/) that will help you get started. +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). From 1c1e6206fa1a4b0a6bf97ac979f841c1d1821ad7 Mon Sep 17 00:00:00 2001 From: Saleem Abdulrasool Date: Fri, 22 Oct 2021 15:08:52 -0700 Subject: [PATCH 49/54] Update CMakeLists.txt Remove `Heap+OrderedViews.swift` from the source list after #119. --- Sources/PriorityQueueModule/CMakeLists.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/Sources/PriorityQueueModule/CMakeLists.txt b/Sources/PriorityQueueModule/CMakeLists.txt index a79783d2..14319cf3 100644 --- a/Sources/PriorityQueueModule/CMakeLists.txt +++ b/Sources/PriorityQueueModule/CMakeLists.txt @@ -12,7 +12,6 @@ add_library(PriorityQueueModule 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}) From 13b5889757ae084c3eddc02b8d6996668f34e4fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ka=CC=81roly=20Lo=CC=8Brentey?= Date: Thu, 11 Nov 2021 00:39:29 -0800 Subject: [PATCH 50/54] [OrderedCollections][test] Strengthen withHiddenCopies tests `withHiddenCopies(if:of:)` is supposed to check for value semantic violations where mutations of one copy affect another -- however, it currently only checks that iteration returns the same items before/after the change, not that the old copy is still in a fully consistent state. Add an extra parameter that can be set to a closure that performs stricter checks. Use it to call `_checkInvariants()` in ordered collections tests, uncovering a missing uniqueness check in `OrderedSet._insertNew(_:at:in:)`. --- .../AssertionContexts/Combinatorics.swift | 6 ++ .../OrderedDictionary Tests.swift | 68 +++++++++---------- .../OrderedDictionary+Elements Tests.swift | 30 ++++---- .../OrderedDictionary+Values Tests.swift | 12 ++-- .../OrderedSet/OrderedSetTests.swift | 20 +++--- 5 files changed, 71 insertions(+), 65 deletions(-) diff --git a/Sources/_CollectionsTestSupport/AssertionContexts/Combinatorics.swift b/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/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift index 34e7a7dd..0e46b9c0 100644 --- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift @@ -233,7 +233,7 @@ class OrderedDictionaryTests: CollectionTestCase { withLifetimeTracking { tracker in 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[reference[offset].key] = replacement reference[offset].value = replacement expectEqualElements(d, reference) @@ -250,7 +250,7 @@ class OrderedDictionaryTests: CollectionTestCase { withEvery("isShared", in: [false, true]) { isShared in withLifetimeTracking { tracker in var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) - withHiddenCopies(if: isShared, of: &d) { d in + withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in d[reference[offset].key] = nil reference.remove(at: offset) expectEqualElements(d, reference) @@ -270,7 +270,7 @@ class OrderedDictionaryTests: CollectionTestCase { 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] expectEqualElements(d, reference.prefix(offset + 1)) } @@ -286,7 +286,7 @@ class OrderedDictionaryTests: CollectionTestCase { withLifetimeTracking { tracker in 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 } expectEqualElements(d, reference) @@ -309,7 +309,7 @@ class OrderedDictionaryTests: CollectionTestCase { withLifetimeTracking { tracker in 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 mutate(&d[reference[offset].key]) { $0 = replacement } reference[offset].value = replacement expectEqualElements(d, reference) @@ -326,7 +326,7 @@ class OrderedDictionaryTests: CollectionTestCase { withEvery("isShared", in: [false, true]) { isShared in withLifetimeTracking { tracker in var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) - withHiddenCopies(if: isShared, of: &d) { d in + withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in let key = reference[offset].key mutate(&d[key]) { v in expectEqual(v, reference[offset].value) @@ -349,7 +349,7 @@ class OrderedDictionaryTests: CollectionTestCase { 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] @@ -369,7 +369,7 @@ class OrderedDictionaryTests: CollectionTestCase { withLifetimeTracking { tracker in 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 @@ -410,7 +410,7 @@ class OrderedDictionaryTests: CollectionTestCase { 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 + withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in let key = reference[offset].key mutate(&d[key, default: fallback]) { v in expectEqual(v, reference[offset].value) @@ -435,7 +435,7 @@ class OrderedDictionaryTests: CollectionTestCase { 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) @@ -457,7 +457,7 @@ class OrderedDictionaryTests: CollectionTestCase { withLifetimeTracking { tracker in 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 let key = reference[offset].key let old = d.updateValue(replacement, forKey: key) expectEqual(old, reference[offset].value) @@ -479,7 +479,7 @@ class OrderedDictionaryTests: CollectionTestCase { 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) @@ -499,7 +499,7 @@ class OrderedDictionaryTests: CollectionTestCase { withLifetimeTracking { tracker in 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 let key = reference[offset].key let (old, index) = d.updateValue(replacement, forKey: key, insertingAt: 0) @@ -523,7 +523,7 @@ class OrderedDictionaryTests: CollectionTestCase { 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) = @@ -547,7 +547,7 @@ class OrderedDictionaryTests: CollectionTestCase { 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 + 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) @@ -572,7 +572,7 @@ class OrderedDictionaryTests: CollectionTestCase { 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.updateValue(forKey: key, default: fallback) { value in expectEqual(value, fallback) @@ -595,7 +595,7 @@ class OrderedDictionaryTests: CollectionTestCase { 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 + 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) @@ -620,7 +620,7 @@ class OrderedDictionaryTests: CollectionTestCase { 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, value) = reference[count - 1 - offset] d.updateValue(forKey: key, insertingDefault: fallback, at: 0) { v in expectEqual(v, fallback) @@ -641,7 +641,7 @@ class OrderedDictionaryTests: CollectionTestCase { withEvery("isShared", in: [false, true]) { isShared in withLifetimeTracking { tracker in var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) - withHiddenCopies(if: isShared, of: &d) { d in + 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, value) @@ -952,7 +952,7 @@ class OrderedDictionaryTests: CollectionTestCase { withLifetimeTracking { tracker in var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) reference.swapAt(i, j) - withHiddenCopies(if: isShared, of: &d) { d in + withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in d.swapAt(i, j) expectEqualElements(d, reference) expectEqual(d[reference[i].key], reference[i].value) @@ -974,7 +974,7 @@ class OrderedDictionaryTests: CollectionTestCase { var (d, reference) = tracker.orderedDictionary( keys: (0 ..< count).shuffled(using: &rng)) let expectedPivot = reference.partition { $0.key.payload < count / 2 } - withHiddenCopies(if: isShared, of: &d) { d in + withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in let actualPivot = d.partition { $0.key.payload < count / 2 } expectEqual(actualPivot, expectedPivot) expectEqualElements(d, reference) @@ -994,7 +994,7 @@ class OrderedDictionaryTests: CollectionTestCase { var (d, reference) = tracker.orderedDictionary( keys: (0 ..< count).shuffled(using: &rng)) reference.sort(by: { $0.key < $1.key }) - withHiddenCopies(if: isShared, of: &d) { d in + withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in d.sort() expectEqualElements(d, reference) } @@ -1013,7 +1013,7 @@ class OrderedDictionaryTests: CollectionTestCase { var (d, reference) = tracker.orderedDictionary( keys: (0 ..< count).shuffled(using: &rng)) reference.sort(by: { $0.key > $1.key }) - withHiddenCopies(if: isShared, of: &d) { d in + withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in d.sort(by: { $0.key > $1.key }) expectEqualElements(d, reference) } @@ -1031,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) @@ -1073,7 +1073,7 @@ class OrderedDictionaryTests: CollectionTestCase { withEvery("isShared", in: [false, true]) { isShared in withLifetimeTracking { tracker in var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) - withHiddenCopies(if: isShared, of: &d) { d in + withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in reference.reverse() d.reverse() expectEqualElements(d, reference) @@ -1088,7 +1088,7 @@ class OrderedDictionaryTests: CollectionTestCase { withEvery("isShared", in: [false, true]) { isShared in withLifetimeTracking { tracker in var (d, _) = tracker.orderedDictionary(keys: 0 ..< count) - withHiddenCopies(if: isShared, of: &d) { d in + withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in d.removeAll() expectEqual(d.keys.__unstable.scale, 0) expectEqualElements(d, []) @@ -1104,7 +1104,7 @@ class OrderedDictionaryTests: CollectionTestCase { withLifetimeTracking { tracker in 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, []) @@ -1120,7 +1120,7 @@ class OrderedDictionaryTests: CollectionTestCase { withEvery("isShared", in: [false, true]) { isShared in withLifetimeTracking { tracker in var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) - withHiddenCopies(if: isShared, of: &d) { d in + withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in let actual = d.remove(at: offset) let expectedItem = reference.remove(at: offset) expectEqual(actual.key, expectedItem.key) @@ -1139,7 +1139,7 @@ class OrderedDictionaryTests: CollectionTestCase { withEvery("isShared", in: [false, true]) { isShared in withLifetimeTracking { tracker in var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) - withHiddenCopies(if: isShared, of: &d) { d in + withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in d.removeSubrange(range) reference.removeSubrange(range) expectEqualElements(d, reference) @@ -1172,7 +1172,7 @@ class OrderedDictionaryTests: CollectionTestCase { withLifetimeTracking { tracker in 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 ref = reference.removeLast() expectEqual(actual.key, ref.key) @@ -1189,7 +1189,7 @@ class OrderedDictionaryTests: CollectionTestCase { withLifetimeTracking { tracker in 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 expected = reference.removeFirst() expectEqual(actual.key, expected.key) @@ -1207,7 +1207,7 @@ class OrderedDictionaryTests: CollectionTestCase { withEvery("isShared", in: [false, true]) { isShared in withLifetimeTracking { tracker in var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) - withHiddenCopies(if: isShared, of: &d) { d in + withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in d.removeLast(suffix) reference.removeLast(suffix) expectEqualElements(d, reference) @@ -1224,7 +1224,7 @@ class OrderedDictionaryTests: CollectionTestCase { withEvery("isShared", in: [false, true]) { isShared in withLifetimeTracking { tracker in var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) - withHiddenCopies(if: isShared, of: &d) { d in + withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in d.removeFirst(prefix) reference.removeFirst(prefix) expectEqualElements(d, reference) @@ -1241,7 +1241,7 @@ class OrderedDictionaryTests: CollectionTestCase { withEvery("isShared", in: [false, true]) { isShared in withLifetimeTracking { tracker in var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) - withHiddenCopies(if: isShared, of: &d) { d in + withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in d.removeAll(where: { !$0.key.payload.isMultiple(of: n) }) reference.removeAll(where: { !$0.key.payload.isMultiple(of: n) }) expectEqualElements(d, reference) diff --git a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Elements Tests.swift b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Elements Tests.swift index d46bace3..ae07e1e6 100644 --- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Elements Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Elements Tests.swift @@ -148,7 +148,7 @@ class OrderedDictionaryElementsTests: CollectionTestCase { withLifetimeTracking { tracker in var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) reference.swapAt(i, j) - withHiddenCopies(if: isShared, of: &d) { d in + withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in d.elements.swapAt(i, j) expectEquivalentElements( d, reference, @@ -172,7 +172,7 @@ class OrderedDictionaryElementsTests: CollectionTestCase { var (d, reference) = tracker.orderedDictionary( keys: (0 ..< count).shuffled(using: &rng)) let expectedPivot = reference.partition { $0.key.payload < count / 2 } - withHiddenCopies(if: isShared, of: &d) { d in + 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, reference) @@ -192,7 +192,7 @@ class OrderedDictionaryElementsTests: CollectionTestCase { var (d, reference) = tracker.orderedDictionary( keys: (0 ..< count).shuffled(using: &rng)) reference.sort(by: { $0.key < $1.key }) - withHiddenCopies(if: isShared, of: &d) { d in + withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in d.elements.sort() expectEqualElements(d, reference) } @@ -211,7 +211,7 @@ class OrderedDictionaryElementsTests: CollectionTestCase { var (d, reference) = tracker.orderedDictionary( keys: (0 ..< count).shuffled(using: &rng)) reference.sort(by: { $0.key > $1.key }) - withHiddenCopies(if: isShared, of: &d) { d in + withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in d.elements.sort(by: { $0.key > $1.key }) expectEqualElements(d, reference) } @@ -229,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) @@ -271,7 +271,7 @@ class OrderedDictionaryElementsTests: CollectionTestCase { withEvery("isShared", in: [false, true]) { isShared in withLifetimeTracking { tracker in var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) - withHiddenCopies(if: isShared, of: &d) { d in + withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in reference.reverse() d.elements.reverse() expectEqualElements(d, reference) @@ -286,7 +286,7 @@ class OrderedDictionaryElementsTests: CollectionTestCase { withEvery("isShared", in: [false, true]) { isShared in withLifetimeTracking { tracker in var (d, _) = tracker.orderedDictionary(keys: 0 ..< count) - withHiddenCopies(if: isShared, of: &d) { d in + withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in d.elements.removeAll() expectEqual(d.keys.__unstable.scale, 0) expectEqualElements(d, []) @@ -302,7 +302,7 @@ class OrderedDictionaryElementsTests: CollectionTestCase { withLifetimeTracking { tracker in 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, []) @@ -318,7 +318,7 @@ class OrderedDictionaryElementsTests: CollectionTestCase { withEvery("isShared", in: [false, true]) { isShared in withLifetimeTracking { tracker in var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) - withHiddenCopies(if: isShared, of: &d) { d in + withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in let actual = d.elements.remove(at: offset) let expected = reference.remove(at: offset) expectEqual(actual.key, expected.key) @@ -337,7 +337,7 @@ class OrderedDictionaryElementsTests: CollectionTestCase { withEvery("isShared", in: [false, true]) { isShared in withLifetimeTracking { tracker in var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) - withHiddenCopies(if: isShared, of: &d) { d in + withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in d.elements.removeSubrange(range) reference.removeSubrange(range) expectEqualElements(d, reference) @@ -370,7 +370,7 @@ class OrderedDictionaryElementsTests: CollectionTestCase { withLifetimeTracking { tracker in 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 expected = reference.removeLast() expectEqual(actual.key, expected.key) @@ -387,7 +387,7 @@ class OrderedDictionaryElementsTests: CollectionTestCase { withLifetimeTracking { tracker in 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 expected = reference.removeFirst() expectEqual(actual.key, expected.key) @@ -405,7 +405,7 @@ class OrderedDictionaryElementsTests: CollectionTestCase { withEvery("isShared", in: [false, true]) { isShared in withLifetimeTracking { tracker in var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) - withHiddenCopies(if: isShared, of: &d) { d in + withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in d.elements.removeLast(suffix) reference.removeLast(suffix) expectEqualElements(d, reference) @@ -422,7 +422,7 @@ class OrderedDictionaryElementsTests: CollectionTestCase { withEvery("isShared", in: [false, true]) { isShared in withLifetimeTracking { tracker in var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) - withHiddenCopies(if: isShared, of: &d) { d in + withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in d.elements.removeFirst(prefix) reference.removeFirst(prefix) expectEqualElements(d, reference) @@ -439,7 +439,7 @@ class OrderedDictionaryElementsTests: CollectionTestCase { withEvery("isShared", in: [false, true]) { isShared in withLifetimeTracking { tracker in var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) - withHiddenCopies(if: isShared, of: &d) { d in + withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in d.elements.removeAll(where: { !$0.key.payload.isMultiple(of: n) }) reference.removeAll(where: { !$0.key.payload.isMultiple(of: n) }) expectEqualElements(d, reference) diff --git a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Values Tests.swift b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Values Tests.swift index 241c281a..d10c1528 100644 --- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Values Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Values Tests.swift @@ -41,7 +41,7 @@ class OrderedDictionaryValueTests: CollectionTestCase { withLifetimeTracking { tracker in 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 reference[offset].value = replacement expectEqualElements(d.values, reference.map { $0.value }) @@ -95,7 +95,7 @@ class OrderedDictionaryValueTests: CollectionTestCase { let t = reference[i].value reference[i].value = reference[j].value reference[j].value = t - withHiddenCopies(if: isShared, of: &d) { d in + withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in d.values.swapAt(i, j) expectEqualElements(d.values, reference.map { $0.value }) expectEqual(d[reference[i].key], reference[i].value) @@ -118,7 +118,7 @@ class OrderedDictionaryValueTests: CollectionTestCase { 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) @@ -139,7 +139,7 @@ class OrderedDictionaryValueTests: CollectionTestCase { 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) } @@ -158,7 +158,7 @@ class OrderedDictionaryValueTests: CollectionTestCase { 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) @@ -186,7 +186,7 @@ class OrderedDictionaryValueTests: CollectionTestCase { 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) diff --git a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift index bd37b11b..f2161dc3 100644 --- a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift +++ b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift @@ -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) From 074b0ad21387e767b5b3ff1cb014a118a3b80bde Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ka=CC=81roly=20Lo=CC=8Brentey?= Date: Thu, 11 Nov 2021 00:40:01 -0800 Subject: [PATCH 51/54] [OrderedSet] Add missing uniqueness check in `OrderedSet._insertNew(_:at:in:)` --- .../OrderedCollections/OrderedSet/OrderedSet+Insertions.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Insertions.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Insertions.swift index 3079a0ca..6b054366 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Insertions.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Insertions.swift @@ -129,6 +129,7 @@ extension OrderedSet { return } + _ensureUnique() _table!.update { hashTable in assert(!hashTable.isOccupied(bucket)) hashTable.adjustContents(preparingForInsertionOfElementAtOffset: index, in: _elements) From ddc8b9c66d07cb0af38e98ca160f1f7cc85c88d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ka=CC=81roly=20Lo=CC=8Brentey?= Date: Mon, 15 Nov 2021 14:08:09 -0800 Subject: [PATCH 52/54] [Utils] run-full-tests.sh: Keep going after a failure --- Utils/run-full-tests.sh | 72 +++++++++++++++++++++++------------------ 1 file changed, 41 insertions(+), 31 deletions(-) diff --git a/Utils/run-full-tests.sh b/Utils/run-full-tests.sh index a77341b3..367bce3b 100755 --- a/Utils/run-full-tests.sh +++ b/Utils/run-full-tests.sh @@ -22,9 +22,13 @@ 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 @@ -37,13 +41,6 @@ fi echo "Build output logs are saved in $bold_on$build_dir$bold_off" swift --version -report_failure() { - logs="$1" - echo " ${bold_on}Failed.${bold_off} See $logs for full console output." - tail -10 "$logs" - exit 1 -} - _count=0 try() { label="$1" @@ -53,9 +50,15 @@ try() { output="$build_dir/$count.$label.log" echo "$bold_on[$count $label]$bold_off $@" start="$(date +%s)" - "$@" >"$output" 2>&1 || report_failure "$output" - end="$(date +%s)" - echo " Completed in $(($end - $start))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 @@ -67,29 +70,36 @@ 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.build" \ - xcodebuild -scheme swift-collections-Package \ - -configuration Release \ - -destination "generic/platform=macOS" \ - -destination "generic/platform=macOS,variant=Mac Catalyst" \ - -destination "generic/platform=iOS" \ - -destination "generic/platform=iOS Simulator" \ - -destination "generic/platform=watchOS" \ - -destination "generic/platform=watchOS Simulator" \ - -destination "generic/platform=tvOS" \ - -destination "generic/platform=tvOS Simulator" \ - clean build - try "xcodebuild.test" \ - xcodebuild -scheme swift-collections-Package \ - -configuration Release \ - -destination "platform=macOS" \ - -destination "platform=macOS,variant=Mac Catalyst" \ - -destination "platform=iOS Simulator,name=iPhone 12" \ - -destination "platform=watchOS Simulator,name=Apple Watch Series 6 - 44mm" \ - -destination "platform=tvOS Simulator,name=Apple TV 4K (at 1080p) (2nd generation)" \ - test + 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 From 9dde4b560323d43ec2ca8225a6c5c79a9bc0735d Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 15 Nov 2021 15:37:59 -0800 Subject: [PATCH 53/54] [Utils] run-full-tests.sh: Add support for testing on Swift 5.3 without manual editing --- Utils/run-full-tests.sh | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Utils/run-full-tests.sh b/Utils/run-full-tests.sh index 367bce3b..98df0c61 100755 --- a/Utils/run-full-tests.sh +++ b/Utils/run-full-tests.sh @@ -36,10 +36,14 @@ if [ "$(uname)" = "Darwin" ]; then 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 +$swift --version _count=0 try() { From efefae56531b30d75553f234134e3c83bd26c6a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ka=CC=81roly=20Lo=CC=8Brentey?= Date: Fri, 24 Sep 2021 20:26:58 -0700 Subject: [PATCH 54/54] [Deque] `append(contentsOf:):` Use exponential capacity reservation Depending on the supplied sequence, `Deque.append(contentsOf:)` currently reserves just enough capacity as it needs to perform the append. This isn't right -- it can result in O(n) reallocs instead of O(log(n)) when items are incrementally appended in constant-sized `append(contents:)` batches. --- Sources/DequeModule/Deque+Collection.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Sources/DequeModule/Deque+Collection.swift b/Sources/DequeModule/Deque+Collection.swift index e1614b6a..61ba34a2 100644 --- a/Sources/DequeModule/Deque+Collection.swift +++ b/Sources/DequeModule/Deque+Collection.swift @@ -672,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) @@ -713,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)