diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 00000000..5ace4600 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,6 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index ac86156e..4115629a 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -10,7 +10,7 @@ on: jobs: tests: name: Test - uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@main + uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@0.0.7 with: linux_exclude_swift_versions: '[{"swift_version": "5.8"}, {"swift_version": "5.9"}, {"swift_version": "5.10"}]' windows_exclude_swift_versions: '[{"swift_version": "5.9"}, {"swift_version": "5.10"}]' @@ -22,7 +22,7 @@ jobs: embedded-swift: name: Build with Embedded Swift - uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@0.0.2 + uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@0.0.6 with: enable_linux_checks: false enable_macos_checks: false @@ -33,7 +33,7 @@ jobs: soundness: name: Soundness - uses: swiftlang/github-workflows/.github/workflows/soundness.yml@0.0.2 + uses: swiftlang/github-workflows/.github/workflows/soundness.yml@0.0.6 with: license_header_check_project_name: "Swift.org" # https://github.com/apple/swift-collections/issues/428 diff --git a/Benchmarks/Libraries/Deque.json b/Benchmarks/Libraries/Deque.json index 1d1adb1e..d1628eff 100644 --- a/Benchmarks/Libraries/Deque.json +++ b/Benchmarks/Libraries/Deque.json @@ -209,14 +209,15 @@ }, { "kind": "group", - "title": "Deque vs std::deque", - "directory": "versus STL deque", + "title": "Deque vs std::deque vs VecDeque vs RigidDeque vs UniqueDeque", + "directory": "versus other deques", "contents": [ { "kind": "chart", "title": "init from buffer of integers", "tasks": [ "std::deque constructor from buffer", + "VecDeque constructor from buffer", "Deque init from unsafe buffer" ] }, @@ -225,10 +226,12 @@ "title": "sequential iteration", "tasks": [ "std::deque sequential iteration", + "VecDeque sequential iteration", "Deque sequential iteration (contiguous, iterator)", "Deque sequential iteration (contiguous, indices)", "Deque sequential iteration (discontiguous, iterator)", - "Deque sequential iteration (discontiguous, indices)" + "Deque sequential iteration (discontiguous, indices)", + "UniqueDeque sequential iteration" ] }, { @@ -246,8 +249,19 @@ "title": "append individual integers", "tasks": [ "std::deque push_back", + "VecDeque push_back", "Deque append", - "Deque append, reserving capacity" + "UniqueDeque append" + ] + }, + { + "kind": "chart", + "title": "append individual integers, reserving capacity", + "tasks": [ + "VecDeque push_back, reserving capacity", + "Deque append, reserving capacity", + "RigidDeque append, reserving capacity", + "UniqueDeque append, reserving capacity" ] }, { @@ -255,8 +269,19 @@ "title": "prepend individual integers", "tasks": [ "std::deque push_front", + "VecDeque push_front", "Deque prepend", - "Deque prepend, reserving capacity" + "UniqueDeque prepend" + ] + }, + { + "kind": "chart", + "title": "prepend individual integers, reserving capacity", + "tasks": [ + "VecDeque push_front, reserving capacity", + "Deque prepend, reserving capacity", + "RigidDeque prepend, reserving capacity", + "UniqueDeque prepend, reserving capacity" ] }, { @@ -264,7 +289,9 @@ "title": "random insertions", "tasks": [ "std::deque random insertions", - "Deque random insertions" + "VecDeque random insertions", + "Deque random insertions", + "UniqueDeque random insertions" ] }, { diff --git a/Benchmarks/Package.resolved b/Benchmarks/Package.resolved index 1936b386..72b9ccc3 100644 --- a/Benchmarks/Package.resolved +++ b/Benchmarks/Package.resolved @@ -1,13 +1,13 @@ { - "originHash" : "77540dbea8c5b0878a1a745326146f44af61e58620d5484d3d37c7454bf8b088", + "originHash" : "4f32ed9368a26ffe852c02e155d3f9304019975ede688f715b0601ca2185ea48", "pins" : [ { "identity" : "swift-argument-parser", "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-argument-parser", "state" : { - "revision" : "41982a3656a71c768319979febd796c6fd111d5c", - "version" : "1.5.0" + "revision" : "cdd0ef3755280949551dc26dee5de9ddeda89f54", + "version" : "1.6.2" } }, { diff --git a/Benchmarks/Package.swift b/Benchmarks/Package.swift index 96727d25..c95c1c58 100644 --- a/Benchmarks/Package.swift +++ b/Benchmarks/Package.swift @@ -12,6 +12,27 @@ import PackageDescription +let availabilityMacros: KeyValuePairs = [ + "SwiftStdlib 5.0": "macOS 10.14.4, iOS 12.2, watchOS 5.2, tvOS 12.2", + "SwiftStdlib 5.1": "macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0", + "SwiftStdlib 5.6": "macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4", + "SwiftStdlib 5.8": "macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4", + "SwiftStdlib 5.9": "macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0", + "SwiftStdlib 5.10": "macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4, visionOS 1.1", + "SwiftStdlib 6.0": "macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0", + "SwiftStdlib 6.1": "macOS 15.4, iOS 18.4, watchOS 11.4, tvOS 18.4, visionOS 2.4", + "SwiftStdlib 6.2": "macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, visionOS 26.0", + // Note: if you touch these, please make sure to also update the similar lists in + // CMakeLists.txt and Xcode/Shared.xcconfig. +] + +let _sharedSettings: [SwiftSetting] = ( + availabilityMacros.map { name, value in + .enableExperimentalFeature("AvailabilityMacro=\(name): \(value)") + } + + [.enableExperimentalFeature("Extern")] +) + let package = Package( name: "swift-collections.Benchmarks", platforms: [.macOS(.v15), .iOS(.v18), .watchOS(.v11), .tvOS(.v18), .visionOS(.v2)], @@ -30,17 +51,31 @@ let package = Package( .product(name: "Collections", package: "swift-collections"), .product(name: "CollectionsBenchmark", package: "swift-collections-benchmark"), "CppBenchmarks", - ] + ], + swiftSettings: _sharedSettings ), .target( name: "CppBenchmarks" ), + .plugin( + name: "RustBuild", + capability: .buildTool() + ), + .target( + name: "RustBenchmarks", + plugins: [ + .plugin(name: "RustBuild") + ] + ), .executableTarget( name: "benchmark", dependencies: [ "Benchmarks", ], - path: "Sources/benchmark-tool" + path: "Sources/benchmark-tool", + linkerSettings: [ + .unsafeFlags(["-L\(Context.packageDirectory)/.build/plugins/outputs/benchmarks/RustBenchmarks/destination/RustBuild", "-lRustBenchmarks"]) + ] ), .executableTarget( name: "memory-benchmark", diff --git a/Benchmarks/Plugins/RustBuild/RustBuild.swift b/Benchmarks/Plugins/RustBuild/RustBuild.swift new file mode 100644 index 00000000..e02f8356 --- /dev/null +++ b/Benchmarks/Plugins/RustBuild/RustBuild.swift @@ -0,0 +1,54 @@ +import Foundation +import PackagePlugin + +@main +struct RustBuild: BuildToolPlugin { + func findRustCompiler() throws -> URL { + let which = Process() + which.executableURL = URL(filePath: "/usr/bin/which") + which.arguments = ["rustc"] + + let whichOutput = Pipe() + which.standardOutput = whichOutput + + try which.run() + which.waitUntilExit() + + let output = whichOutput.fileHandleForReading.readDataToEndOfFile() + var pathString = String(decoding: output, as: UTF8.self) + pathString.removeLast() + return URL(filePath: pathString) + } + + func createBuildCommands( + context: PluginContext, + target: Target + ) throws -> [Command] { + guard let sourceFiles = target.sourceModule?.sourceFiles else { return [] } + + // Filter the dummy Swift source file out. + let rustSources = sourceFiles.filter { + $0.url.pathExtension == "rs" + } + + let rustCompiler = try findRustCompiler() + + let inputs = rustSources.map { + $0.url + } + let inputPaths = inputs.map { + $0.path + } + let lib = "lib\(target.name).a" + let output = context.pluginWorkDirectoryURL.appendingPathComponent(lib) + let args = inputPaths + ["-o", output.path, "-O", "--crate-type", "staticlib"] + + return [.buildCommand( + displayName: "Compiling Rust Sources in Target \(target.name)", + executable: rustCompiler, + arguments: args, + inputFiles: inputs, + outputFiles: [output] + )] + } +} diff --git a/Benchmarks/Sources/Benchmarks/BigStringBenchmarks.swift b/Benchmarks/Sources/Benchmarks/BigStringBenchmarks.swift index 657d945e..30799913 100644 --- a/Benchmarks/Sources/Benchmarks/BigStringBenchmarks.swift +++ b/Benchmarks/Sources/Benchmarks/BigStringBenchmarks.swift @@ -74,7 +74,7 @@ struct BridgedStringInput { } } -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +@available(SwiftStdlib 6.2, *) struct BigStringInput { let flat: String let big: BigString @@ -85,10 +85,9 @@ struct BigStringInput { } } - extension Benchmark { public mutating func addBigStringBenchmarks() { - guard #available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) else { + guard #available(macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, visionOS 26.0, *) else { return } diff --git a/Benchmarks/Sources/Benchmarks/DequeBenchmarks.swift b/Benchmarks/Sources/Benchmarks/DequeBenchmarks.swift index 83e51af4..e3a29b9f 100644 --- a/Benchmarks/Sources/Benchmarks/DequeBenchmarks.swift +++ b/Benchmarks/Sources/Benchmarks/DequeBenchmarks.swift @@ -335,7 +335,6 @@ extension Benchmark { for i in input { deque.append(i) } - precondition(deque.count == input.count) blackHole(deque) } @@ -536,6 +535,5 @@ extension Benchmark { } } } - } } diff --git a/Benchmarks/Sources/Benchmarks/RigidDequeBenchmarks.swift b/Benchmarks/Sources/Benchmarks/RigidDequeBenchmarks.swift new file mode 100644 index 00000000..884e7059 --- /dev/null +++ b/Benchmarks/Sources/Benchmarks/RigidDequeBenchmarks.swift @@ -0,0 +1,63 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021 - 2024 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 +@_spi(Testing) import DequeModule + +/// Do nothing and immediately return. +/// +/// Some compiler optimizations can eliminate operations whose results don't +/// get used, and this could potentially interfere with the accuracy of a +/// benchmark. To defeat these optimizations, pass such unused results to +/// this function so that the compiler considers them used. +@inline(never) +@_optimize(none) +fileprivate func blackHole(_ value: borrowing RigidDeque) {} + +@inline(never) +fileprivate func appendReserveCapacity(_ input: UnsafeBufferPointer) { + var deque = RigidDeque(capacity: input.count) + for i in input { + deque.append(i) + } + blackHole(deque) +} + +@inline(never) +fileprivate func prependReserveCapacity(_ input: UnsafeBufferPointer) { + var deque = RigidDeque(capacity: input.count) + for i in input { + deque.prepend(i) + } + blackHole(deque) +} + +extension Benchmark { + public mutating func addRigidDequeBenchmarks() { + self.addSimple( + title: "RigidDeque append, reserving capacity", + input: [Int].self + ) { input in + input.withUnsafeBufferPointer { + appendReserveCapacity($0) + } + } + + self.addSimple( + title: "RigidDeque prepend, reserving capacity", + input: [Int].self + ) { input in + input.withUnsafeBufferPointer { + prependReserveCapacity($0) + } + } + } +} diff --git a/Benchmarks/Sources/Benchmarks/Rust/RustBenchmarks.swift b/Benchmarks/Sources/Benchmarks/Rust/RustBenchmarks.swift new file mode 100644 index 00000000..cfd5bae6 --- /dev/null +++ b/Benchmarks/Sources/Benchmarks/Rust/RustBenchmarks.swift @@ -0,0 +1,18 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2025 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 + +extension Benchmark { + public mutating func addRustBenchmarks() { + _addRustVecDequeBenchmarks() + } +} diff --git a/Benchmarks/Sources/Benchmarks/Rust/RustVecDequeBenchmarks.swift b/Benchmarks/Sources/Benchmarks/Rust/RustVecDequeBenchmarks.swift new file mode 100644 index 00000000..324dfe57 --- /dev/null +++ b/Benchmarks/Sources/Benchmarks/Rust/RustVecDequeBenchmarks.swift @@ -0,0 +1,141 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2025 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 + +@_extern(c, "rust_vecdeque_create") +func rust_vecdeque_create( + _: UnsafeRawPointer?, + _: Int +) -> UnsafeMutableRawPointer? + +@_extern(c, "rust_vecdeque_destroy") +func rust_vecdeque_destroy(_: UnsafeMutableRawPointer?) + +@_extern(c, "rust_vecdeque_from_int_range") +func rust_vecdeque_from_int_range(_: Int) + +@_extern(c, "rust_vecdeque_from_int_buffer") +func rust_vecdeque_from_int_buffer(_: UnsafePointer?, _: Int) + +@_extern(c, "rust_vecdeque_append_integers") +func rust_vecdeque_append_integers(_: UnsafePointer?, _: Int) + +@_extern(c, "rust_vecdeque_append_integers_with_capacity") +func rust_vecdeque_append_integers_with_capacity(_: UnsafePointer?, _: Int) + +@_extern(c, "rust_vecdeque_prepend_integers") +func rust_vecdeque_prepend_integers(_: UnsafePointer?, _: Int) + +@_extern(c, "rust_vecdeque_prepend_integers_with_capacity") +func rust_vecdeque_prepend_integers_with_capacity(_: UnsafePointer?, _: Int) + +@_extern(c, "rust_vecdeque_random_insertions") +func rust_vecdeque_random_insertions(_: UnsafePointer?, _: Int) + +@_extern(c, "rust_vecdeque_iterate") +func rust_vecdeque_iterate(_: UnsafeMutableRawPointer?) + +internal class RustDeque { + var ptr: UnsafeMutableRawPointer? + + init(_ input: [Int]) { + self.ptr = input.withUnsafeBufferPointer { buffer in + rust_vecdeque_create(buffer.baseAddress, buffer.count) + } + } + + deinit { + destroy() + } + + func destroy() { + if let ptr = ptr { + rust_vecdeque_destroy(ptr) + } + ptr = nil + } +} + +extension Benchmark { + internal mutating func _addRustVecDequeBenchmarks() { + self.addSimple( + title: "VecDeque push_back from integer range", + input: Int.self + ) { count in + rust_vecdeque_from_int_range(count) + } + + self.addSimple( + title: "VecDeque constructor from buffer", + input: [Int].self + ) { input in + input.withUnsafeBufferPointer { buffer in + rust_vecdeque_from_int_buffer(buffer.baseAddress, buffer.count) + } + } + + self.addSimple( + title: "VecDeque push_back", + input: [Int].self + ) { input in + input.withUnsafeBufferPointer { buffer in + rust_vecdeque_append_integers(buffer.baseAddress, buffer.count) + } + } + + self.addSimple( + title: "VecDeque push_back, reserving capacity", + input: [Int].self + ) { input in + input.withUnsafeBufferPointer { buffer in + rust_vecdeque_append_integers_with_capacity(buffer.baseAddress, buffer.count) + } + } + + self.addSimple( + title: "VecDeque push_front", + input: [Int].self + ) { input in + input.withUnsafeBufferPointer { buffer in + rust_vecdeque_prepend_integers(buffer.baseAddress, buffer.count) + } + } + + self.addSimple( + title: "VecDeque push_front, reserving capacity", + input: [Int].self + ) { input in + input.withUnsafeBufferPointer { buffer in + rust_vecdeque_prepend_integers_with_capacity(buffer.baseAddress, buffer.count) + } + } + + self.addSimple( + title: "VecDeque random insertions", + input: Insertions.self + ) { insertions in + insertions.values.withUnsafeBufferPointer { buffer in + rust_vecdeque_random_insertions(buffer.baseAddress, buffer.count) + } + } + + self.add( + title: "VecDeque sequential iteration", + input: [Int].self + ) { input in + let deque = RustDeque(input) + return { timer in + rust_vecdeque_iterate(deque.ptr) + } + } + } +} diff --git a/Benchmarks/Sources/Benchmarks/UniqueDequeBenchmarks.swift b/Benchmarks/Sources/Benchmarks/UniqueDequeBenchmarks.swift new file mode 100644 index 00000000..9ea9b199 --- /dev/null +++ b/Benchmarks/Sources/Benchmarks/UniqueDequeBenchmarks.swift @@ -0,0 +1,132 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021 - 2024 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 +@_spi(Testing) import DequeModule + +@inline(never) +@_optimize(none) +fileprivate func blackHole(_ value: Int) {} + +@inline(never) +@_optimize(none) +fileprivate func blackHole(_ value: borrowing UniqueDeque) {} + +@inline(never) +fileprivate func append(_ input: UnsafeBufferPointer) { + var deque = UniqueDeque() + for i in input { + deque.append(i) + } + blackHole(deque) +} + +@inline(never) +fileprivate func appendReserveCapacity(_ input: UnsafeBufferPointer) { + var deque = UniqueDeque(capacity: input.count) + for i in input { + deque.append(i) + } + blackHole(deque) +} + +@inline(never) +fileprivate func prepend(_ input: UnsafeBufferPointer) { + var deque = UniqueDeque() + for i in input { + deque.prepend(i) + } + blackHole(deque) +} + +@inline(never) +fileprivate func prependReserveCapacity(_ input: UnsafeBufferPointer) { + var deque = UniqueDeque(capacity: input.count) + for i in input { + deque.prepend(i) + } + blackHole(deque) +} + +@inline(never) +fileprivate func randomInsertions(_ insertions: UnsafeBufferPointer) { + var deque = UniqueDeque() + for i in insertions.indices { + deque.insert(i, at: insertions[i]) + } + blackHole(deque) +} + +@inline(never) +fileprivate func sequentialIteration(_ deque: borrowing UniqueDeque) { + for i in deque.indices { + blackHole(deque[i]) + } +} + +extension Benchmark { + public mutating func addUniqueDequeBenchmarks() { + self.addSimple( + title: "UniqueDeque append", + input: [Int].self + ) { input in + input.withUnsafeBufferPointer { + append($0) + } + } + + self.addSimple( + title: "UniqueDeque append, reserving capacity", + input: [Int].self + ) { input in + input.withUnsafeBufferPointer { + appendReserveCapacity($0) + } + } + + self.addSimple( + title: "UniqueDeque prepend", + input: [Int].self + ) { input in + input.withUnsafeBufferPointer { + prepend($0) + } + } + + self.addSimple( + title: "UniqueDeque prepend, reserving capacity", + input: [Int].self + ) { input in + input.withUnsafeBufferPointer { + prependReserveCapacity($0) + } + } + + self.addSimple( + title: "UniqueDeque random insertions", + input: Insertions.self + ) { insertions in + insertions.values.withUnsafeBufferPointer { + randomInsertions($0) + } + } + + self.add( + title: "UniqueDeque sequential iteration", + input: [Int].self + ) { input in + let deque = UniqueDeque(copying: input) + return { timer in + sequentialIteration(deque) + } + } + } +} diff --git a/Benchmarks/Sources/RustBenchmarks/VecDequeBenchmarks.rs b/Benchmarks/Sources/RustBenchmarks/VecDequeBenchmarks.rs new file mode 100644 index 00000000..bfe4ee24 --- /dev/null +++ b/Benchmarks/Sources/RustBenchmarks/VecDequeBenchmarks.rs @@ -0,0 +1,138 @@ +use std::alloc::{alloc, dealloc, Layout}; +use std::collections::VecDeque; +use std::hint::black_box; + +#[no_mangle] +unsafe extern "C" fn rust_vecdeque_create( + mut start: *const isize, + count: isize +) -> *mut VecDeque { + let layout = Layout::new::>(); + let allocated = alloc(layout) as *mut VecDeque; + + let mut vec_deque = VecDeque::with_capacity(count as usize); + + for _ in 0..count { + vec_deque.push_back(start.read()); + start = start.add(1); + } + + allocated.write(vec_deque); + + allocated +} + +#[no_mangle] +unsafe extern "C" fn rust_vecdeque_destroy(ptr: *mut VecDeque) { + ptr.drop_in_place(); + dealloc(ptr as *mut u8, Layout::new::>()); +} + +#[no_mangle] +extern "C" fn rust_vecdeque_from_int_range(count: isize) { + let mut vd = VecDeque::default(); + + for i in 0..count { + vd.push_back(black_box(i)); + } + + black_box(&vd); +} + +#[no_mangle] +unsafe extern "C" fn rust_vecdeque_from_int_buffer( + mut start: *const isize, + count: isize +) { + let mut vd = VecDeque::with_capacity(count as usize); + + for _ in 0..count { + vd.push_back(start.read()); + start = start.add(1); + } + + black_box(&vd); +} + +#[no_mangle] +unsafe extern "C" fn rust_vecdeque_append_integers( + mut start: *const isize, + count: isize +) { + let mut vd = VecDeque::default(); + + for _ in 0..count { + vd.push_back(start.read()); + start = start.add(1); + } + + black_box(&vd); +} + +#[no_mangle] +unsafe extern "C" fn rust_vecdeque_append_integers_with_capacity( + mut start: *const isize, + count: isize +) { + let mut vd = VecDeque::with_capacity(count as usize); + + for _ in 0..count { + vd.push_back(start.read()); + start = start.add(1); + } + + black_box(&vd); +} + +#[no_mangle] +unsafe extern "C" fn rust_vecdeque_prepend_integers( + mut start: *const isize, + count: isize +) { + let mut vd = VecDeque::default(); + + for _ in 0..count { + vd.push_front(start.read()); + start = start.add(1); + } + + black_box(&vd); +} + +#[no_mangle] +unsafe extern "C" fn rust_vecdeque_prepend_integers_with_capacity( + mut start: *const isize, + count: isize +) { + let mut vd = VecDeque::with_capacity(count as usize); + + for _ in 0..count { + vd.push_front(start.read()); + start = start.add(1); + } + + black_box(&vd); +} + +#[no_mangle] +unsafe extern "C" fn rust_vecdeque_random_insertions( + start: *const isize, + count: isize +) { + let mut deque = VecDeque::new(); + + for i in 0..count { + deque.insert(i as usize, start.wrapping_add(i as usize).read()); + } + + black_box(&deque); +} + +#[no_mangle] +unsafe extern "C" fn rust_vecdeque_iterate(ptr: *mut u8) { + let deque_ptr = ptr as *mut VecDeque; + + for e in &*deque_ptr { + black_box(e); + } +} diff --git a/Benchmarks/Sources/RustBenchmarks/dummy.swift b/Benchmarks/Sources/RustBenchmarks/dummy.swift new file mode 100644 index 00000000..e69de29b diff --git a/Benchmarks/Sources/benchmark-tool/main.swift b/Benchmarks/Sources/benchmark-tool/main.swift index 1a9f7ab2..49cf1d3e 100644 --- a/Benchmarks/Sources/benchmark-tool/main.swift +++ b/Benchmarks/Sources/benchmark-tool/main.swift @@ -31,6 +31,8 @@ benchmark.addSetBenchmarks() benchmark.addDictionaryBenchmarks() benchmark.addTreeDictionaryBenchmarks() benchmark.addDequeBenchmarks() +benchmark.addRigidDequeBenchmarks() +benchmark.addUniqueDequeBenchmarks() benchmark.addOrderedSetBenchmarks() benchmark.addOrderedDictionaryBenchmarks() #if false @@ -41,6 +43,7 @@ benchmark.addHeapBenchmarks() benchmark.addBitSetBenchmarks() benchmark.addTreeSetBenchmarks() benchmark.addCppBenchmarks() +benchmark.addRustBenchmarks() benchmark.addBigStringBenchmarks() #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) benchmark.addFoundationBenchmarks() diff --git a/Package.swift b/Package.swift index 8a1903e5..3c7c5a57 100644 --- a/Package.swift +++ b/Package.swift @@ -12,7 +12,7 @@ import PackageDescription -#if false // FIXME: Disabled while we're debugging a runtime crash (rdar://150240032) +// FIXME: This can sometimes induce a runtime crash (rdar://150240032) let _traits: Set = [ .default( enabledTraits: [ @@ -35,7 +35,6 @@ let _traits: Set = [ types before they ship. """), ] -#endif // This package recognizes the conditional compilation flags listed below. // To use enable them, uncomment the corresponding lines or define them @@ -43,9 +42,9 @@ let _traits: Set = [ // // swift build -Xswiftc -DCOLLECTIONS_INTERNAL_CHECKS var defines: [SwiftSetting] = [ -// .define( -// "COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW", -// .when(traits: ["UnstableContainersPreview"])), + .define( + "COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW", + .when(traits: ["UnstableContainersPreview"])), .define( "COLLECTIONS_UNSTABLE_SORTED_COLLECTIONS", .when(traits: ["UnstableSortedCollections"])), @@ -80,7 +79,10 @@ var defines: [SwiftSetting] = [ // This removes the distinct modules for each data structure, instead // putting them all directly into the `Collections` module. // Note: This is a source-incompatible variation of the default configuration. -// "COLLECTIONS_SINGLE_MODULE", +// .define("COLLECTIONS_SINGLE_MODULE"), + + // Enables longer, more exhaustive tests. +// .define("COLLECTIONS_LONG_TESTS"), ] let availabilityMacros: KeyValuePairs = [ @@ -104,8 +106,8 @@ let extraSettings: [SwiftSetting] = [ .enableExperimentalFeature("Lifetimes"), .enableExperimentalFeature("InoutLifetimeDependence"), .enableExperimentalFeature("SuppressedAssociatedTypes"), -// .enableExperimentalFeature("AddressableParameters"), -// .enableExperimentalFeature("AddressableTypes"), + .enableExperimentalFeature("AddressableParameters"), + .enableExperimentalFeature("AddressableTypes"), // Note: if you touch these, please make sure to also update the similar lists in // CMakeLists.txt and Xcode/Shared.xcconfig. @@ -266,7 +268,7 @@ let targets: [CustomTarget] = [ .target( kind: .exported, name: "DequeModule", - dependencies: ["InternalCollectionsUtilities"], + dependencies: ["ContainersPreview", "InternalCollectionsUtilities"], exclude: ["CMakeLists.txt"]), .target( kind: .test, @@ -359,6 +361,6 @@ let _targets: [Target] = targets.map { $0.toTarget() } let package = Package( name: "swift-collections", products: _products, - traits: [], //_traits, + traits: _traits, targets: _targets ) diff --git a/Package@swift-6.0.swift b/Package@swift-6.0.swift index e04dc722..701b2265 100644 --- a/Package@swift-6.0.swift +++ b/Package@swift-6.0.swift @@ -50,6 +50,9 @@ var defines: [String] = [ // putting them all directly into the `Collections` module. // Note: This is a source-incompatible variation of the default configuration. // "COLLECTIONS_SINGLE_MODULE", + + // Enables longer, more exhaustive tests. +// "COLLECTIONS_LONG_TESTS", ] let availabilityMacros: KeyValuePairs = [ @@ -273,7 +276,7 @@ let targets: [CustomTarget] = [ .target( kind: .exported, name: "DequeModule", - dependencies: ["InternalCollectionsUtilities"], + dependencies: ["ContainersPreview", "InternalCollectionsUtilities"], exclude: ["CMakeLists.txt"]), .target( kind: .test, diff --git a/README.md b/README.md index 10de447b..c357f14b 100644 --- a/README.md +++ b/README.md @@ -10,25 +10,28 @@ Read more about the package, and the intent behind it, in the [announcement on s The package currently provides the following implementations: -- [`BitSet`][BitSet] and [`BitArray`][BitArray], dynamic bit collections. +- [`UniqueArray`][UniqueArray] and [`RigidArray`][RigidArray], noncopyable array variants trading some of `Array`'s flexibility for more predictable performance. -- [`Deque`][Deque], a double-ended queue backed by a ring buffer. Deques are range-replaceable, mutable, random-access collections. - -- [`Heap`][Heap], a min-max heap backed by an array, suitable for use as a priority queue. +- [`Deque`][Deque], [`UniqueDeque`][UniqueDeque] and [`RigidDeque`][RigidDeque], variants of a double-ended queue type backed by a ring buffer. Deques are range-replaceable, mutable, random-access collections. - [`OrderedSet`][OrderedSet], a variant of the standard `Set` where the order of items is well-defined and items can be arbitrarily reordered. Uses a `ContiguousArray` as its backing store, augmented by a separate hash table of bit packed offsets into it. - [`OrderedDictionary`][OrderedDictionary], an ordered variant of the standard `Dictionary`, providing similar benefits. -- [`TreeSet`][TreeSet] and [`TreeDictionary`][TreeDictionary], persistent hashed collections implementing Compressed Hash-Array Mapped Prefix Trees (CHAMP). These work similar to the standard `Set` and `Dictionary`, but they excel at use cases that mutate shared copies, offering dramatic memory savings and radical time improvements. +- [`BitSet`][BitSet] and [`BitArray`][BitArray], dynamic bit collections. -- [`UniqueArray`][UniqueArray] and [`RigidArray`][RigidArray], noncopyable array variants trading some of `Array`'s flexibility for more predictable performance. +- [`Heap`][Heap], a min-max heap backed by an array, suitable for use as a priority queue. + +- [`TreeSet`][TreeSet] and [`TreeDictionary`][TreeDictionary], persistent hashed collections implementing Compressed Hash-Array Mapped Prefix Trees (CHAMP). These work similar to the standard `Set` and `Dictionary`, but they excel at use cases that mutate shared copies, offering dramatic memory savings and radical time improvements. - [`TrailingArray`][TrailingArray], a low-level, ownership-aware variant of `ManagedBuffer`, for interoperability with C constructs that consist of a fixed-size header directly followed by variable-size storage buffer. [BitSet]: https://swiftpackageindex.com/apple/swift-collections/documentation/bitcollections/bitset [BitArray]: https://swiftpackageindex.com/apple/swift-collections/documentation/bitcollections/bitarray [Deque]: https://swiftpackageindex.com/apple/swift-collections/documentation/dequemodule/deque +[RigidDeque]: https://swiftpackageindex.com/apple/swift-collections/documentation/dequemodule/rigiddeque +[UniqueDeque]: https://swiftpackageindex.com/apple/swift-collections/documentation/dequemodule/uniquedeque +[Deque]: https://swiftpackageindex.com/apple/swift-collections/documentation/dequemodule/deque [Heap]: https://swiftpackageindex.com/apple/swift-collections/documentation/heapmodule/heap [OrderedSet]: https://swiftpackageindex.com/apple/swift-collections/documentation/orderedcollections/orderedset [OrderedDictionary]: https://swiftpackageindex.com/apple/swift-collections/documentation/orderedcollections/ordereddictionary @@ -57,7 +60,7 @@ The Swift Collections package is source stable. The version numbers follow [Sema ### Public API -The public API of version 1.3 of the `swift-collections` package consists of non-underscored declarations that are marked `public` in the `Collections`, `BitCollections`, `DequeModule`, `HeapModule`, `OrderedCollections` and `HashTreeCollections` modules. +The public API of version 1.4 of the `swift-collections` package consists of non-underscored declarations that are marked `public` in the `Collections`, `BasicContainers`, `BitCollections`, `DequeModule`, `HeapModule`, `OrderedCollections` and `HashTreeCollections` modules. Interfaces that aren't part of the public API may continue to change in any release, including patch releases. @@ -68,9 +71,11 @@ By "underscored declarations" we mean declarations that have a leading underscor - `_FooModule.Bar` (underscored module) - `FooModule.Bar.init(_value:)` (underscored initializer) +Interfaces that get enabled by opting into either of the `UnstableContainersPreview` or `UnstableSortedCollections` package traits are not part of the public API; those interfaces may get removed or changed in any release. + If you have a use case that requires using underscored (or otherwise non-public) 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. -This source compatibility promise only applies to swift-collection when built as a Swift package. (The repository also contains unstable configurations for building swift-collections using CMake and Xcode. These configurations are provided for internal Swift project use only -- such as for building the (private) swift-collections binaries that ship within Swift toolchains.) +This source compatibility promise only applies to swift-collections when built as a Swift package. (The repository also contains unstable configurations for building swift-collections using CMake and Xcode. These configurations are provided for internal Swift project use only -- such as for building the (private) swift-collections binaries that ship within Swift toolchains.) Note that the files in the `Tests`, `Utils`, `Documentation`, `Xcode`, `cmake` and `Benchmarks` subdirectories may change at whim; they may be added, modified or removed in any new release. Do not rely on anything about them. @@ -88,6 +93,7 @@ The following table maps package releases to their minimum required Swift toolch | swift-collections 1.1.x | >= Swift 5.7.2 | >= Xcode 14.2 | | swift-collections 1.2.x | >= Swift 5.10.0 | >= Xcode 15.3 | | swift-collections 1.3.x | >= Swift 6.0.3 | >= Xcode 16.2 | +| swift-collections 1.4.x | >= Swift 6.0.3 | >= Xcode 16.2 | (Note: the package has no minimum deployment target, so while it does require clients to use a recent Swift toolchain to build it, the code itself is able to run on any OS release that supports running Swift code.) @@ -104,7 +110,7 @@ let package = Package( dependencies: [ .package( url: "https://github.com/apple/swift-collections.git", - .upToNextMinor(from: "1.3.0") // or `.upToNextMajor + .upToNextMinor(from: "1.4.0") // or `.upToNextMajor ) ], targets: [ @@ -134,15 +140,16 @@ We maintain separate branches for each minor version of the package: | ----------------------- | ----------- | -------- | | swift-collections 1.0.x | release/1.0 | Obsolete | | swift-collections 1.1.x | release/1.1 | Obsolete | -| swift-collections 1.2.x | release/1.2 | Bugfixes only | +| swift-collections 1.2.x | release/1.2 | Obsolete | | swift-collections 1.3.x | release/1.3 | Bugfixes only | +| swift-collections 1.4.x | release/1.4 | Bugfixes only | | n.a. | main | Feature work towards next minor release | Changes must land on the branch corresponding to the earliest release that they will need to ship on. They are periodically propagated to subsequent branches, in the following direction: -`release/1.1` → `release/1.2` → `release/1.3` → `main` +`release/1.3` → `release/1.4` → `main` -For example, anything landing on `release/1.2` will eventually appear on `release/1.3` and then `main` too; there is no need to file standalone PRs for each release line. Change propagation is not instantaneous, as it currently requires manual work -- it is performed by project maintainers. +For example, anything landing on `release/1.3` will eventually appear on `release/1.4` and then `main` too; there is no need to file standalone PRs for each release line. Change propagation is not instantaneous, as it currently requires manual work -- it is performed by project maintainers. ### Working on the package @@ -172,7 +179,7 @@ By submitting a pull request, you represent that you have the right to license y #### Proposing the addition of a new data structure -**Note:** As of 2025, we are fully preoccupied with refactoring our existing data structures to support noncopyable and/or nonescapable element types; this includes designing new container protocols around them. I don't expect we'll have capacity to work on any major new data structure implementations until this effort is complete. +**Note:** We are currently fully preoccupied with refactoring our existing data structures to support noncopyable and/or nonescapable element types; this includes designing new container protocols around them. I don't expect we'll have capacity to work on any major new data structure implementations until this effort is complete. ### Code of Conduct diff --git a/Sources/BasicContainers/CMakeLists.txt b/Sources/BasicContainers/CMakeLists.txt index 94586ef4..d0c1af97 100644 --- a/Sources/BasicContainers/CMakeLists.txt +++ b/Sources/BasicContainers/CMakeLists.txt @@ -1,7 +1,7 @@ #[[ This source file is part of the Swift Collections Open Source Project -Copyright (c) 2022 - 2025 Apple Inc. and the Swift project authors +Copyright (c) 2022 - 2026 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See https://swift.org/LICENSE.txt for license information @@ -23,18 +23,30 @@ else() endif() target_sources(${module_name} PRIVATE - "RigidArray.swift" - "RigidArray+Append.swift" - "RigidArray+Experimental.swift" - "RigidArray+Initializers.swift" - "RigidArray+Insertions.swift" - "RigidArray+Removals.swift" - "RigidArray+Replacements.swift" - "UniqueArray.swift" - "UniqueArray+Append.swift" - "UniqueArray+Experimental.swift" - "UniqueArray+Initializers.swift" - "UniqueArray+Insertions.swift" - "UniqueArray+Removals.swift" - "UniqueArray+Replacements.swift" + "RigidArray/RigidArray.swift" + "RigidArray/RigidArray+Append.swift" + "RigidArray/RigidArray+Consumption.swift" + "RigidArray/RigidArray+Container.swift" + "RigidArray/RigidArray+Deprecated.swift" + "RigidArray/RigidArray+Descriptions.swift" + "RigidArray/RigidArray+Equatable.swift" + "RigidArray/RigidArray+Experimental.swift" + "RigidArray/RigidArray+Hashable.swift" + "RigidArray/RigidArray+Initializers.swift" + "RigidArray/RigidArray+Insertions.swift" + "RigidArray/RigidArray+Removals.swift" + "RigidArray/RigidArray+Replacements.swift" + "UniqueArray/UniqueArray.swift" + "UniqueArray/UniqueArray+Append.swift" + "UniqueArray/UniqueArray+Consumption.swift" + "UniqueArray/UniqueArray+Container.swift" + "UniqueArray/UniqueArray+Deprecated.swift" + "UniqueArray/UniqueArray+Descriptions.swift" + "UniqueArray/UniqueArray+Equatable.swift" + "UniqueArray/UniqueArray+Experimental.swift" + "UniqueArray/UniqueArray+Hashable.swift" + "UniqueArray/UniqueArray+Initializers.swift" + "UniqueArray/UniqueArray+Insertions.swift" + "UniqueArray/UniqueArray+Removals.swift" + "UniqueArray/UniqueArray+Replacements.swift" ) diff --git a/Sources/BasicContainers/RigidArray+Append.swift b/Sources/BasicContainers/RigidArray/RigidArray+Append.swift similarity index 82% rename from Sources/BasicContainers/RigidArray+Append.swift rename to Sources/BasicContainers/RigidArray/RigidArray+Append.swift index f1c57ee4..0d4d58f1 100644 --- a/Sources/BasicContainers/RigidArray+Append.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Append.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors +// Copyright (c) 2024 - 2026 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information @@ -39,13 +39,12 @@ extension RigidArray where Element: ~Copyable { /// then this returns the given item without appending it; otherwise it /// returns nil. /// - /// - Parameter item: The element to append to the collection. + /// - Parameter item: The element to append to the array. /// - Returns: `item` if the array is full; otherwise nil. /// /// - Complexity: O(1) @inlinable public mutating func pushLast(_ item: consuming Element) -> Element? { - // FIXME: Remove this in favor of a standard algorithm. if isFull { return item } append(item) return nil @@ -60,29 +59,33 @@ extension RigidArray where Element: ~Copyable { /// If the array does not have sufficient capacity to store the new items in /// the buffer, then this triggers a runtime error. /// - /// - Parameters - /// - count: The number of items to append to the array. - /// - body: A callback that gets called precisely once to directly - /// populate newly reserved storage within the array. The function - /// is allowed to initialize fewer than `count` items. The array is - /// appended however many items the callback adds to the output span - /// before it returns (or before it throws an error). + /// If the callback fails to fully populate its output span or if + /// it throws an error, then the array keeps all items that were + /// successfully initialized before the callback terminated the insertion. /// - /// - Complexity: O(`count`) + /// - Parameters: + /// - newItemCount: The number of items to append to the array. + /// - initializer: A callback that gets called at most once to directly + /// populate newly reserved storage within the array. The function + /// is allowed to initialize fewer than `newItemCount` items. + /// The array is appended however many items the callback adds to + /// the output span before it returns (or before it throws an error). + /// + /// - Complexity: O(`newItemCount`) @_alwaysEmitIntoClient - public mutating func append( - count: Int, - initializingWith body: (inout OutputSpan) throws(E) -> Result - ) throws(E) -> Result { - // FIXME: This is extremely similar to `edit()`, except it provides a narrower span. - precondition(freeCapacity >= count, "RigidArray capacity overflow") - let buffer = _freeSpace._extracting(first: count) + public mutating func append( + addingCount newItemCount: Int, + initializingWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) { + precondition(newItemCount >= 0, "Cannot add a negative number of items") + precondition(freeCapacity >= newItemCount, "RigidArray capacity overflow") + let buffer = _freeSpace._extracting(first: newItemCount) var span = OutputSpan(buffer: buffer, initializedCount: 0) defer { _count &+= span.finalize(for: buffer) span = OutputSpan() } - return try body(&span) + return try initializer(&span) } } @@ -94,7 +97,7 @@ extension RigidArray where Element: ~Copyable { /// If the array does not have sufficient capacity to hold all items in the /// buffer, then this triggers a runtime error. /// - /// - Parameters + /// - Parameters: /// - items: A fully initialized buffer whose contents to move into /// the array. /// @@ -117,7 +120,7 @@ extension RigidArray where Element: ~Copyable { /// If the array does not have sufficient capacity to hold all items in its /// storage, then this triggers a runtime error. /// - /// - Parameters + /// - Parameters: /// - items: An input span whose contents need to be appended to this array. /// /// - Complexity: O(`items.count`) @@ -139,7 +142,7 @@ extension RigidArray where Element: ~Copyable { /// If the array does not have sufficient capacity to hold all items in its /// storage, then this triggers a runtime error. /// - /// - Parameters + /// - Parameters: /// - items: An output span whose contents need to be appended to this array. /// /// - Complexity: O(`items.count`) @@ -161,7 +164,7 @@ extension RigidArray where Element: ~Copyable { /// If the target array does not have sufficient capacity to hold all items /// in the source array, then this triggers a runtime error. /// - /// - Parameters + /// - Parameters: /// - items: An array whose items to move to the end of this array. /// /// - Complexity: O(`items.count`) @@ -170,10 +173,8 @@ extension RigidArray where Element: ~Copyable { moving items: inout RigidArray ) { // FIXME: Remove this in favor of a generic algorithm over range-replaceable containers - unsafe items._unsafeEdit { buffer, count in - let source = buffer._extracting(first: count) - unsafe self.append(moving: source) - count = 0 + items.edit { span in + self.append(moving: &span) } } } @@ -187,9 +188,8 @@ extension RigidArray where Element: ~Copyable { /// If the target array does not have sufficient capacity to hold all items /// in the source array, then this triggers a runtime error. /// - /// - Parameters - /// - items: A fully initialized buffer whose contents to move into - /// the array. + /// - Parameters: + /// - items: A container whose contents to move into this array. /// /// - Complexity: O(`items.count`) @_alwaysEmitIntoClient @@ -210,7 +210,7 @@ extension RigidArray { /// If the array does not have sufficient capacity to hold all items in the /// buffer, then this triggers a runtime error. /// - /// - Parameters + /// - Parameters: /// - newElements: A fully initialized buffer whose contents to copy into /// the array. /// @@ -233,7 +233,7 @@ extension RigidArray { /// If the array does not have sufficient capacity to hold all items in the /// buffer, then this triggers a runtime error. /// - /// - Parameters + /// - Parameters: /// - newElements: A fully initialized buffer whose contents to copy into /// the array. /// @@ -250,7 +250,7 @@ extension RigidArray { /// If the array does not have sufficient capacity to hold all items in the /// span, then this triggers a runtime error. /// - /// - Parameters + /// - Parameters: /// - newElements: A span whose contents to copy into the array. /// /// - Complexity: O(`newElements.count`) @@ -274,9 +274,9 @@ extension RigidArray { #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW @inlinable internal mutating func _append< - Source: Container & ~Copyable & ~Escapable + Source: BorrowingSequence & ~Copyable & ~Escapable >( - copyingContainer newElements: borrowing Source + copying newElements: borrowing Source ) { let target = _freeSpace _count += newElements._copyContents(intoPrefixOf: target) @@ -284,23 +284,23 @@ extension RigidArray { #endif #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW - /// Copies the elements of a container to the end of this array. + /// Copies the elements of a borrowing sequence to the end of this array. /// /// If the array does not have sufficient capacity to hold all items in the - /// source iterable, then this triggers a runtime error. + /// source sequence, then this triggers a runtime error. /// - /// - Parameters + /// - Parameters: /// - newElements: A container whose contents to copy into the array. /// /// - Complexity: O(`newElements.count`) @_alwaysEmitIntoClient @inline(__always) public mutating func append< - Source: Container & ~Copyable & ~Escapable + Source: BorrowingSequence & ~Copyable & ~Escapable >( copying newElements: borrowing Source ) { - _append(copyingContainer: newElements) + _append(copying: newElements) } #endif @@ -309,7 +309,7 @@ extension RigidArray { /// If the array does not have sufficient capacity to hold all items in the /// sequence, then this triggers a runtime error. /// - /// - Parameters + /// - Parameters: /// - newElements: The new elements to copy into the array. /// /// - Complexity: O(*m*), where *m* is the length of `newElements`. @@ -326,21 +326,21 @@ extension RigidArray { } #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW - /// Copies the elements of a container to the end of this array. + /// Copies the elements of a borrowing sequence to the end of this array. /// /// If the array does not have sufficient capacity to hold all items in the - /// source iterable, then this triggers a runtime error. + /// source sequence, then this triggers a runtime error. /// - /// - Parameters + /// - Parameters: /// - newElements: The new elements to copy into the array. /// /// - Complexity: O(*m*), where *m* is the length of `newElements`. @_alwaysEmitIntoClient @inline(__always) public mutating func append< - Source: Container & Sequence + Source: BorrowingSequence & Sequence >(copying newElements: Source) { - _append(copyingContainer: newElements) + _append(copying: newElements) } #endif } diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Consumption.swift b/Sources/BasicContainers/RigidArray/RigidArray+Consumption.swift new file mode 100644 index 00000000..39ff9bb9 --- /dev/null +++ b/Sources/BasicContainers/RigidArray/RigidArray+Consumption.swift @@ -0,0 +1,128 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2024 - 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + /// Remove the specified subrange of items from this array, + /// passing an input span to the given function to consume them in place. + /// + /// - Parameter subrange: The subrange of items to consume from this array. + /// - Parameter consumer: A function taking an input span of the removed items, + /// allowing them to be consumed straight out of the array's storage. + /// The function is not required to consume all items in the span; + /// however, the span's remaining items will still be removed from + /// the array. + /// + /// - Complexity: O(`self.count`) + @_alwaysEmitIntoClient + public mutating func consume( + _ subrange: Range, + consumingWith consumer: (inout InputSpan) -> Void + ) { + _checkValidBounds(subrange) + guard !subrange.isEmpty else { + var span = InputSpan() + consumer(&span) + return + } + let buffer = unsafe _storage.extracting(subrange) + var span = InputSpan(buffer: buffer, initializedCount: buffer.count) + + consumer(&span) + _ = consume span + + _closeGap(at: subrange.lowerBound, count: subrange.count) + _count -= subrange.count + } + + /// Remove the specified subrange of items from this deque, + /// passing a series of input spans to a given callback function to consume + /// them in place. + /// + /// The callback is not required to fully consume the contents of its + /// argument; any items it leaves in the input span get automatically + /// consumed. The underlying storage isn't necessarily contiguous, so + /// the callback may be called more than once, whether or not it fully + /// consumes its input. If the specified range is empty, the callback + /// may not be called at all. + /// + /// - Parameter subrange: The subrange of items to consume from this array. + /// - Parameter consumer: A function taking an input span of the removed items, + /// allowing them to be consumed straight out of the array's storage. + /// The function is called at most once. + /// + /// - Complexity: O(`self.count`) + @_alwaysEmitIntoClient + @inline(__always) + public mutating func consume>( + _ subrange: R, + consumingWith consumer: (inout InputSpan) -> Void + ) { + consume(subrange.relative(to: indices), consumingWith: consumer) + } + + /// Remove all items currently in this array, passing an input + /// span to a given callback function to consume them in place. + /// + /// The callback is not required to fully consume the contents of its + /// argument; any items it leaves in the input span get automatically + /// consumed. + /// + /// - Parameter consumer: A function taking an input span of the removed items, + /// allowing them to be consumed straight out of the array's storage. + /// The function is called at most once. + /// + /// - Complexity: O(`self.count`) + @_alwaysEmitIntoClient + public mutating func consumeAll( + consumingWith consumer: (inout InputSpan) -> Void + ) { + consume(indices, consumingWith: consumer) + } + + /// Remove the specified number of items from the end of this array, + /// passing an input span to a given callback function to consume them in + /// place. + /// + /// The callback is not required to fully consume the contents of its + /// argument; any items it leaves in the input span get automatically + /// consumed. + /// + /// - Parameter n: The number of items to consume from the end of the array. + /// `n` must be greater than or equal to zero and must not exceed + /// the count of the array. + /// - Parameter consumer: A function taking an input span of the removed items, + /// allowing them to be consumed straight out of the array's storage. + /// The function is called at most once. + /// - Complexity: O(`n`) + @inline(__always) + @_alwaysEmitIntoClient + public mutating func consumeLast( + _ n: Int, + consumingWith consumer: (inout InputSpan) -> Void + ) { + precondition( + n >= 0 && n <= _count, + "Count of elements to consume is out of bounds") + self.consume(_count &- n ..< _count, consumingWith: consumer) + } +} +#endif + +#endif diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Container.swift b/Sources/BasicContainers/RigidArray/RigidArray+Container.swift new file mode 100644 index 00000000..2ac86747 --- /dev/null +++ b/Sources/BasicContainers/RigidArray/RigidArray+Container.swift @@ -0,0 +1,393 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2025 - 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +@available(SwiftStdlib 5.0, *) +extension RigidArray: BorrowingSequence where Element: ~Copyable { + public typealias BorrowingIterator = Span.BorrowingIterator + + @inlinable + public var estimatedCount: EstimatedCount { + .exactly(count) + } + + @_alwaysEmitIntoClient + @inline(__always) + public func makeBorrowingIterator() -> BorrowingIterator { + self.span.makeBorrowingIterator() + } +} +#endif + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +@available(SwiftStdlib 5.0, *) +extension RigidArray: Container where Element: ~Copyable { +} +#endif + +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + /// A Boolean value indicating whether this array contains no elements. + /// + /// - Complexity: O(1) + @inlinable + @inline(__always) + public var isEmpty: Bool { count == 0 } + + /// The number of elements in this array. + /// + /// - Complexity: O(1) + @inlinable + @inline(__always) + public var count: Int { _count } +} + +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + /// A type that represents a position in the array: an integer offset from the + /// start. + /// + /// Valid indices consist of the position of every element and a "past the + /// end” position that’s not valid for use as a subscript argument. + public typealias Index = Int + + /// The position of the first element in a nonempty array. This is always zero. + /// + /// - Complexity: O(1) + @inlinable + @inline(__always) + public var startIndex: Int { 0 } + + /// The array’s "past the end” position—that is, the position one greater than + /// the last valid subscript argument. This is always equal to the array's + /// count. + /// + /// - Complexity: O(1) + @inlinable + @inline(__always) + public var endIndex: Int { count } + + /// The range of indices that are valid for subscripting the array. + /// + /// - Complexity: O(1) + @inlinable + @inline(__always) + public var indices: Range { unsafe Range(uncheckedBounds: (0, count)) } + + @_alwaysEmitIntoClient + @_transparent + package func _checkItemIndex(_ index: Int) { + precondition( + UInt(bitPattern: index) < UInt(bitPattern: _count), + "Index out of bounds") + } + + @_alwaysEmitIntoClient + @_transparent + package func _checkValidIndex(_ index: Int) { + precondition( + UInt(bitPattern: index) <= UInt(bitPattern: _count), + "Index out of bounds") + } + + @_alwaysEmitIntoClient + @_transparent + package func _checkValidBounds(_ subrange: Range) { + precondition( + subrange.lowerBound >= 0 && subrange.upperBound <= _count, + "Index range out of bounds") + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + @inlinable @inline(__always) + internal func _ptr(to index: Int) -> UnsafePointer { + _checkItemIndex(index) + let p = _storage.baseAddress.unsafelyUnwrapped.advanced(by: index) + return UnsafePointer(p) + } + + @inlinable @inline(__always) + internal mutating func _mutablePtr( + to index: Int + ) -> UnsafeMutablePointer { + _checkItemIndex(index) + return _storage.baseAddress.unsafelyUnwrapped.advanced(by: index) + } + + /// Accesses the element at the specified position. + /// + /// - Parameter position: The position of the element to access. + /// The position must be a valid index of the array that is not equal + /// to the `endIndex` property. + /// + /// - Complexity: O(1) + @inlinable + public subscript(position: Int) -> Element { + @inline(__always) + unsafeAddress { + _ptr(to: position) + } + @inline(__always) + unsafeMutableAddress { + _mutablePtr(to: position) + } + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + /// Exchanges the values at the specified indices of the array. + /// + /// Both parameters must be valid indices of the array and not equal to + /// endIndex. Passing the same index as both `i` and `j` has no effect. + /// + /// - Parameter i: The index of the first value to swap. + /// - Parameter j: The index of the second valud to swap. + /// + /// - Complexity: O(1) + @inlinable + public mutating func swapAt(_ i: Int, _ j: Int) { + _checkItemIndex(i) + _checkItemIndex(j) + unsafe _items.swapAt(i, j) + } +} +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + /// Returns the position immediately after the given index. + /// + /// - Note: To improve performance, this method does not validate that the + /// index is valid before incrementing it. Index validation is + /// deferred until the resulting index is used to access an element. + /// This optimization may be removed in future versions; do not rely on it. + /// + /// - Parameter index: A valid index of the array. `i` must be less + /// than `endIndex`. + /// - Returns: The index immediately following `i`. + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @inline(__always) + public func index(after index: Int) -> Int { index + 1 } + + /// Returns the position immediately before the given index. + /// + /// - Note: To improve performance, this method does not validate that the + /// index is valid before decrementing it. Index validation is + /// deferred until the resulting index is used to access an element. + /// This optimization may be removed in future versions; do not rely on it. + /// + /// - Parameter index: A valid index of the array. `i` must be greater + /// than `startIndex`. + /// - Returns: The index immediately preceding `i`. + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @inline(__always) + public func index(before index: Int) -> Int { index - 1 } + + /// Replaces the given index with its successor. + /// + /// - Note: To improve performance, this method does not validate that the + /// given index is valid before incrementing it. Index validation is + /// deferred until the resulting index is used to access an element. + /// This optimization may be removed in future versions; do not rely on it. + /// + /// - Parameter index: A valid index of the array. `i` must be less + /// than `endIndex`. + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @inline(__always) + public func formIndex(after index: inout Int) { index += 1 } + + /// Replaces the given index with its predecessor. + /// + /// - Note: To improve performance, this method does not validate that the + /// given index is valid before decrementing it. Index validation is + /// deferred until the resulting index is used to access an element. + /// This optimization may be removed in future versions; do not rely on it. + /// + /// - Parameter index: A valid index of the array. `i` must be greater than + /// `startIndex`. + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @inline(__always) + public func formIndex(before index: inout Int) { index -= 1 } + + /// Returns an index that is the specified distance from the given index. + /// + /// The value passed as `n` must not offset `index` beyond the bounds of the + /// array. + /// + /// - Note: To improve performance, this method does not validate that the + /// given index is valid before offseting it. Index validation is + /// deferred until the resulting index is used to access an element. + /// This optimization may be removed in future versions; do not rely on it. + /// + /// - Parameter index: A valid index of the array. + /// - Parameter n: The distance by which to offset `index`. + /// - Returns: An index offset by distance from `index`. If `n` is positive, + /// this is the same value as the result of `n` calls to `index(after:)`. + /// If `n` is negative, this is the same value as the result of `abs(n)` + /// calls to `index(before:)`. + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @inline(__always) + public func index(_ index: Int, offsetBy n: Int) -> Int { + index + n + } + + /// Returns the distance between two indices. + /// + /// - Note: To improve performance, this method does not validate that the + /// given index is valid before offseting it. Index validation is + /// deferred until the resulting index is used to access an element. + /// This optimization may be removed in future versions; do not rely on it. + /// + /// - Parameter start: A valid index of the collection. + /// - Parameter end: Another valid index of the collection. If end is equal + /// to start, the result is zero. + /// - Returns: The distance between `start` and `end`. + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @inline(__always) + public func distance(from start: Index, to end: Index) -> Int { + end - start + } + + /// Offsets the given index by the specified distance, but no further than + /// the given limiting index. + /// + /// If the operation was able to offset `index` by exactly the requested + /// number of steps without hitting `limit`, then on return `n` is set to `0`, + /// and `index` is set to the adjusted index. + /// + /// If the operation hits the limit before it can take the requested number + /// of steps, then on return `index` is set to `limit`, and `n` is set + /// to the number of steps that couldn't be taken. + /// + /// The value passed as `n` must not offset `index` beyond the bounds of the + /// container, unless the index passed as `limit` prevents offsetting beyond + /// those bounds. + /// + /// - Note: To improve performance, this method does not validate that the + /// given index is valid before offseting it. Index validation is + /// deferred until the resulting index is used to access an element. + /// This optimization may be removed in future versions; do not rely on it. + /// + /// - Parameter index: A valid index of the array. On return, `index` is + /// set to `limit` if + /// - Parameter n: The distance to offset `index`. + /// On return, `n` is set to zero if the operation succeeded without + /// hitting the limit; otherwise, `n` reflects the number of steps that + /// couldn't be taken. + /// - Parameter limit: A valid index of the array to use as a limit. + /// If `n > 0`, a limit that is less than `index` has no effect. + /// Likewise, if `n < 0`, a limit that is greater than `index` has no + /// effect. + /// - Complexity: O(1) + @_alwaysEmitIntoClient + public func formIndex( + _ index: inout Index, offsetBy n: inout Int, limitedBy limit: Index + ) { + index._advance(by: &n, limitedBy: limit) + } + + /// Return a span over the array's storage that begins with the element at + /// the given index, and extends to the end of the contiguous storage chunk + /// that contains it, but no more than `maximumCount` items. + /// + /// On return, the index is updated to address the next item following the + /// end of the returned span. + /// + /// This method can be used to efficiently process the items of a container in + /// bulk, by directly iterating over its piecewise contiguous pieces of + /// storage: + /// + /// var index = items.startIndex + /// while true { + /// let span = items.nextSpan(after: &index, maximumCount: 4) + /// if span.isEmpty { break } + /// // Process items in `span` + /// } + /// + /// The `maximumCount` argument gives the caller control over the number of + /// items it receives from the iterator. This lets the caller avoid getting + /// more elements than it would be able to immediately process, which would + /// significantly complicate container use. + /// + /// If the caller is able to process any number available items, it can signal + /// that by passing `Int.max` as the `maximumCount`, or simply by calling the + /// `nexSpan(after:)` method, which does precisely that. This is frequently + /// the case when the caller simply wants to iterate over the entire + /// container in a single loop. + /// + /// `maximumCount` sets an upper bound. To read a specific number of items, + /// the caller usually needs to invoke `nextSpan` in a loop: + /// + /// var items: some Container + /// var index = items.startIndex + /// var remainder = numberOfItemsToRead + /// while remainder > 0 { + /// let next = items.nextSpan(after: &index, maximumCount: remainder) + /// guard !next.isEmpty else { + /// // Container does not have enough items + /// break + /// } + /// remainder -= next.count + /// // Process items in `next` + /// } + /// + /// - Note: The spans returned by this method are not guaranteed to be + /// disjunct. Some containers may use the same storage chunk (or parts of a + /// storage chunk) multiple times, to repeat their contents. + /// + /// - Note: Repeated invocations of `nextSpan` on the same container and index + /// are not guaranteed to return identical results. (This is particularly + /// the case with containers that can store contents in their "inline" + /// representation. Such containers may not always have a unique address + /// in memory; the locations of the spans exposed by this method may vary + /// between different borrows of the same container.) + /// + /// - Parameter index: A valid index in the container, including the end + /// index. On return, this index is advanced by the count of the resulting + /// span, to simplify iteration. + /// - Parameter maximumCount: The maximum number of items the caller is able + /// to process immediately. `maximumCount` must be greater than zero. + /// If you are able to process an arbitrary number of items, set + /// `maximumCount` to `Int.max`, or call the `nextSpan(after:)` method. + /// - Returns: A span over contiguous storage that starts at the given index. + /// If the input index is the end index, then this returns an empty span. + /// Otherwise the result is non-empty, with its first element matching the + /// element at the input index. + /// - Complexity: O(1) + @inlinable + @_lifetime(borrow self) + public func nextSpan( + after index: inout Int, maximumCount: Int + ) -> Span { + _checkValidIndex(index) + precondition(maximumCount > 0, "maximumCount must be positive") + let start = index + index = start &+ Swift.min(maximumCount, _count &- start) + return _span(in: Range(uncheckedBounds: (start, index))) + } +} + +#endif + diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Deprecated.swift b/Sources/BasicContainers/RigidArray/RigidArray+Deprecated.swift new file mode 100644 index 00000000..8f84a257 --- /dev/null +++ b/Sources/BasicContainers/RigidArray/RigidArray+Deprecated.swift @@ -0,0 +1,439 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2024 - 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + /// Append a given number of items to the end of this array by populating + /// an output span. + /// + /// If the array does not have sufficient capacity to store the new items in + /// the buffer, then this triggers a runtime error. + /// + /// - Parameters: + /// - count: The number of items to append to the array. + /// - initializer: A callback that gets called at most once to directly + /// populate newly reserved storage within the array. The function + /// is allowed to initialize fewer than `count` items. The array is + /// appended however many items the callback adds to the output span + /// before it returns (or before it throws an error). + /// + /// - Complexity: O(`count`) + @available(*, deprecated, renamed: "append(addingCount:initializingWith:)") + @_alwaysEmitIntoClient + @inline(__always) + public mutating func append( + count: Int, + initializingWith initializer: (inout OutputSpan) throws(E) -> Result + ) throws(E) -> Result { + var result: Result? = nil + try append(addingCount: count) { target throws(E) in + result = try initializer(&target) + } + return result.take()! + } + + /// Inserts a given number of new items into this array at the specified + /// position, using a callback to directly initialize array storage by + /// populating an output span. + /// + /// All existing elements at or following the specified position are moved to + /// make room for the new items. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// - Parameters: + /// - count: The number of items to insert into the array. + /// - index: The position at which to insert the new items. + /// `index` must be a valid index in the array. + /// - body: A callback that gets called exactly once to directly + /// populate newly reserved storage within the array. The function + /// is called with an empty output span of capacity matching the + /// supplied count, and it must fully populate it before returning. + /// + /// - Complexity: O(`self.count` + `count`) + @available(*, deprecated, renamed: "insert(addingCount:at:initializingWith:)") + @inlinable + public mutating func insert( + count: Int, + at index: Int, + initializingWith body: (inout OutputSpan) -> Result + ) -> Result { + var result: Result? = nil + self.insert(addingCount: count, at: index) { target in + result = body(&target) + } + return result! + } + + /// Replaces the specified range of elements by a given count of new items, + /// using a callback to directly initialize array storage by populating + /// an output span. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting room for the new elements starting at the + /// same location. The number of new elements need not match the number + /// of elements being removed. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, then + /// this method is equivalent to calling + /// `insert(count: newCount, at: subrange.lowerbound, initializingWith: body)`. + /// + /// Likewise, if you pass a zero for `newCount`, then this method + /// removes the elements in the given subrange without any replacement. + /// This case is more directly expressed by `removeSubrange(subrange)`. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newCount: the number of items to replace the old subrange. + /// - body: A callback that gets called exactly once to directly + /// populate newly reserved storage within the array. The function + /// is called with an empty output span of capacity `newCount`, + /// and it must fully populate it before returning. + /// + /// - Complexity: O(`self.count` + `newCount`) + @available(*, deprecated, renamed: "replace(removing:addingCapacity:initializingWith:)") + @inlinable + public mutating func replaceSubrange( + _ subrange: Range, + newCount: Int, + initializingWith body: (inout OutputSpan) -> Result + ) -> Result { + var result: Result? = nil + self.replace(removing: subrange, addingCount: newCount) { target in + result = body(&target) + } + return result! + } + + /// Replaces the specified range of elements by moving the elements of a + /// fully initialized buffer into their place. On return, the buffer is left + /// in an uninitialized state. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(moving:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: A fully initialized buffer whose contents to move into + /// the array. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @available(*, deprecated, renamed: "replace(removing:moving:)") + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + moving newElements: UnsafeMutableBufferPointer, + ) { + replace(removing: subrange, moving: newElements) + } + + /// Replaces the specified range of elements by moving the contents of an + /// output span into their place. On return, the span is left empty. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(moving:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - items: An output span whose contents are to be moved into the array. + /// + /// - Complexity: O(`self.count` + `items.count`) + @available(*, deprecated, renamed: "replace(removing:moving:)") + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + moving items: inout OutputSpan + ) { + replace(removing: subrange, moving: &items) + } + + /// Replaces the specified range of elements by moving the elements of a + /// another array into their place. On return, the source array + /// becomes empty, but it is not destroyed, and it preserves its original + /// storage capacity. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: An array whose contents to move into `self`. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @available(*, deprecated, renamed: "replace(removing:moving:)") + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + moving newElements: inout RigidArray, + ) { + self.replace(removing: subrange, moving: &newElements) + } + + + /// Perform a range replacement up to populating the newly opened gap. This + /// deinitializes existing elements in the specified subrange, rearranges + /// following elements to be at their final location, and sets the container's + /// new count. + /// + /// - Returns: A buffer pointer addressing the newly opened gap, to be + /// initialized by the caller. + @available(*, deprecated) // FIXME: Obsolete, remove this + @usableFromInline + @unsafe + internal mutating func _gapForReplacement( + of subrange: Range, newItemCount: Int + ) -> UnsafeMutableBufferPointer { + precondition( + subrange.lowerBound >= 0 && subrange.upperBound <= _count, + "Index range out of bounds") + precondition(newItemCount >= 0, "Cannot add a negative number of items") + precondition( + newItemCount - subrange.count <= freeCapacity, + "RigidArray capacity overflow") + unsafe _items.extracting(subrange).deinitialize() + return _resizeGap(in: subrange, to: newItemCount) + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidArray { + /// Copy the contents of this array into a newly allocated rigid array + /// instance with just enough capacity to hold all its elements. + /// + /// - Complexity: O(`count`) + @available(*, deprecated, renamed: "clone()") + @inlinable + public func copy() -> Self { + clone() + } + + + /// Copy the contents of this array into a newly allocated rigid array + /// instance with the specified capacity. + /// + /// - Parameter capacity: The desired capacity of the resulting rigid array. + /// `capacity` must be greater than or equal to `count`. + /// + /// - Complexity: O(`count`) + @available(*, deprecated, renamed: "clone(capacity:)") + @inlinable + public func copy(capacity: Int) -> Self { + clone(capacity: capacity) + } + + /// Replaces the specified subrange of elements by copying the elements of + /// the given buffer pointer, which must be fully initialized. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @available(*, deprecated, renamed: "replace(removing:copying:)") + @inlinable + public mutating func replaceSubrange( + _ subrange: Range, + copying newElements: UnsafeBufferPointer + ) { + self.replace(removing: subrange, copying: newElements) + } + + /// Replaces the specified subrange of elements by copying the elements of + /// the given buffer pointer, which must be fully initialized. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @available(*, deprecated, renamed: "replace(removing:copying:)") + @inlinable + public mutating func replaceSubrange( + _ subrange: Range, + copying newElements: UnsafeMutableBufferPointer + ) { + self.replace(removing: subrange, copying: newElements) + } + + /// Replaces the specified subrange of elements by copying the elements of + /// the given span. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length span as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @available(*, deprecated, renamed: "replace(removing:copying:)") + @inlinable + public mutating func replaceSubrange( + _ subrange: Range, + copying newElements: Span + ) { + self.replace(removing: subrange, copying: newElements) + } + + @available(*, unavailable) + @usableFromInline + internal mutating func _replaceSubrange( + _ subrange: Range, + copyingCollection newElements: __owned some Collection, + newCount: Int + ) { + self._replace( + removing: subrange, + copyingCollection: newElements, + newCount: newCount) + } + + /// Replaces the specified subrange of elements by copying the elements of + /// the given collection. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length collection as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @available(*, deprecated, renamed: "replace(removing:copying:)") + @inlinable + @inline(__always) + public mutating func replaceSubrange( + _ subrange: Range, + copying newElements: __owned some Collection + ) { + self.replace(removing: subrange, copying: newElements) + } +} + +#endif diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Descriptions.swift b/Sources/BasicContainers/RigidArray/RigidArray+Descriptions.swift new file mode 100644 index 00000000..f237b812 --- /dev/null +++ b/Sources/BasicContainers/RigidArray/RigidArray+Descriptions.swift @@ -0,0 +1,30 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension RigidArray /*: CustomStringConvertible */ where Element: ~Copyable { + public var description: String { + /// FIXME: Print the item descriptions when available. + "<\(count) items>" + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidArray /*: CustomDebugStringConvertible */ where Element: ~Copyable { + public var debugDescription: String { + /// FIXME: Print the item descriptions when available. + "<\(count) items>" + } +} + +#endif diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Equatable.swift b/Sources/BasicContainers/RigidArray/RigidArray+Equatable.swift new file mode 100644 index 00000000..53d836aa --- /dev/null +++ b/Sources/BasicContainers/RigidArray/RigidArray+Equatable.swift @@ -0,0 +1,38 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.2) + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +#endif + +@available(SwiftStdlib 5.0, *) +extension RigidArray /*: Equatable */ where Element: Equatable /* & ~Copyable */ { + public func isTriviallyIdentical(to other: borrowing Self) -> Bool { + self._storage._isIdentical(to: other._storage) + && self._count == other._count + } +} + + +@available(SwiftStdlib 5.0, *) +extension RigidArray /*: Equatable */ where Element: Equatable /* & ~Copyable */ { + @inlinable + public static func ==( + left: borrowing Self, + right: borrowing Self + ) -> Bool { + left.span._elementsEqual(to: right.span) + } +} + +#endif diff --git a/Sources/BasicContainers/RigidArray+Experimental.swift b/Sources/BasicContainers/RigidArray/RigidArray+Experimental.swift similarity index 96% rename from Sources/BasicContainers/RigidArray+Experimental.swift rename to Sources/BasicContainers/RigidArray/RigidArray+Experimental.swift index 214e0b44..cdfcd455 100644 --- a/Sources/BasicContainers/RigidArray+Experimental.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Experimental.swift @@ -22,7 +22,7 @@ extension RigidArray where Element: ~Copyable { @inlinable @_lifetime(borrow self) public func borrowElement(at index: Int) -> Borrow { - precondition(index >= 0 && index < _count, "Index out of bounds") + _checkItemIndex(index) return unsafe Borrow( unsafeAddress: _storage.baseAddress.unsafelyUnwrapped.advanced(by: index), borrowing: self @@ -37,7 +37,7 @@ extension RigidArray where Element: ~Copyable { @inlinable @_lifetime(&self) public mutating func mutateElement(at index: Int) -> Mut { - precondition(index >= 0 && index < _count) + _checkItemIndex(index) return unsafe Mut( unsafeAddress: _storage.baseAddress.unsafelyUnwrapped.advanced(by: index), mutating: &self diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Hashable.swift b/Sources/BasicContainers/RigidArray/RigidArray+Hashable.swift new file mode 100644 index 00000000..fa7d4b5f --- /dev/null +++ b/Sources/BasicContainers/RigidArray/RigidArray+Hashable.swift @@ -0,0 +1,27 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.2) + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +#endif + +@available(SwiftStdlib 5.0, *) +extension RigidArray /*: Hashable */ where Element: Hashable /* & ~Copyable */ { + @inlinable + public func hash(into hasher: inout Hasher) { + hasher.combine(self.count) + self.span._hashContents(into: &hasher) + } +} + +#endif diff --git a/Sources/BasicContainers/RigidArray+Initializers.swift b/Sources/BasicContainers/RigidArray/RigidArray+Initializers.swift similarity index 72% rename from Sources/BasicContainers/RigidArray+Initializers.swift rename to Sources/BasicContainers/RigidArray/RigidArray+Initializers.swift index d9d8fc72..c850ba47 100644 --- a/Sources/BasicContainers/RigidArray+Initializers.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Initializers.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors +// Copyright (c) 2024 - 2026 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information @@ -16,6 +16,30 @@ import ContainersPreview #if compiler(>=6.2) +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + /// Initializes a new rigid array with zero capacity and no elements. + /// + /// - Complexity: O(1) + @inlinable + public init() { + unsafe _storage = .init(start: nil, count: 0) + _count = 0 + } + + /// Initializes a new rigid array with the specified capacity and no elements. + @inlinable + public init(capacity: Int) { + precondition(capacity >= 0, "Array capacity must be nonnegative") + if capacity > 0 { + unsafe _storage = .allocate(capacity: capacity) + } else { + unsafe _storage = .init(start: nil, count: 0) + } + _count = 0 + } +} + @available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { /// Creates a new array with the specified capacity, directly initializing @@ -23,7 +47,7 @@ extension RigidArray where Element: ~Copyable { /// /// - Parameters: /// - capacity: The storage capacity of the new array. - /// - body: A callback that gets called precisely once to directly + /// - body: A callback that gets called at most once to directly /// populate newly reserved storage within the array. The function /// is allowed to add fewer than `capacity` items. The array is /// initialized with however many items the callback adds to the @@ -31,10 +55,10 @@ extension RigidArray where Element: ~Copyable { @inlinable public init( capacity: Int, - initializingWith body: (inout OutputSpan) throws(E) -> Void + initializingWith initializer: (inout OutputSpan) throws(E) -> Void ) throws(E) { self.init(capacity: capacity) - try edit(body) + try edit(initializer) } } @@ -98,15 +122,38 @@ extension RigidArray /*where Element: Copyable*/ { /// The container must not contain more than `capacity` elements. @_alwaysEmitIntoClient @inline(__always) - public init & ~Copyable & ~Escapable>( - capacity: Int? = nil, + public init & ~Copyable & ~Escapable>( + capacity: Int, copying contents: borrowing Source ) { - self.init(capacity: capacity ?? contents.count) + self.init(capacity: capacity) + self.append(copying: contents) + } + +#endif + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Creates a new array with the specified capacity, holding a copy + /// of the contents of a given container. + /// + /// - Parameters: + /// - capacity: The storage capacity of the new array, or nil to allocate + /// just enough capacity to store the contents. + /// - contents: The container whose contents to copy into the new array. + /// The container must not contain more than `capacity` elements. + @_alwaysEmitIntoClient + @inline(__always) + public init & Sequence>( + capacity: Int, + copying contents: Source + ) { + self.init(capacity: capacity) self.append(copying: contents) } #endif - + + // FIXME: Add a version that's generic over `Container`, with an optional capacity + /// Creates a new array with the specified capacity, holding a copy /// of the contents of a given collection. /// @@ -124,26 +171,24 @@ extension RigidArray /*where Element: Copyable*/ { self.init(capacity: capacity ?? contents.count) self.append(copying: contents) } - -#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Creates a new array with the specified capacity, holding a copy - /// of the contents of a given container. + /// of the contents of the given span. /// /// - Parameters: /// - capacity: The storage capacity of the new array, or nil to allocate - /// just enough capacity to store the contents. - /// - contents: The container whose contents to copy into the new array. - /// The container must not contain more than `capacity` elements. + /// just enough capacity to store the contents of the span. + /// - span: The span whose contents to copy into the new array. + /// The span must not contain more than `capacity` elements. @_alwaysEmitIntoClient @inline(__always) - public init & Sequence>( + public init( capacity: Int? = nil, - copying contents: Source + copying span: Span ) { - self.init(capacity: capacity ?? contents.count) - self.append(copying: contents) + self.init(capacity: capacity ?? span.count) + self.append(copying: span) } -#endif } // FIXME: Add init(moving:), init(consuming:) diff --git a/Sources/BasicContainers/RigidArray+Insertions.swift b/Sources/BasicContainers/RigidArray/RigidArray+Insertions.swift similarity index 81% rename from Sources/BasicContainers/RigidArray+Insertions.swift rename to Sources/BasicContainers/RigidArray/RigidArray+Insertions.swift index 669a4fc1..f3336d3a 100644 --- a/Sources/BasicContainers/RigidArray+Insertions.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Insertions.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors +// Copyright (c) 2024 - 2026 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information @@ -37,7 +37,7 @@ extension RigidArray where Element: ~Copyable { /// - Complexity: O(`self.count`) @inlinable public mutating func insert(_ item: consuming Element, at index: Int) { - precondition(index >= 0 && index <= count, "Index out of bounds") + _checkValidIndex(index) precondition(!isFull, "RigidArray capacity overflow") if index < count { let source = unsafe _storage.extracting(index ..< count) @@ -56,40 +56,64 @@ extension RigidArray where Element: ~Copyable { /// position, using a callback to directly initialize array storage by /// populating an output span. /// - /// All existing elements at or following the specified position are moved to - /// make room for the new items. + /// Existing elements in the array's storage are moved towards the back as + /// needed to make room for the new items. /// - /// If the capacity of the array isn't sufficient to accommodate the new - /// elements, then this method triggers a runtime error. + /// If the capacity of the array isn't sufficient to accommodate the specified + /// number of new elements, then this method triggers a runtime error. + /// + /// var buffer = RigidArray(capacity: 20) + /// buffer.append([-999, 999]) + /// var i = 0 + /// buffer.insert(capacity: 3, at: 1) { target in + /// while !target.isFull { + /// target.append(i) + /// i += 1 + /// } + /// } + /// // `buffer` now contains [-999, 0, 1, 2, 999] + /// + /// If the callback fails to fully populate its output span or if + /// it throws an error, then the array keeps all items that were + /// successfully initialized before the callback terminated the insertion. + /// + /// Partial insertions create a gap in array storage that needs to be + /// closed by moving already inserted items to their correct positions given + /// the adjusted count. This adds some overhead compared to adding exactly as + /// many items as promised. /// /// - Parameters: - /// - count: The number of items to insert into the array. + /// - newItemCount: The maximum number of items to insert into the array. /// - index: The position at which to insert the new items. /// `index` must be a valid index in the array. - /// - body: A callback that gets called precisely once to directly + /// - initializer: A callback that gets called at most once to directly /// populate newly reserved storage within the array. The function - /// is called with an empty output span of capacity matching the - /// supplied count, and it must fully populate it before returning. + /// is always called with an empty output span. /// - /// - Complexity: O(`self.count` + `count`) - @inlinable - public mutating func insert( - count: Int, + /// - Complexity: O(`self.count` + `newItemCount`) in addition to the complexity + /// of the callback invocations. + @_alwaysEmitIntoClient + @inline(__always) + public mutating func insert( + addingCount newItemCount: Int, at index: Int, - initializingWith body: (inout OutputSpan) -> Result - ) -> Result { - // FIXME: This does not allow `body` to throw, to prevent having to move the tail twice. Is that okay? - precondition(index >= 0 && index <= self.count, "Index out of bounds") - precondition(count <= freeCapacity, "RigidArray capacity overflow") - let target = unsafe _openGap(at: index, count: count) + initializingWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) { + _checkValidIndex(index) + precondition(newItemCount >= 0, "Cannot add a negative number of items") + precondition(newItemCount <= freeCapacity, "RigidArray capacity overflow") + let target = unsafe _openGap(at: index, count: newItemCount) + _count &+= newItemCount var span = OutputSpan(buffer: target, initializedCount: 0) defer { let c = span.finalize(for: target) - precondition(c == count, "Inserted fewer items than promised") - _count &+= c + if c < newItemCount { + _closeGap(at: index &+ c, count: newItemCount &- c) + _count &-= newItemCount &- c + } span = OutputSpan() } - return body(&span) + try initializer(&span) } } @@ -105,7 +129,7 @@ extension RigidArray where Element: ~Copyable { /// If the capacity of the array isn't sufficient to accommodate the new /// elements, then this method triggers a runtime error. /// - /// - Parameters + /// - Parameters: /// - items: A fully initialized buffer whose contents to move into /// the array. /// - index: The position at which to insert the new items. @@ -117,14 +141,11 @@ extension RigidArray where Element: ~Copyable { moving items: UnsafeMutableBufferPointer, at index: Int ) { - insert(count: items.count, at: index) { target in - target.withUnsafeMutableBufferPointer { buffer, count in - buffer.moveInitializeAll(fromContentsOf: items) - count = items.count - } + insert(addingCount: items.count, at: index) { target in + target._append(moving: items) } } - + #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW /// Moves the elements of an input span into this array, /// starting at the specified position, and leaving the span empty. @@ -135,7 +156,7 @@ extension RigidArray where Element: ~Copyable { /// If the capacity of the array isn't sufficient to accommodate the new /// elements, then this method triggers a runtime error. /// - /// - Parameters + /// - Parameters: /// - items: An input span whose contents to move into /// the array. /// - index: The position at which to insert the new items. @@ -164,7 +185,7 @@ extension RigidArray where Element: ~Copyable { /// If the capacity of the array isn't sufficient to accommodate the new /// elements, then this method triggers a runtime error. /// - /// - Parameters + /// - Parameters: /// - items: An output span whose contents to move into /// the array. /// - index: The position at which to insert the new items. @@ -194,7 +215,7 @@ extension RigidArray where Element: ~Copyable { /// If the capacity of the array isn't sufficient to accommodate the new /// elements, then this method triggers a runtime error. /// - /// - Parameters + /// - Parameters: /// - items: An array whose contents to move into `self`. /// - index: The position at which to insert the new items. /// `index` must be a valid index in the array. @@ -205,16 +226,10 @@ extension RigidArray where Element: ~Copyable { moving items: inout RigidArray, at index: Int ) { - insert(count: items.count, at: index) { target in - target.withUnsafeMutableBufferPointer { dst, dstCount in - items.edit { source in - source.withUnsafeMutableBufferPointer { src, srcCount in - dst.moveInitializeAll(fromContentsOf: src) - dstCount = src.count - srcCount = 0 - } - } - } + // FIXME: Remove this in favor of a generic algorithm over consumable containers + guard !items.isEmpty else { return } + items.edit { source in + self.insert(moving: &source, at: index) } } } @@ -231,9 +246,8 @@ extension RigidArray where Element: ~Copyable { /// If the capacity of the array isn't sufficient to accommodate the new /// elements, then this method triggers a runtime error. /// - /// - Parameters - /// - items: A fully initialized buffer whose contents to move into - /// the array. + /// - Parameters: + /// - items: The array whose contents to move into `self`. /// - index: The position at which to insert the new items. /// `index` must be a valid index in the array. /// @@ -265,7 +279,7 @@ extension RigidArray { /// If the capacity of the array isn't sufficient to accommodate the new /// elements, then this method triggers a runtime error. /// - /// - Parameters + /// - Parameters: /// - newElements: The new elements to insert into the array. The buffer /// must be fully initialized. /// - index: The position at which to insert the new elements. It must be @@ -277,11 +291,8 @@ extension RigidArray { copying newElements: UnsafeBufferPointer, at index: Int ) { guard newElements.count > 0 else { return } - self.insert(count: newElements.count, at: index) { target in - target.withUnsafeMutableBufferPointer { buffer, count in - buffer.initializeAll(fromContentsOf: newElements) - count = newElements.count - } + self.insert(addingCount: newElements.count, at: index) { target in + target._append(copying: newElements) } } @@ -298,7 +309,7 @@ extension RigidArray { /// If the capacity of the array isn't sufficient to accommodate the new /// elements, then this method triggers a runtime error. /// - /// - Parameters + /// - Parameters: /// - newElements: The new elements to insert into the array. The buffer /// must be fully initialized. /// - index: The position at which to insert the new elements. It must be @@ -306,6 +317,7 @@ extension RigidArray { /// /// - Complexity: O(`count` + `newElements.count`) @inlinable + @inline(__always) public mutating func insert( copying newElements: UnsafeMutableBufferPointer, at index: Int @@ -325,23 +337,25 @@ extension RigidArray { /// If the capacity of the array isn't sufficient to accommodate the new /// elements, then this method triggers a runtime error. /// - /// - Parameters + /// - Parameters: /// - newElements: The new elements to insert into the array. /// - index: The position at which to insert the new elements. It must be /// a valid index of the array. /// /// - Complexity: O(`count` + `newElements.count`) @inlinable + @inline(__always) public mutating func insert( copying newElements: Span, at index: Int ) { - unsafe newElements.withUnsafeBufferPointer { - unsafe self.insert(copying: $0, at: index) + guard newElements.count > 0 else { return } + self.insert(addingCount: newElements.count, at: index) { target in + target._append(copying: newElements) } } #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW - @inlinable + @_alwaysEmitIntoClient internal mutating func _insertContainer< C: Container & ~Copyable & ~Escapable >( @@ -349,15 +363,15 @@ extension RigidArray { copying items: borrowing C, newCount: Int ) { - insert(count: newCount, at: index) { target in - target.withUnsafeMutableBufferPointer { buffer, count in - let copied = items._copyContents(intoPrefixOf: buffer) - precondition( - copied == newCount, - "Broken Container: count doesn't match contents") - count = newCount + var it = items.makeBorrowingIterator() + insert(addingCount: newCount, at: index) { target in + while !target.isFull { + let source = it.nextSpan(maximumCount: target.freeCapacity) + precondition(!source.isEmpty, "Broken container: mismatching count") + target._append(copying: source) } } + precondition(it.nextSpan().isEmpty, "Broken container: mismatching count") } #endif @@ -367,7 +381,7 @@ extension RigidArray { copying items: some Collection, newCount: Int ) { - precondition(index >= 0 && index <= _count, "Index out of bounds") + _checkValidIndex(index) precondition(newCount <= freeCapacity, "RigidArray capacity overflow") let gap = unsafe _openGap(at: index, count: newCount) @@ -386,7 +400,7 @@ extension RigidArray { "Broken Collection: count doesn't match contents") _count += newCount } - + #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW /// Copies the elements of a container into this array at the specified /// position. @@ -401,7 +415,7 @@ extension RigidArray { /// If the capacity of the array isn't sufficient to accommodate the new /// elements, then this method triggers a runtime error. /// - /// - Parameters + /// - Parameters: /// - newElements: The new elements to insert into the array. /// - index: The position at which to insert the new elements. It must be /// a valid index of the array. @@ -432,7 +446,7 @@ extension RigidArray { /// If the capacity of the array isn't sufficient to accommodate the new /// elements, then this method triggers a runtime error. /// - /// - Parameters + /// - Parameters: /// - newElements: The new elements to insert into the array. /// - index: The position at which to insert the new elements. It must be /// a valid index of the array. @@ -446,7 +460,7 @@ extension RigidArray { _insertCollection( at: index, copying: newElements, newCount: newElements.count) } - + #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW /// Copies the elements of a container into this array at the specified /// position. @@ -461,7 +475,7 @@ extension RigidArray { /// If the capacity of the array isn't sufficient to accommodate the new /// elements, then this method triggers a runtime error. /// - /// - Parameters + /// - Parameters: /// - newElements: The new elements to insert into the array. /// - index: The position at which to insert the new elements. It must be /// a valid index of the array. diff --git a/Sources/BasicContainers/RigidArray+Removals.swift b/Sources/BasicContainers/RigidArray/RigidArray+Removals.swift similarity index 56% rename from Sources/BasicContainers/RigidArray+Removals.swift rename to Sources/BasicContainers/RigidArray/RigidArray+Removals.swift index a1149b90..4ee28a3f 100644 --- a/Sources/BasicContainers/RigidArray+Removals.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Removals.swift @@ -18,6 +18,26 @@ import ContainersPreview @available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { + /// Removes and returns the element at the specified position. + /// + /// All the elements following the specified position are moved to close the + /// gap. + /// + /// - Parameter i: The position of the element to remove. `index` must be + /// a valid index of the array that is not equal to the end index. + /// - Returns: The removed element. + /// + /// - Complexity: O(`count`) + @inlinable + @discardableResult + public mutating func remove(at index: Int) -> Element { + _checkItemIndex(index) + let old = unsafe _storage.moveElement(from: index) + _closeGap(at: index, count: 1) + _count -= 1 + return old + } + /// Removes all elements from the array, preserving its allocated capacity. /// /// - Complexity: O(*n*), where *n* is the original count of the array. @@ -66,26 +86,6 @@ extension RigidArray where Element: ~Copyable { _count &-= k } - /// Removes and returns the element at the specified position. - /// - /// All the elements following the specified position are moved to close the - /// gap. - /// - /// - Parameter i: The position of the element to remove. `index` must be - /// a valid index of the array that is not equal to the end index. - /// - Returns: The removed element. - /// - /// - Complexity: O(`count`) - @inlinable - @discardableResult - public mutating func remove(at index: Int) -> Element { - precondition(index >= 0 && index < _count, "Index out of bounds") - let old = unsafe _storage.moveElement(from: index) - _closeGap(at: index, count: 1) - _count -= 1 - return old - } - /// Removes the specified subrange of elements from the array. /// /// All the elements following the specified subrange are moved to close the @@ -97,9 +97,7 @@ extension RigidArray where Element: ~Copyable { /// - Complexity: O(`count`) @inlinable public mutating func removeSubrange(_ bounds: Range) { - precondition( - bounds.lowerBound >= 0 && bounds.upperBound <= _count, - "Subrange out of bounds") + _checkValidBounds(bounds) guard !bounds.isEmpty else { return } unsafe _storage.extracting(bounds).deinitialize() _closeGap(at: bounds.lowerBound, count: bounds.count) @@ -135,82 +133,4 @@ extension RigidArray where Element: ~Copyable { } } -#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW -@available(SwiftStdlib 5.0, *) -extension RigidArray where Element: ~Copyable { - /// Remove all items currently in this array, returning an input span to - /// allow them to be consumed in place. - /// The input span extends the exclusive mutating access initiated by this - /// operation to cover the span's lifetime. Once the span is destroyed, - /// the array becomes empty, but it preserves its original storage capacity. - /// - /// - Complexity: O(*n*), where *n* is the original count of the array. - @_lifetime(&self) - @_alwaysEmitIntoClient - public mutating func consumeAll() -> InputSpan { - let span = InputSpan(buffer: _items, initializedCount: self.count) - self._count = 0 - return _overrideLifetime(span, mutating: &self) - } - - /// Remove the specified number of items from the end of this array, - /// returning an input span to allow them to be consumed in place. - /// The input span extends the exclusive mutating access initiated by this - /// operation to cover the span's lifetime. - /// - /// - Parameter n: The number of items to consume from the end of the array. - /// `n` must be greater than or equal to zero and must not exceed - /// the count of the array. - /// - /// - Complexity: O(`n`) - @_lifetime(&self) - @_alwaysEmitIntoClient - public mutating func consumeLast(_ n: Int) -> InputSpan { - precondition( - n >= 0 && n <= _count, - "Count of elements to consume is out of bounds") - self._count &-= n - let span = InputSpan( - buffer: self._storage._extracting(first: n), - initializedCount: n) - return _overrideLifetime(span, mutating: &self) - } - - /// Remove the specified subrange of items from this array, - /// passing an input span to the given function to consume them in place. - /// - /// - Parameter bounds: The subrange of items to consume from this array. - /// - Parameter body: A function taking an input span of the removed items, - /// allowing them to be consumed straight out of the array's storage. - /// The function is not required to consume all items in the span; - /// however, the span's remaining items will still be removed from - /// the array. - /// - /// - Complexity: O(`self.count`) - @_alwaysEmitIntoClient - public mutating func consumeSubrange( - _ bounds: Range, - consumingWith body: (inout InputSpan) throws(E) -> Result - ) throws(E) -> Result { - precondition( - bounds.lowerBound >= 0 && bounds.upperBound <= _count, - "Subrange out of bounds") - guard !bounds.isEmpty else { - var span = InputSpan() - return try body(&span) - } - let buffer = unsafe _storage.extracting(bounds) - var span = InputSpan(buffer: buffer, initializedCount: buffer.count) - defer { - let remainder = span.finalize(for: buffer) - buffer._extracting(last: remainder).deinitialize() - _closeGap(at: bounds.lowerBound, count: bounds.count) - _count -= bounds.count - span = InputSpan() - } - return try body(&span) - } -} -#endif - #endif diff --git a/Sources/BasicContainers/RigidArray+Replacements.swift b/Sources/BasicContainers/RigidArray/RigidArray+Replacements.swift similarity index 60% rename from Sources/BasicContainers/RigidArray+Replacements.swift rename to Sources/BasicContainers/RigidArray/RigidArray+Replacements.swift index 654cca7d..2c9d0b2c 100644 --- a/Sources/BasicContainers/RigidArray+Replacements.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Replacements.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors +// Copyright (c) 2024 - 2026 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information @@ -22,52 +22,186 @@ extension RigidArray where Element: ~Copyable { /// using a callback to directly initialize array storage by populating /// an output span. /// - /// This method has the effect of removing the specified range of elements - /// from the array and inserting room for the new elements starting at the - /// same location. The number of new elements need not match the number - /// of elements being removed. + /// The number of new items need not match the number of elements being + /// removed. /// - /// If the capacity of the array isn't sufficient to accommodate the new + /// This method has the same overall effect as calling + /// + /// try array.removeSubrange(subrange) + /// try array.insert( + /// addingCount: newItemCount, + /// at: subrange.lowerBound, + /// initializingWith: initializer) + /// + /// Except it performs faster (by a constant factor), by avoiding moving + /// some items in the array twice. + /// + /// If the array does not have sufficient capacity to accommodate the new /// elements, then this method triggers a runtime error. /// - /// If you pass a zero-length range as the `subrange` parameter, then - /// this method is equivalent to calling - /// `insert(count: newCount, initializingWith: body)`. + /// If the callback fails to fully populate its output span or if + /// it throws an error, then the array keeps all items that were + /// successfully initialized before the callback terminated the prepend. /// - /// Likewise, if you pass a zero for `newCount`, then this method - /// removes the elements in the given subrange without any replacement. - /// Calling `removeSubrange(subrange)` is preferred in this case. + /// Partial insertions create a gap in array storage that needs to be + /// closed by moving newly inserted items to their correct positions given + /// the adjusted count. This adds some overhead compared to adding exactly as + /// many items as promised. /// - /// - Parameters + /// - Parameters: /// - subrange: The subrange of the array to replace. The bounds of /// the range must be valid indices in the array. - /// - newCount: the number of items to replace the old subrange. - /// - body: A callback that gets called precisely once to directly + /// - newItemCount: the maximum number of items to replace the old subrange. + /// - initializer: A callback that gets called at most once to directly /// populate newly reserved storage within the array. The function - /// is called with an empty output span of capacity `newCount`, - /// and it must fully populate it before returning. + /// is always called with an empty output span. /// - /// - Complexity: O(`self.count` + `newCount`) + /// - Complexity: O(`self.count` + `newItemCount`) in addition to the complexity + /// of the callback invocations. @inlinable - public mutating func replaceSubrange( - _ subrange: Range, - newCount: Int, - initializingWith body: (inout OutputSpan) -> Result - ) -> Result { - // FIXME: Should we allow throwing (and a partially filled output span)? - // FIXME: Should we have a version of this with two closures, to allow custom-consuming the old items? - // replaceSubrange(5..<10, newCount: 3, consumingWith: {...}, initializingWith: {...}) - let target = _gapForReplacement(of: subrange, withNewCount: newCount) + public mutating func replace( + removing subrange: Range, + addingCount newItemCount: Int, + initializingWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) -> Void { + _checkValidBounds(subrange) + precondition(newItemCount >= 0, "Cannot add a negative number of items") + precondition( + newItemCount - subrange.count <= freeCapacity, + "RigidArray capacity overflow") + try _uncheckedReplace( + removing: subrange, + addingCount: newItemCount, + initializingWith: initializer) + } + + @_alwaysEmitIntoClient + internal mutating func _uncheckedReplace( + removing subrange: Range, + addingCount newItemCount: Int, + initializingWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) -> Void { + // Destroy removed items + unsafe _items.extracting(subrange).deinitialize() + let target = _resizeGap(in: subrange, to: newItemCount) var span = OutputSpan(buffer: target, initializedCount: 0) defer { let c = span.finalize(for: target) - precondition(c == newCount, "Inserted fewer items than promised") + if c < newItemCount { + self._closeGap( + at: subrange.lowerBound &+ c, + count: newItemCount &- c) + _count &-= newItemCount &- c + } span = OutputSpan() } - return body(&span) + try initializer(&span) } } +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Replaces the specified range of elements by a given count of new items, + /// using callbacks to consume old items, and to then insert new ones. + /// + /// The number of new items need not match the number of elements being + /// removed. + /// + /// This method has the same overall effect as calling + /// + /// try array.consume(subrange, consumingWith: consumer) + /// try array.insert( + /// addingCount: newItemCount, + /// at: subrange.lowerBound, + /// initializingWith: initializer) + /// + /// Except it performs faster (by a constant factor), by avoiding moving + /// some items in the deque twice. + /// + /// If the capacity of the array isn't sufficient to accommodate the specified + /// number of new elements, then this method triggers a runtime error. + /// + /// The `consumer` callback is not required to fully depopulate its input + /// span. Any items the callback leaves in the span still get removed and + /// discarded from the array before insertions begin. + /// + /// The `initializer` callback is not required to fully populate its + /// output span, and it is allowed to throw an error. In such cases, the + /// deque keeps all items that were successfully initialized before the + /// callback terminated. + /// + /// Partial insertions create a gap in array storage that needs to be + /// closed by moving newly inserted items to their correct positions given + /// the adjusted count. This adds some overhead compared to adding exactly as + /// many items as promised. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - newItemCount: the maximum number of items to replace the old subrange. + /// - consumer: A callback that gets called at most once to consume + /// the elements to be removed directly from the deque's storage. The + /// function is always called with a non-empty input span. + /// - initializer: A callback that gets called at most once to directly + /// populate newly reserved storage within the deque. The function + /// is always called with an empty output span. + /// + /// - Complexity: O(`self.count` + `newItemCount`) in addition to the + /// complexity of the callback invocations. + @inlinable + public mutating func replace( + removing subrange: Range, + consumingWith consumer: (inout InputSpan) -> Void, + addingCount newItemCount: Int, + initializingWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) -> Void { + _checkValidBounds(subrange) + precondition(newItemCount >= 0, "Cannot add a negative number of items") + precondition( + newItemCount - subrange.count <= freeCapacity, + "RigidArray capacity overflow") + try _uncheckedReplace( + removing: subrange, + consumingWith: consumer, + addingCount: newItemCount, + initializingWith: initializer) + } + + @_alwaysEmitIntoClient + internal mutating func _uncheckedReplace( + removing subrange: Range, + consumingWith consumer: (inout InputSpan) -> Void, + addingCount newItemCount: Int, + initializingWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) -> Void { + do { + // Consume items to be removed + let buffer = unsafe _storage.extracting(subrange) + var span = InputSpan(buffer: buffer, initializedCount: buffer.count) + consumer(&span) + _ = consume span + } + do { + // Insert new items + let target = _resizeGap(in: subrange, to: newItemCount) + var span = OutputSpan(buffer: target, initializedCount: 0) + defer { + let c = span.finalize(for: target) + if c < newItemCount { + self._closeGap( + at: subrange.lowerBound &+ c, + count: capacity &- c) + } + span = OutputSpan() + } + try initializer(&span) + } + } +#endif +} + + @available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { /// Replaces the specified range of elements by moving the elements of a @@ -83,15 +217,15 @@ extension RigidArray where Element: ~Copyable { /// elements, then this method triggers a runtime error. /// /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(moving:at:)` method instead is preferred in this case. + /// inserts the elements of `newElements` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(moving:at:)`. /// /// Likewise, if you pass a zero-length buffer as the `newElements` /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. /// - /// - Parameters + /// - Parameters: /// - subrange: The subrange of the array to replace. The bounds of /// the range must be valid indices in the array. /// - newElements: A fully initialized buffer whose contents to move into @@ -99,11 +233,11 @@ extension RigidArray where Element: ~Copyable { /// /// - Complexity: O(`self.count` + `newElements.count`) @_alwaysEmitIntoClient - public mutating func replaceSubrange( - _ subrange: Range, + public mutating func replace( + removing subrange: Range, moving newElements: UnsafeMutableBufferPointer, ) { - replaceSubrange(subrange, newCount: newElements.count) { target in + replace(removing: subrange, addingCount: newElements.count) { target in target.withUnsafeMutableBufferPointer { buffer, count in count = unsafe buffer._moveInitializePrefix(from: newElements) } @@ -123,28 +257,28 @@ extension RigidArray where Element: ~Copyable { /// elements, then this method triggers a runtime error. /// /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(moving:at:)` method instead is preferred in this case. + /// inserts the elements of `newElements` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(moving:at:)`. /// /// Likewise, if you pass a zero-length buffer as the `newElements` /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. /// - /// - Parameters + /// - Parameters: /// - subrange: The subrange of the array to replace. The bounds of /// the range must be valid indices in the array. /// - items: An input span whose contents are to be moved into the array. /// /// - Complexity: O(`self.count` + `items.count`) @_alwaysEmitIntoClient - public mutating func replaceSubrange( - _ subrange: Range, + public mutating func replace( + removing subrange: Range, moving items: inout InputSpan ) { items.withUnsafeMutableBufferPointer { buffer, count in let source = buffer._extracting(last: count) - unsafe self.replaceSubrange(subrange, moving: source) + unsafe self.replace(removing: subrange, moving: source) count = 0 } } @@ -162,28 +296,28 @@ extension RigidArray where Element: ~Copyable { /// elements, then this method triggers a runtime error. /// /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(moving:at:)` method instead is preferred in this case. + /// inserts the elements of `newElements` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(moving:at:)`. /// /// Likewise, if you pass a zero-length buffer as the `newElements` /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. /// - /// - Parameters + /// - Parameters: /// - subrange: The subrange of the array to replace. The bounds of /// the range must be valid indices in the array. /// - items: An output span whose contents are to be moved into the array. /// /// - Complexity: O(`self.count` + `items.count`) @_alwaysEmitIntoClient - public mutating func replaceSubrange( - _ subrange: Range, + public mutating func replace( + removing subrange: Range, moving items: inout OutputSpan ) { items.withUnsafeMutableBufferPointer { buffer, count in let source = buffer._extracting(first: count) - unsafe self.replaceSubrange(subrange, moving: source) + unsafe self.replace(removing: subrange, moving: source) count = 0 } } @@ -202,28 +336,29 @@ extension RigidArray where Element: ~Copyable { /// elements, then this method triggers a runtime error. /// /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. + /// inserts the elements of `newElements` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(moving:at:)`. /// /// Likewise, if you pass a zero-length buffer as the `newElements` /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. /// - /// - Parameters + /// - Parameters: /// - subrange: The subrange of the array to replace. The bounds of /// the range must be valid indices in the array. /// - newElements: An array whose contents to move into `self`. /// /// - Complexity: O(`self.count` + `newElements.count`) @_alwaysEmitIntoClient - public mutating func replaceSubrange( - _ subrange: Range, + public mutating func replace( + removing subrange: Range, moving newElements: inout RigidArray, ) { + // FIXME: Remove this in favor of a generic algorithm over consumable containers unsafe newElements._unsafeEdit { buffer, count in let source = buffer._extracting(first: count) - unsafe self.replaceSubrange(subrange, moving: source) + unsafe self.replace(removing: subrange, moving: source) count = 0 } } @@ -244,27 +379,27 @@ extension RigidArray where Element: ~Copyable { /// elements, then this method triggers a runtime error. /// /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. + /// inserts the elements of `newElements` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(consuming:at:)`. /// /// Likewise, if you pass a zero-length buffer as the `newElements` /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. /// - /// - Parameters + /// - Parameters: /// - subrange: The subrange of the array to replace. The bounds of /// the range must be valid indices in the array. /// - newElements: An array whose contents to move into `self`. /// /// - Complexity: O(`self.count` + `newElements.count`) @_alwaysEmitIntoClient - public mutating func replaceSubrange( - _ subrange: Range, + public mutating func replace( + removing subrange: Range, consuming newElements: consuming RigidArray, ) { // FIXME: Remove this in favor of a generic algorithm over consumable containers - replaceSubrange(subrange, moving: &newElements) + replace(removing: subrange, moving: &newElements) } #endif } @@ -283,13 +418,13 @@ extension RigidArray { /// elements, then this method triggers a runtime error. /// /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. + /// inserts the elements of `newElements` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(copying:at:)`. /// /// Likewise, if you pass a zero-length buffer as the `newElements` /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. /// /// - Parameters: /// - subrange: The subrange of the array to replace. The bounds of @@ -298,11 +433,11 @@ extension RigidArray { /// /// - Complexity: O(`self.count` + `newElements.count`) @inlinable - public mutating func replaceSubrange( - _ subrange: Range, + public mutating func replace( + removing subrange: Range, copying newElements: UnsafeBufferPointer ) { - replaceSubrange(subrange, newCount: newElements.count) { target in + replace(removing: subrange, addingCount: newElements.count) { target in target.withUnsafeMutableBufferPointer { buffer, count in count = unsafe buffer._initializePrefix(copying: newElements) } @@ -321,13 +456,13 @@ extension RigidArray { /// elements, then this method triggers a runtime error. /// /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. + /// inserts the elements of `newElements` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(copying:at:)`. /// /// Likewise, if you pass a zero-length buffer as the `newElements` /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. /// /// - Parameters: /// - subrange: The subrange of the array to replace. The bounds of @@ -336,12 +471,12 @@ extension RigidArray { /// /// - Complexity: O(`self.count` + `newElements.count`) @inlinable - public mutating func replaceSubrange( - _ subrange: Range, + public mutating func replace( + removing subrange: Range, copying newElements: UnsafeMutableBufferPointer ) { - unsafe self.replaceSubrange( - subrange, + unsafe self.replace( + removing: subrange, copying: UnsafeBufferPointer(newElements)) } @@ -357,13 +492,13 @@ extension RigidArray { /// elements, then this method triggers a runtime error. /// /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. + /// inserts the elements of `newElements` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(copying:at:)`. /// /// Likewise, if you pass a zero-length span as the `newElements` /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. /// /// - Parameters: /// - subrange: The subrange of the array to replace. The bounds of @@ -372,42 +507,47 @@ extension RigidArray { /// /// - Complexity: O(`self.count` + `newElements.count`) @inlinable - public mutating func replaceSubrange( - _ subrange: Range, + public mutating func replace( + removing subrange: Range, copying newElements: Span ) { unsafe newElements.withUnsafeBufferPointer { buffer in - unsafe self.replaceSubrange(subrange, copying: buffer) + unsafe self.replace(removing: subrange, copying: buffer) } } #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW @inlinable - internal mutating func _replaceSubrange< + internal mutating func _replace< C: Container & ~Copyable & ~Escapable >( - _ subrange: Range, - copyingContainer newElements: borrowing C, + removing subrange: Range, + copyingContainer items: borrowing C, newCount: Int ) { - self.replaceSubrange(subrange, newCount: newCount) { target in - target.withUnsafeMutableBufferPointer { buffer, count in - count = newElements._copyContents(intoPrefixOf: buffer) + var it = items.makeBorrowingIterator() + self.replace(removing: subrange, addingCount: newCount) { target in + while !target.isFull { + let source = it.nextSpan(maximumCount: target.freeCapacity) precondition( - count == newCount, + !source.isEmpty, "Broken Container: count doesn't match contents") + target._append(copying: source) } + precondition( + it.nextSpan().isEmpty, + "Broken Container: count doesn't match contents") } } #endif @inlinable - internal mutating func _replaceSubrange( - _ subrange: Range, + internal mutating func _replace( + removing subrange: Range, copyingCollection newElements: __owned some Collection, newCount: Int ) { - self.replaceSubrange(subrange, newCount: newCount) { target in + self.replace(removing: subrange, addingCount: newCount) { target in target.withUnsafeMutableBufferPointer { dst, dstCount in let done: Void? = newElements.withContiguousStorageIfAvailable { src in let i = unsafe dst._initializePrefix(copying: src) @@ -441,13 +581,13 @@ extension RigidArray { /// elements, then this method triggers a runtime error. /// /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. + /// inserts the elements of `newElements` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(copying:at:)`. /// /// Likewise, if you pass a zero-length container as the `newElements` /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. /// /// - Parameters: /// - subrange: The subrange of the array to replace. The bounds of @@ -457,14 +597,16 @@ extension RigidArray { /// - Complexity: O(`self.count` + `newElements.count`) @inlinable @inline(__always) - public mutating func replaceSubrange< + public mutating func replace< C: Container & ~Copyable & ~Escapable >( - _ subrange: Range, + removing subrange: Range, copying newElements: borrowing C ) { - _replaceSubrange( - subrange, copyingContainer: newElements, newCount: newElements.count) + _replace( + removing: subrange, + copyingContainer: newElements, + newCount: newElements.count) } #endif @@ -480,13 +622,13 @@ extension RigidArray { /// elements, then this method triggers a runtime error. /// /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. + /// inserts the elements of `newElements` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(copying:at:)`. /// /// Likewise, if you pass a zero-length collection as the `newElements` /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. /// /// - Parameters: /// - subrange: The subrange of the array to replace. The bounds of @@ -496,12 +638,14 @@ extension RigidArray { /// - Complexity: O(`self.count` + `newElements.count`) @inlinable @inline(__always) - public mutating func replaceSubrange( - _ subrange: Range, + public mutating func replace( + removing subrange: Range, copying newElements: __owned some Collection ) { - _replaceSubrange( - subrange, copyingCollection: newElements, newCount: newElements.count) + _replace( + removing: subrange, + copyingCollection: newElements, + newCount: newElements.count) } #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW @@ -517,13 +661,13 @@ extension RigidArray { /// elements, then this method triggers a runtime error. /// /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. + /// inserts the elements of `newElements` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(copying:at:)`. /// /// Likewise, if you pass a zero-length container as the `newElements` /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. /// /// - Parameters: /// - subrange: The subrange of the array to replace. The bounds of @@ -534,14 +678,16 @@ extension RigidArray { /// *m* is the count of `newElements`. @inlinable @inline(__always) - public mutating func replaceSubrange< + public mutating func replace< C: Container & Collection >( - _ subrange: Range, + removing subrange: Range, copying newElements: C ) { - _replaceSubrange( - subrange, copyingContainer: newElements, newCount: newElements.count) + _replace( + removing: subrange, + copyingContainer: newElements, + newCount: newElements.count) } #endif } diff --git a/Sources/BasicContainers/RigidArray.swift b/Sources/BasicContainers/RigidArray/RigidArray.swift similarity index 73% rename from Sources/BasicContainers/RigidArray.swift rename to Sources/BasicContainers/RigidArray/RigidArray.swift index 6d78ed8c..2ef88c48 100644 --- a/Sources/BasicContainers/RigidArray.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors +// Copyright (c) 2024 - 2026 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information @@ -86,30 +86,16 @@ public struct RigidArray: ~Copyable { @usableFromInline internal var _count: Int + @_alwaysEmitIntoClient deinit { unsafe _storage.extracting(0 ..< _count).deinitialize() unsafe _storage.deallocate() } - - /// Initializes a new rigid array with the specified capacity and no elements. - @inlinable - public init(capacity: Int) { - precondition(capacity >= 0, "Array capacity must be nonnegative") - if capacity > 0 { - unsafe _storage = .allocate(capacity: capacity) - } else { - unsafe _storage = .init(start: nil, count: 0) - } - _count = 0 - } - - /// Initializes a new rigid array with zero capacity and no elements. - /// - /// - Complexity: O(1) - @inlinable - public init() { - unsafe _storage = .init(start: nil, count: 0) - _count = 0 + + @_alwaysEmitIntoClient + package init(_storage: UnsafeMutableBufferPointer, count: Int) { + self._storage = _storage + self._count = count } } @@ -210,7 +196,7 @@ extension RigidArray where Element: ~Copyable { extension RigidArray where Element: ~Copyable { /// Arbitrarily edit the storage underlying this array by invoking a /// user-supplied closure with a mutable `OutputSpan` view over it. - /// This method calls its function argument precisely once, allowing it to + /// This method calls its function argument at most once, allowing it to /// arbitrarily modify the contents of the output span it is given. /// The argument is free to add, remove or reorder any items; however, /// it is not allowed to replace the span or change its capacity. @@ -221,7 +207,7 @@ extension RigidArray where Element: ~Copyable { /// /// - Parameter body: A function that edits the contents of this array through /// an `OutputSpan` argument. This method invokes this function - /// precisely once. + /// at most once. /// - Returns: This method returns the result of its function argument. /// - Complexity: Adds O(1) overhead to the complexity of the function /// argument. @@ -267,125 +253,6 @@ extension RigidArray where Element: ~Copyable { //MARK: - Container primitives -@available(SwiftStdlib 5.0, *) -extension RigidArray where Element: ~Copyable { - /// A Boolean value indicating whether this array contains no elements. - /// - /// - Complexity: O(1) - @inlinable - @inline(__always) - public var isEmpty: Bool { count == 0 } - - /// The number of elements in this array. - /// - /// - Complexity: O(1) - @inlinable - @inline(__always) - public var count: Int { _count } -} - -#if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW -@available(SwiftStdlib 5.0, *) -extension RigidArray: Container where Element: ~Copyable { - public typealias BorrowIterator = Span - - @_alwaysEmitIntoClient - @inline(__always) - public func startBorrowIteration() -> Span { - self.span - } -} -#endif - -@available(SwiftStdlib 5.0, *) -extension RigidArray where Element: ~Copyable { - /// A type that represents a position in the array: an integer offset from the - /// start. - /// - /// Valid indices consist of the position of every element and a "past the - /// end” position that’s not valid for use as a subscript argument. - public typealias Index = Int - - /// The position of the first element in a nonempty array. This is always zero. - /// - /// - Complexity: O(1) - @inlinable - @inline(__always) - public var startIndex: Int { 0 } - - /// The array’s "past the end” position—that is, the position one greater than - /// the last valid subscript argument. This is always equal to array's count. - /// - /// - Complexity: O(1) - @inlinable - @inline(__always) - public var endIndex: Int { count } - - /// The range of indices that are valid for subscripting the array. - /// - /// - Complexity: O(1) - @inlinable - @inline(__always) - public var indices: Range { unsafe Range(uncheckedBounds: (0, count)) } -} - -@available(SwiftStdlib 5.0, *) -extension RigidArray where Element: ~Copyable { - @inlinable @inline(__always) - internal func _ptr(to index: Int) -> UnsafePointer { - precondition(index >= 0 && index < _count, "Index out of bounds") - let p = _storage.baseAddress.unsafelyUnwrapped.advanced(by: index) - return UnsafePointer(p) - } - - @inlinable @inline(__always) - internal mutating func _mutablePtr( - to index: Int - ) -> UnsafeMutablePointer { - precondition(index >= 0 && index < _count, "Index out of bounds") - return _storage.baseAddress.unsafelyUnwrapped.advanced(by: index) - } - - /// Accesses the element at the specified position. - /// - /// - Parameter position: The position of the element to access. - /// The position must be a valid index of the array that is not equal - /// to the `endIndex` property. - /// - /// - Complexity: O(1) - @inlinable - public subscript(position: Int) -> Element { - @inline(__always) - unsafeAddress { - _ptr(to: position) - } - @inline(__always) - unsafeMutableAddress { - _mutablePtr(to: position) - } - } -} - -@available(SwiftStdlib 5.0, *) -extension RigidArray where Element: ~Copyable { - /// Exchanges the values at the specified indices of the array. - /// - /// Both parameters must be valid indices of the array and not equal to - /// endIndex. Passing the same index as both `i` and `j` has no effect. - /// - /// - Parameter i: The index of the first value to swap. - /// - Parameter j: The index of the second valud to swap. - /// - /// - Complexity: O(1) - @inlinable - public mutating func swapAt(_ i: Int, _ j: Int) { - precondition( - i >= 0 && i < _count && j >= 0 && j < _count, - "Index out of bounds") - unsafe _items.swapAt(i, j) - } -} - @available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { /// Return a borrowing span over the maximal storage chunk following the @@ -496,11 +363,11 @@ extension RigidArray { /// instance with just enough capacity to hold all its elements. /// /// - Complexity: O(`count`) - @inlinable - public func copy() -> Self { - copy(capacity: count) + @_alwaysEmitIntoClient + public func clone() -> Self { + clone(capacity: self.count) } - + /// Copy the contents of this array into a newly allocated rigid array /// instance with the specified capacity. /// @@ -509,7 +376,7 @@ extension RigidArray { /// /// - Complexity: O(`count`) @inlinable - public func copy(capacity: Int) -> Self { + public func clone(capacity: Int) -> Self { precondition(capacity >= count, "RigidArray capacity overflow") var result = RigidArray(capacity: capacity) let initialized = unsafe result._storage.initialize(fromContentsOf: _items) @@ -555,35 +422,29 @@ extension RigidArray where Element: ~Copyable { Range(uncheckedBounds: (index, index + count))) } - /// Perform a range replacement up to populating the newly opened gap. This - /// deinitializes existing elements in the specified subrange, rearranges - /// following elements to be at their final location, and sets the container's - /// new count. + /// Resize the gap in the given subrange to have the specified count. + /// This operation moves elements following the gap to be at their expected + /// new location, and it adjusts the container's count to reflect the change. /// /// - Returns: A buffer pointer addressing the newly opened gap, to be /// initialized by the caller. @inlinable @unsafe - internal mutating func _gapForReplacement( - of subrange: Range, withNewCount newCount: Int + internal mutating func _resizeGap( + in subrange: Range, to newItemCount: Int ) -> UnsafeMutableBufferPointer { - precondition( - subrange.lowerBound >= 0 && subrange.upperBound <= _count, - "Index range out of bounds") - precondition( - newCount - subrange.count <= freeCapacity, - "RigidArray capacity overflow") - unsafe _items.extracting(subrange).deinitialize() - if newCount > subrange.count { + assert(subrange.lowerBound >= 0 && subrange.upperBound <= _count) + assert(newItemCount >= 0 && newItemCount - subrange.count <= freeCapacity) + if newItemCount > subrange.count { _ = unsafe _openGap( - at: subrange.upperBound, count: newCount - subrange.count) - } else if newCount < subrange.count { + at: subrange.upperBound, count: newItemCount - subrange.count) + } else if newItemCount < subrange.count { _closeGap( - at: subrange.lowerBound + newCount, count: subrange.count - newCount) + at: subrange.lowerBound + newItemCount, count: subrange.count - newItemCount) } - _count += newCount - subrange.count + _count += newItemCount - subrange.count let gapRange = unsafe Range( - uncheckedBounds: (subrange.lowerBound, subrange.lowerBound + newCount)) + uncheckedBounds: (subrange.lowerBound, subrange.lowerBound + newItemCount)) return unsafe _storage.extracting(gapRange) } } diff --git a/Sources/BasicContainers/UniqueArray+Append.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Append.swift similarity index 80% rename from Sources/BasicContainers/UniqueArray+Append.swift rename to Sources/BasicContainers/UniqueArray/UniqueArray+Append.swift index 7cb3c56d..55275d1c 100644 --- a/Sources/BasicContainers/UniqueArray+Append.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Append.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors +// Copyright (c) 2024 - 2026 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information @@ -43,22 +43,28 @@ extension UniqueArray where Element: ~Copyable { /// number of new elements, then this reallocates the array's storage to /// grow its capacity, using a geometric growth rate. /// - /// - Parameters - /// - count: The number of items to append to the array. - /// - body: A callback that gets called precisely once to directly - /// populate newly reserved storage within the array. The function - /// is allowed to initialize fewer than `count` items. The array is - /// appended however many items the callback adds to the output span - /// before it returns (or before it throws an error). + /// If the callback fails to fully populate its output span or if + /// it throws an error, then the array keeps all items that were + /// successfully initialized before the callback terminated the insertion. /// - /// - Complexity: O(`count`) + /// - Parameters: + /// - newItemCount: The number of items to append to the array. + /// - initializer: A callback that gets called at most once to directly + /// populate newly reserved storage within the array. The function + /// is allowed to initialize fewer than `uninitializedCount` items. + /// The array is appended however many items the callback adds to the + /// output span before it returns (or before it throws an error). + /// + /// - Complexity: O(`uninitializedCount`) @_alwaysEmitIntoClient - public mutating func append( - count: Int, - initializingWith body: (inout OutputSpan) throws(E) -> Result - ) throws(E) -> Result { - _ensureFreeCapacity(count) - return try _storage.append(count: count, initializingWith: body) + public mutating func append( + addingCount newItemCount: Int, + initializingWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) { + _ensureFreeCapacity(newItemCount) + return try _storage.append( + addingCount: newItemCount, + initializingWith: initializer) } } @@ -71,7 +77,7 @@ extension UniqueArray where Element: ~Copyable { /// buffer, then this reallocates the array's storage to grow its capacity, /// using a geometric growth rate. /// - /// - Parameters + /// - Parameters: /// - items: A fully initialized buffer whose contents to move into /// the array. /// @@ -92,7 +98,7 @@ extension UniqueArray where Element: ~Copyable { /// then this reallocates the array's storage to grow its capacity, /// using a geometric growth rate. /// - /// - Parameters + /// - Parameters: /// - items: An input span whose contents need to be appended to this array. /// /// - Complexity: O(`items.count`) @@ -112,7 +118,7 @@ extension UniqueArray where Element: ~Copyable { /// then this reallocates the array's storage to grow its capacity, /// using a geometric growth rate. /// - /// - Parameters + /// - Parameters: /// - items: An output span whose contents need to be appended to this array. /// /// - Complexity: O(`items.count`) @@ -132,7 +138,7 @@ extension UniqueArray where Element: ~Copyable { /// in the source array, then this automatically grows the target array's /// capacity, using a geometric growth rate. /// - /// - Parameters + /// - Parameters: /// - items: An array whose items to move to the end of this array. /// /// - Complexity: O(`items.count`) when amortized over many invocations on @@ -157,7 +163,7 @@ extension UniqueArray where Element: ~Copyable { /// in the source array, then this automatically grows the target array's /// capacity, using a geometric growth rate. /// - /// - Parameters + /// - Parameters: /// - items: An array whose items to move to the end of this array. /// /// - Complexity: O(`items.count`) @@ -180,7 +186,7 @@ extension UniqueArray { /// in the source buffer, then this automatically grows the array's /// capacity, using a geometric growth rate. /// - /// - Parameters + /// - Parameters: /// - newElements: A fully initialized buffer whose contents to copy into /// the array. /// @@ -200,7 +206,7 @@ extension UniqueArray { /// then this reallocates the array's storage to extend its capacity, using /// a geometric growth rate. /// - /// - Parameters + /// - Parameters: /// - newElements: A fully initialized buffer whose contents to copy into /// the array. /// @@ -219,7 +225,7 @@ extension UniqueArray { /// then this reallocates the array's storage to extend its capacity, using a /// geometric growth rate. /// - /// - Parameters + /// - Parameters: /// - newElements: A span whose contents to copy into the array. /// /// - Complexity: O(`newElements.count`) when amortized over many @@ -231,13 +237,34 @@ extension UniqueArray { } #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW - /// Copies the elements of a container to the end of this array. + @inlinable + internal mutating func _append< + Source: BorrowingSequence & ~Copyable & ~Escapable + >( + copying newElements: borrowing Source + ) { + _ensureFreeCapacity(newElements.underestimatedCount) + var it = newElements.makeBorrowingIterator() + while true { + let span = it.nextSpan() + if span.isEmpty { break } + _ensureFreeCapacity(span.count) + _storage.append(copying: span) + } + } + // FIXME: Add _append(copyingContainer:), forwarding to the same method on RigidArray +#endif + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Copies the elements of a borrowing sequence to the end of this array. /// /// If the array does not have sufficient capacity to hold enough elements, /// then this reallocates the array's storage to extend its capacity, using - /// a geometric growth rate. + /// a geometric growth rate. If the input sequence does not provide a precise + /// estimate of its count, then the array's storage may need to be resized + /// more than once. /// - /// - Parameters + /// - Parameters: /// - newElements: A container whose contents to copy into the array. /// /// - Complexity: O(`newElements.count`), when amortized over many invocations @@ -245,12 +272,11 @@ extension UniqueArray { @_alwaysEmitIntoClient @inline(__always) public mutating func append< - Source: Container & ~Copyable & ~Escapable + Source: BorrowingSequence & ~Copyable & ~Escapable >( copying newElements: borrowing Source ) { - _ensureFreeCapacity(newElements.count) - _storage._append(copyingContainer: newElements) + self._append(copying: newElements) } #endif @@ -259,11 +285,11 @@ extension UniqueArray { /// /// If the array does not have sufficient capacity to hold enough elements, /// then this reallocates the array's storage to extend its capacity, using - /// a geometric growth rate. If the input sequence does not provide a correct + /// a geometric growth rate. If the input sequence does not provide a precise /// estimate of its count, then the array's storage may need to be resized /// more than once. /// - /// - Parameters + /// - Parameters: /// - newElements: The new elements to copy into the array. /// /// - Complexity: O(*m*), where *m* is the length of `newElements`, when @@ -292,7 +318,7 @@ extension UniqueArray { /// then this reallocates the array's storage to extend its capacity, using a /// geometric growth rate. /// - /// - Parameters + /// - Parameters: /// - newElements: A container whose contents to copy into the array. /// /// - Complexity: O(`newElements.count`), when amortized over many invocations @@ -300,10 +326,9 @@ extension UniqueArray { @_alwaysEmitIntoClient @inline(__always) public mutating func append< - Source: Container & Sequence + Source: BorrowingSequence & Sequence >(copying newElements: Source) { - _ensureFreeCapacity(newElements.count) - _storage._append(copyingContainer: newElements) + self._append(copying: newElements) } #endif } diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Consumption.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Consumption.swift new file mode 100644 index 00000000..56ce174e --- /dev/null +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Consumption.swift @@ -0,0 +1,112 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2024 - 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + /// Remove the specified subrange of items from this array, + /// passing an input span to the given function to consume them in place. + /// + /// - Parameter subrange: The subrange of items to consume from this array. + /// - Parameter consumer: A function taking an input span of the removed items, + /// allowing them to be consumed straight out of the array's storage. + /// The function is not required to consume all items in the span; + /// however, the span's remaining items will still be removed from + /// the array. + /// + /// - Complexity: O(`self.count`) + @_alwaysEmitIntoClient + public mutating func consume( + _ subrange: Range, + consumingWith consumer: (inout InputSpan) -> Void + ) { + _storage.consume(subrange, consumingWith: consumer) + } + + /// Remove the specified subrange of items from this deque, + /// passing a series of input spans to a given callback function to consume + /// them in place. + /// + /// The callback is not required to fully consume the contents of its + /// argument; any items it leaves in the input span get automatically + /// consumed. The underlying storage isn't necessarily contiguous, so + /// the callback may be called more than once, whether or not it fully + /// consumes its input. If the specified range is empty, the callback + /// may not be called at all. + /// + /// - Parameter subrange: The subrange of items to consume from this array. + /// - Parameter consumer: A function taking an input span of the removed items, + /// allowing them to be consumed straight out of the array's storage. + /// The function is called at most once. + /// + /// - Complexity: O(`self.count`) + @_alwaysEmitIntoClient + @inline(__always) + public mutating func consume>( + _ subrange: R, + consumingWith consumer: (inout InputSpan) -> Void + ) { + _storage.consume(subrange.relative(to: indices), consumingWith: consumer) + } + + /// Remove all items currently in this array, passing an input + /// span to a given callback function to consume them in place. + /// + /// The callback is not required to fully consume the contents of its + /// argument; any items it leaves in the input span get automatically + /// consumed. + /// + /// - Parameter consumer: A function taking an input span of the removed items, + /// allowing them to be consumed straight out of the array's storage. + /// The function is called at most once. + /// + /// - Complexity: O(`self.count`) + @_alwaysEmitIntoClient + public mutating func consumeAll( + consumingWith consumer: (inout InputSpan) -> Void + ) { + _storage.consume(indices, consumingWith: consumer) + } + + /// Remove the specified number of items from the end of this array, + /// passing an input span to a given callback function to consume them in + /// place. + /// + /// The callback is not required to fully consume the contents of its + /// argument; any items it leaves in the input span get automatically + /// consumed. + /// + /// - Parameter n: The number of items to consume from the end of the array. + /// `n` must be greater than or equal to zero and must not exceed + /// the count of the array. + /// - Parameter consumer: A function taking an input span of the removed items, + /// allowing them to be consumed straight out of the array's storage. + /// The function is called at most once. + /// - Complexity: O(`n`) + @inline(__always) + @_alwaysEmitIntoClient + public mutating func consumeLast( + _ n: Int, + consumingWith consumer: (inout InputSpan) -> Void + ) { + _storage.consumeLast(n, consumingWith: consumer) + } +} +#endif + +#endif diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift new file mode 100644 index 00000000..789a2fdb --- /dev/null +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift @@ -0,0 +1,344 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +@available(SwiftStdlib 5.0, *) +extension UniqueArray: BorrowingSequence where Element: ~Copyable { + public typealias BorrowingIterator = RigidArray.BorrowingIterator + + public var estimatedCount: EstimatedCount { + .exactly(count) + } + + @_alwaysEmitIntoClient + @inline(__always) + public func makeBorrowingIterator() -> BorrowingIterator { + self._storage.makeBorrowingIterator() + } +} +#endif + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +@available(SwiftStdlib 5.0, *) +extension UniqueArray: Container where Element: ~Copyable { +} +#endif + +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + /// A Boolean value indicating whether this array contains no elements. + /// + /// - Complexity: O(1) + @inlinable + @inline(__always) + public var isEmpty: Bool { _storage.isEmpty } + + /// The number of elements in this array. + /// + /// - Complexity: O(1) + @inlinable + @inline(__always) + public var count: Int { _storage.count } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + /// A type that represents a position in the array: an integer offset from the + /// start. + /// + /// Valid indices consist of the position of every element and a "past the + /// end” position that’s not valid for use as a subscript argument. + public typealias Index = Int + + /// The position of the first element in a nonempty array. This is always zero. + /// + /// - Complexity: O(1) + @inlinable + @inline(__always) + public var startIndex: Int { _storage.startIndex } + + /// The array’s "past the end” position—that is, the position one greater than + /// the last valid subscript argument. This is always equal to array's count. + /// + /// - Complexity: O(1) + @inlinable + @inline(__always) + public var endIndex: Int { _storage.count } + + /// The range of indices that are valid for subscripting the array. + /// + /// - Complexity: O(1) + @inlinable + @inline(__always) + public var indices: Range { _storage.indices } + + /// Accesses the element at the specified position. + /// + /// - Parameter position: The position of the element to access. + /// The position must be a valid index of the array that is not equal + /// to the `endIndex` property. + /// + /// - Complexity: O(1) + @inlinable + public subscript(position: Int) -> Element { + @inline(__always) + unsafeAddress { + _storage._ptr(to: position) + } + @inline(__always) + unsafeMutableAddress { + _storage._mutablePtr(to: position) + } + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + /// Exchanges the values at the specified indices of the array. + /// + /// Both parameters must be valid indices of the array and not equal to + /// endIndex. Passing the same index as both `i` and `j` has no effect. + /// + /// - Parameter i: The index of the first value to swap. + /// - Parameter j: The index of the second valud to swap. + /// + /// - Complexity: O(1) + @inlinable + public mutating func swapAt(_ i: Int, _ j: Int) { + _storage.swapAt(i, j) + } +} + + +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + /// Returns the position immediately after the given index. + /// + /// - Note: To improve performance, this method does not validate that the + /// index is valid before incrementing it. Index validation is + /// deferred until the resulting index is used to access an element. + /// This optimization may be removed in future versions; do not rely on it. + /// + /// - Parameter index: A valid index of the array. `i` must be less + /// than `endIndex`. + /// - Returns: The index immediately following `i`. + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @inline(__always) + public func index(after index: Int) -> Int { index + 1 } + + /// Returns the position immediately before the given index. + /// + /// - Note: To improve performance, this method does not validate that the + /// index is valid before decrementing it. Index validation is + /// deferred until the resulting index is used to access an element. + /// This optimization may be removed in future versions; do not rely on it. + /// + /// - Parameter index: A valid index of the array. `i` must be greater + /// than `startIndex`. + /// - Returns: The index immediately preceding `i`. + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @inline(__always) + public func index(before index: Int) -> Int { index - 1 } + + /// Replaces the given index with its successor. + /// + /// - Note: To improve performance, this method does not validate that the + /// given index is valid before incrementing it. Index validation is + /// deferred until the resulting index is used to access an element. + /// This optimization may be removed in future versions; do not rely on it. + /// + /// - Parameter index: A valid index of the array. `i` must be less + /// than `endIndex`. + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @inline(__always) + public func formIndex(after index: inout Int) { index += 1 } + + /// Replaces the given index with its predecessor. + /// + /// - Note: To improve performance, this method does not validate that the + /// given index is valid before decrementing it. Index validation is + /// deferred until the resulting index is used to access an element. + /// This optimization may be removed in future versions; do not rely on it. + /// + /// - Parameter index: A valid index of the array. `i` must be greater than + /// `startIndex`. + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @inline(__always) + public func formIndex(before index: inout Int) { index -= 1 } + + /// Returns an index that is the specified distance from the given index. + /// + /// The value passed as `n` must not offset `index` beyond the bounds of the + /// array. + /// + /// - Note: To improve performance, this method does not validate that the + /// given index is valid before offseting it. Index validation is + /// deferred until the resulting index is used to access an element. + /// This optimization may be removed in future versions; do not rely on it. + /// + /// - Parameter index: A valid index of the array. + /// - Parameter n: The distance by which to offset `index`. + /// - Returns: An index offset by distance from `index`. If `n` is positive, + /// this is the same value as the result of `n` calls to `index(after:)`. + /// If `n` is negative, this is the same value as the result of `abs(n)` + /// calls to `index(before:)`. + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @inline(__always) + public func index(_ index: Int, offsetBy n: Int) -> Int { + index + n + } + + /// Returns the distance between two indices. + /// + /// - Note: To improve performance, this method does not validate that the + /// given index is valid before offseting it. Index validation is + /// deferred until the resulting index is used to access an element. + /// This optimization may be removed in future versions; do not rely on it. + /// + /// - Parameter start: A valid index of the collection. + /// - Parameter end: Another valid index of the collection. If end is equal + /// to start, the result is zero. + /// - Returns: The distance between `start` and `end`. + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @inline(__always) + public func distance(from start: Index, to end: Index) -> Int { + end - start + } + + /// Offsets the given index by the specified distance, but no further than + /// the given limiting index. + /// + /// If the operation was able to offset `index` by exactly the requested + /// number of steps without hitting `limit`, then on return `n` is set to `0`, + /// and `index` is set to the adjusted index. + /// + /// If the operation hits the limit before it can take the requested number + /// of steps, then on return `index` is set to `limit`, and `n` is set + /// to the number of steps that couldn't be taken. + /// + /// The value passed as `n` must not offset `index` beyond the bounds of the + /// container, unless the index passed as `limit` prevents offsetting beyond + /// those bounds. + /// + /// - Note: To improve performance, this method does not validate that the + /// given index is valid before offseting it. Index validation is + /// deferred until the resulting index is used to access an element. + /// This optimization may be removed in future versions; do not rely on it. + /// + /// - Parameter index: A valid index of the array. On return, `index` is + /// set to `limit` if + /// - Parameter n: The distance to offset `index`. + /// On return, `n` is set to zero if the operation succeeded without + /// hitting the limit; otherwise, `n` reflects the number of steps that + /// couldn't be taken. + /// - Parameter limit: A valid index of the array to use as a limit. + /// If `n > 0`, a limit that is less than `index` has no effect. + /// Likewise, if `n < 0`, a limit that is greater than `index` has no + /// effect. + /// - Complexity: O(1) + @_alwaysEmitIntoClient + public func formIndex( + _ index: inout Index, offsetBy n: inout Int, limitedBy limit: Index + ) { + _storage.formIndex(&index, offsetBy: &n, limitedBy: limit) + } + + /// Return a span over the array's storage that begins with the element at + /// the given index, and extends to the end of the contiguous storage chunk + /// that contains it, but no more than `maximumCount` items. + /// + /// On return, the index is updated to address the next item following the + /// end of the returned span. + /// + /// This method can be used to efficiently process the items of a container in + /// bulk, by directly iterating over its piecewise contiguous pieces of + /// storage: + /// + /// var index = items.startIndex + /// while true { + /// let span = items.nextSpan(after: &index, maximumCount: 4) + /// if span.isEmpty { break } + /// // Process items in `span` + /// } + /// + /// The `maximumCount` argument gives the caller control over the number of + /// items it receives from the iterator. This lets the caller avoid getting + /// more elements than it would be able to immediately process, which would + /// significantly complicate container use. + /// + /// If the caller is able to process any number available items, it can signal + /// that by passing `Int.max` as the `maximumCount`, or simply by calling the + /// `nexSpan(after:)` method, which does precisely that. This is frequently + /// the case when the caller simply wants to iterate over the entire + /// container in a single loop. + /// + /// `maximumCount` sets an upper bound. To read a specific number of items, + /// the caller usually needs to invoke `nextSpan` in a loop: + /// + /// var items: some Container + /// var index = items.startIndex + /// var remainder = numberOfItemsToRead + /// while remainder > 0 { + /// let next = items.nextSpan(after: &index, maximumCount: remainder) + /// guard !next.isEmpty else { + /// // Container does not have enough items + /// break + /// } + /// remainder -= next.count + /// // Process items in `next` + /// } + /// + /// - Note: The spans returned by this method are not guaranteed to be + /// disjunct. Some containers may use the same storage chunk (or parts of a + /// storage chunk) multiple times, to repeat their contents. + /// + /// - Note: Repeated invocations of `nextSpan` on the same container and index + /// are not guaranteed to return identical results. (This is particularly + /// the case with containers that can store contents in their "inline" + /// representation. Such containers may not always have a unique address + /// in memory; the locations of the spans exposed by this method may vary + /// between different borrows of the same container.) + /// + /// - Parameter index: A valid index in the container, including the end + /// index. On return, this index is advanced by the count of the resulting + /// span, to simplify iteration. + /// - Parameter maximumCount: The maximum number of items the caller is able + /// to process immediately. `maximumCount` must be greater than zero. + /// If you are able to process an arbitrary number of items, set + /// `maximumCount` to `Int.max`, or call the `nextSpan(after:)` method. + /// - Returns: A span over contiguous storage that starts at the given index. + /// If the input index is the end index, then this returns an empty span. + /// Otherwise the result is non-empty, with its first element matching the + /// element at the input index. + /// - Complexity: O(1) + @inlinable + @_lifetime(borrow self) + public func nextSpan( + after index: inout Int, maximumCount: Int + ) -> Span { + _storage.nextSpan(after: &index, maximumCount: maximumCount) + } +} + +#endif diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Deprecated.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Deprecated.swift new file mode 100644 index 00000000..552da64d --- /dev/null +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Deprecated.swift @@ -0,0 +1,452 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2024 - 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + /// Append a given number of items to the end of this array by populating + /// an output span. + /// + /// If the array does not have sufficient capacity to hold the requested + /// number of new elements, then this reallocates the array's storage to + /// grow its capacity, using a geometric growth rate. + /// + /// - Parameters: + /// - count: The number of items to append to the array. + /// - initializer: A callback that gets called exactly once to directly + /// populate newly reserved storage within the array. The function + /// is allowed to initialize fewer than `count` items. The array is + /// appended however many items the callback adds to the output span + /// before it returns (or before it throws an error). + /// + /// - Complexity: O(`count`) + @available(*, deprecated, renamed: "append(addingCount:initializingWith:)") + @_alwaysEmitIntoClient + @inline(__always) + public mutating func append( + count: Int, + initializingWith initializer: (inout OutputSpan) throws(E) -> Result + ) throws(E) -> Result { + var result: Result? = nil + try append(addingCount: count) { target throws(E) in + result = try initializer(&target) + } + return result.take()! + } + + /// Inserts a given number of new items into this array at the specified + /// position, using a callback to directly initialize array storage by + /// populating an output span. + /// + /// All existing elements at or following the specified position are moved to + /// make room for the new items. + /// + /// If the array does not have sufficient capacity to hold the new elements, + /// then this reallocates storage to extend its capacity, using a geometric + /// growth rate. + /// + /// - Parameters: + /// - count: The number of items to insert into the array. + /// - index: The position at which to insert the new items. + /// `index` must be a valid index in the array. + /// - body: A callback that gets called exactly once to directly + /// populate newly reserved storage within the array. The function + /// is called with an empty output span of capacity matching the + /// supplied count, and it must fully populate it before returning. + /// + /// - Complexity: O(`self.count` + `count`) + @available(*, deprecated, renamed: "insert(addingCount:at:initializingWith:)") + @inlinable + public mutating func insert( + count: Int, + at index: Int, + initializingWith body: (inout OutputSpan) -> Result + ) -> Result { + var result: Result? = nil + self.insert(addingCount: count, at: index) { target in + result = body(&target) + } + return result! + } + + /// Replaces the specified range of elements by a given count of new items, + /// using a callback to directly initialize array storage by populating + /// an output span. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting room for the new elements starting at the + /// same location. The number of new elements need not match the number + /// of elements being removed. + /// + /// If the array does not have sufficient capacity to perform the replacement, + /// then this reallocates storage to extend its capacity, using a geometric + /// growth rate. + /// + /// If you pass a zero-length range as the `subrange` parameter, then + /// this method is equivalent to calling + /// `insert(count: newCount, initializingWith: body)`. + /// + /// Likewise, if you pass a zero for `newCount`, then this method + /// removes the elements in the given subrange without any replacement. + /// Calling `removeSubrange(subrange)` is preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newCount: the number of items to replace the old subrange. + /// - body: A callback that gets called exactly once to directly + /// populate newly reserved storage within the array. The function + /// is called with an empty output span of capacity `newCount`, + /// and it must fully populate it before returning. + /// + /// - Complexity: O(`self.count` + `newCount`) + @available(*, deprecated, renamed: "replace(removing:addingCount:initializingWith:)") + @inlinable + public mutating func replaceSubrange( + _ subrange: Range, + newCount: Int, + initializingWith body: (inout OutputSpan) -> Result + ) -> Result { + var result: Result? = nil + self.replace(removing: subrange, addingCount: newCount) { target in + result = body(&target) + } + return result! + } + + /// Replaces the specified range of elements by moving the elements of a + /// fully initialized buffer into their place. On return, the buffer is left + /// in an uninitialized state. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the array does not have sufficient capacity to perform the replacement, + /// then this reallocates the array's storage to extend its capacity, using a + /// geometric growth rate. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: A fully initialized buffer whose contents to move into + /// the array. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @available(*, deprecated, renamed: "replace(removing:moving:)") + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + moving newElements: UnsafeMutableBufferPointer, + ) { + self.replace(removing: subrange, moving: newElements) + } + + /// Replaces the specified range of elements by moving the contents of an + /// output span into their place. On return, the span is left empty. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the array does not have sufficient capacity to perform the replacement, + /// then this reallocates the array's storage to extend its capacity, using a + /// geometric growth rate. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(moving:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - items: An output span whose contents are to be moved into the array. + /// + /// - Complexity: O(`self.count` + `items.count`) + @available(*, deprecated, renamed: "replace(removing:moving:)") + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + moving items: inout OutputSpan + ) { + self.replace(removing: subrange, moving: &items) + } + + /// Replaces the specified range of elements by moving the elements of a + /// another array into their place. On return, the source array + /// becomes empty, but it is not destroyed, and it preserves its original + /// storage capacity. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the array does not have sufficient capacity to hold enough elements, + /// then this reallocates the array's storage to extend its capacity, using a + /// geometric growth rate. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: An array whose contents to move into `self`. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @available(*, deprecated, renamed: "replace(removing:moving:)") + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + moving newElements: inout RigidArray, + ) { + self.replace(removing: subrange, moving: &newElements) + } + + /// Replaces the specified range of elements by moving the elements of a + /// given array into their place, consuming it in the process. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the array does not have sufficient capacity to perform the replacement, + /// then this reallocates the array's storage to extend its capacity, using a + /// geometric growth rate. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: An array whose contents to move into `self`. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @available(*, deprecated, renamed: "replace(removing:consuming:)") + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + consuming newElements: consuming RigidArray, + ) { + self.replace(removing: subrange, consuming: newElements) + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueArray { + /// Copy the contents of this array into a newly allocated unique array + /// instance with just enough capacity to hold all its elements. + /// + /// - Complexity: O(`count`) + @available(*, deprecated, renamed: "clone()") + @inlinable + public func copy() -> Self { + self.clone() + } + + /// Copy the contents of this array into a newly allocated unique array + /// instance with the specified capacity. + /// + /// - Parameter capacity: The desired capacity of the resulting unique array. + /// `capacity` must be greater than or equal to `count`. + /// + /// - Complexity: O(`count`) + @available(*, deprecated, renamed: "clone(capacity:)") + @inlinable + public func copy(capacity: Int) -> Self { + clone(capacity: capacity) + } + + /// Replaces the specified subrange of elements by copying the elements of + /// the given buffer pointer, which must be fully initialized. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same location. + /// The number of new elements need not match the number of elements being + /// removed. + /// + /// If the capacity of the array isn't sufficient to perform the replacement, + /// then this reallocates the array's storage to extend its capacity, using a + /// geometric growth rate. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: The new elements to copy into the collection. + /// + /// - Complexity: O(*n* + *m*), where *n* is count of this array and + /// *m* is the count of `newElements`. + @available(*, deprecated, renamed: "replace(removing:copying:)") + @inlinable + @inline(__always) + public mutating func replaceSubrange( + _ subrange: Range, + copying newElements: UnsafeBufferPointer + ) { + self.replace(removing: subrange, copying: newElements) + } + + /// Replaces the specified subrange of elements by copying the elements of + /// the given buffer pointer, which must be fully initialized. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same location. + /// The number of new elements need not match the number of elements being + /// removed. + /// + /// If the capacity of the array isn't sufficient to perform the replacement, + /// then this reallocates the array's storage to extend its capacity, using a + /// geometric growth rate. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: The new elements to copy into the collection. + /// + /// - Complexity: O(*n* + *m*), where *n* is count of this array and + /// *m* is the count of `newElements`. + @available(*, deprecated, renamed: "replace(removing:copying:)") + @inlinable + @inline(__always) + public mutating func replaceSubrange( + _ subrange: Range, + copying newElements: UnsafeMutableBufferPointer + ) { + self.replace(removing: subrange, copying: newElements) + } + + /// Replaces the specified subrange of elements by copying the elements of + /// the given span. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same location. + /// The number of new elements need not match the number of elements being + /// removed. + /// + /// If the capacity of the array isn't sufficient to perform the replacement, + /// then this reallocates the array's storage to extend its capacity, using a + /// geometric growth rate. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length span as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: The new elements to copy into the collection. + /// + /// - Complexity: O(*n* + *m*), where *n* is count of this array and + /// *m* is the count of `newElements`. + @available(*, deprecated, renamed: "replace(removing:copying:)") + @inlinable + public mutating func replaceSubrange( + _ subrange: Range, + copying newElements: Span + ) { + self.replace(removing: subrange, copying: newElements) + } + + /// Replaces the specified subrange of elements by copying the elements of + /// the given collection. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same location. + /// The number of new elements need not match the number of elements being + /// removed. + /// + /// If the capacity of the array isn't sufficient to perform the replacement, + /// then this reallocates the array's storage to extend its capacity, using a + /// geometric growth rate. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length collection as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: The new elements to copy into the collection. + /// + /// - Complexity: O(*n* + *m*), where *n* is count of this array and + /// *m* is the count of `newElements`. + @available(*, deprecated, renamed: "replace(removing:copying:)") + @inlinable + @inline(__always) + public mutating func replaceSubrange( + _ subrange: Range, + copying newElements: __owned some Collection + ) { + self.replace(removing: subrange, copying: newElements) + } +} + +#endif diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Descriptions.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Descriptions.swift new file mode 100644 index 00000000..bf815ce5 --- /dev/null +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Descriptions.swift @@ -0,0 +1,30 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension UniqueArray /*: CustomStringConvertible */ where Element: ~Copyable { + public var description: String { + /// FIXME: Print the item descriptions when available. + "<\(count) items>" + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueArray /*: CustomDebugStringConvertible */ where Element: ~Copyable { + public var debugDescription: String { + /// FIXME: Print the item descriptions when available. + "<\(count) items>" + } +} + +#endif diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Equatable.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Equatable.swift new file mode 100644 index 00000000..2c4753ae --- /dev/null +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Equatable.swift @@ -0,0 +1,29 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.2) + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +#endif + +@available(SwiftStdlib 5.0, *) +extension UniqueArray /*: Equatable */ where Element: Equatable /* & ~Copyable */ { + @inlinable + public static func ==( + left: borrowing Self, + right: borrowing Self + ) -> Bool { + left.span._elementsEqual(to: right.span) + } +} + +#endif diff --git a/Sources/BasicContainers/UniqueArray+Experimental.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Experimental.swift similarity index 100% rename from Sources/BasicContainers/UniqueArray+Experimental.swift rename to Sources/BasicContainers/UniqueArray/UniqueArray+Experimental.swift diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Hashable.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Hashable.swift new file mode 100644 index 00000000..ee93d30c --- /dev/null +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Hashable.swift @@ -0,0 +1,26 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension UniqueArray /*: Hashable */ where Element: Hashable /* & ~Copyable */ { + @inlinable + public func hash(into hasher: inout Hasher) { + hasher.combine(self.count) + let span = self.span + for i in 0 ..< count { + hasher.combine(span[unchecked: i]) + } + } +} + +#endif diff --git a/Sources/BasicContainers/UniqueArray+Initializers.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Initializers.swift similarity index 72% rename from Sources/BasicContainers/UniqueArray+Initializers.swift rename to Sources/BasicContainers/UniqueArray/UniqueArray+Initializers.swift index f0110a85..5706f5e8 100644 --- a/Sources/BasicContainers/UniqueArray+Initializers.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Initializers.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors +// Copyright (c) 2024 - 2026 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information @@ -16,6 +16,21 @@ import ContainersPreview #if compiler(>=6.2) +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + /// Initializes a new unique array with no elements. + @inlinable + public init() { + _storage = .init(capacity: 0) + } + + /// Initializes a new unique array with the specified capacity and no elements. + @inlinable + public init(capacity: Int) { + _storage = .init(capacity: capacity) + } +} + @available(SwiftStdlib 5.0, *) extension UniqueArray where Element: ~Copyable { /// Creates a new array with the specified capacity, directly initializing @@ -23,7 +38,7 @@ extension UniqueArray where Element: ~Copyable { /// /// - Parameters: /// - capacity: The storage capacity of the new array. - /// - body: A callback that gets called precisely once to directly + /// - body: A callback that gets called at most once to directly /// populate newly reserved storage within the array. The function /// is allowed to add fewer than `capacity` items. The array is /// initialized with however many items the callback adds to the @@ -70,16 +85,16 @@ extension UniqueArray where Element: ~Copyable { extension UniqueArray /*where Element: Copyable*/ { #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW /// Creates a new array with the specified initial capacity, holding a copy - /// of the contents of a given container. + /// of the contents of a given borrowing sequence. /// /// - Parameters: /// - capacity: The storage capacity of the new array, or nil to allocate /// just enough capacity to store the contents. - /// - contents: The container whose contents to copy into the new array. - /// The container must not contain more than `capacity` elements. + /// - contents: A sequence whose contents to copy into the new array. + /// The sequence must not contain more than `capacity` elements. @_alwaysEmitIntoClient @inline(__always) - public init & ~Copyable & ~Escapable>( + public init & ~Copyable & ~Escapable>( capacity: Int? = nil, copying contents: borrowing Source ) { @@ -115,7 +130,7 @@ extension UniqueArray /*where Element: Copyable*/ { /// - contents: The container whose contents to copy into the new array. @_alwaysEmitIntoClient @inline(__always) - public init & Sequence>( + public init & Sequence>( capacity: Int? = nil, copying contents: Source ) { @@ -124,6 +139,23 @@ extension UniqueArray /*where Element: Copyable*/ { } #endif + /// Creates a new array with the specified capacity, holding a copy + /// of the contents of the given span. + /// + /// - Parameters: + /// - capacity: The storage capacity of the new array, or nil to allocate + /// just enough capacity to store the contents of the span. + /// - span: The span whose contents to copy into the new array. + /// The span must not contain more than `capacity` elements. + @_alwaysEmitIntoClient + @inline(__always) + public init( + capacity: Int? = nil, + copying span: Span + ) { + self.init(capacity: capacity ?? span.count) + self.append(copying: span) + } } #endif diff --git a/Sources/BasicContainers/UniqueArray+Insertions.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Insertions.swift similarity index 92% rename from Sources/BasicContainers/UniqueArray+Insertions.swift rename to Sources/BasicContainers/UniqueArray/UniqueArray+Insertions.swift index 4e9fbf27..55e936b2 100644 --- a/Sources/BasicContainers/UniqueArray+Insertions.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Insertions.swift @@ -51,32 +51,46 @@ extension UniqueArray where Element: ~Copyable { /// position, using a callback to directly initialize array storage by /// populating an output span. /// - /// All existing elements at or following the specified position are moved to - /// make room for the new items. + /// Existing elements in the array's storage are moved towards the back as + /// needed to make room for the new items. /// /// If the array does not have sufficient capacity to hold the new elements, - /// then this reallocates storage to extend its capacity, using a geometric - /// growth rate. + /// then this operation reallocates storage to extend its capacity, using a + /// geometric growth rate. + /// + /// var buffer = UniqueArray() + /// buffer.append([-999, 999]) + /// var i = 0 + /// buffer.insert(capacity: 3, at: 1) { target in + /// while !target.isFull { + /// target.append(i) + /// i += 1 + /// } + /// } + /// // `buffer` now contains [-999, 0, 1, 2, 999] /// /// - Parameters: /// - count: The number of items to insert into the array. /// - index: The position at which to insert the new items. /// `index` must be a valid index in the array. - /// - body: A callback that gets called precisely once to directly + /// - body: A callback that gets called at most once to directly /// populate newly reserved storage within the array. The function /// is called with an empty output span of capacity matching the /// supplied count, and it must fully populate it before returning. /// /// - Complexity: O(`self.count` + `count`) - @inlinable - public mutating func insert( - count: Int, + @_alwaysEmitIntoClient + @inline(__always) + public mutating func insert( + addingCount newItemCount: Int, at index: Int, - initializingWith body: (inout OutputSpan) -> Result - ) -> Result { - // FIXME: This does not allow `body` to throw, to prevent having to move the tail twice. Is that okay? - _ensureFreeCapacity(count) - return _storage.insert(count: count, at: index, initializingWith: body) + initializingWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) { + _ensureFreeCapacity(newItemCount) + try _storage.insert( + addingCount: newItemCount, + at: index, + initializingWith: initializer) } } @@ -90,7 +104,7 @@ extension UniqueArray where Element: ~Copyable { /// then this reallocates storage to extend its capacity, using a geometric /// growth rate. /// - /// - Parameters + /// - Parameters: /// - items: A fully initialized buffer whose contents to move into /// the array. /// @@ -116,7 +130,7 @@ extension UniqueArray where Element: ~Copyable { /// then this reallocates storage to extend its capacity, using a geometric /// growth rate. /// - /// - Parameters + /// - Parameters: /// - items: An input span whose contents to move into /// the array. /// - index: The position at which to insert the new items. @@ -143,7 +157,7 @@ extension UniqueArray where Element: ~Copyable { /// then this reallocates storage to extend its capacity, using a geometric /// growth rate. /// - /// - Parameters + /// - Parameters: /// - items: An output span whose contents to move into /// the array. /// - index: The position at which to insert the new items. @@ -168,7 +182,7 @@ extension UniqueArray where Element: ~Copyable { /// then this reallocates storage to extend its capacity, using a geometric /// growth rate. /// - /// - Parameters + /// - Parameters: /// - items: An array whose contents to move into `self`. /// /// - Complexity: O(`self.count` + `items.count`) @@ -193,7 +207,7 @@ extension UniqueArray where Element: ~Copyable { /// then this reallocates storage to extend its capacity, using a geometric /// growth rate. /// - /// - Parameters + /// - Parameters: /// - items: A fully initialized buffer whose contents to move into /// the array. /// @@ -227,7 +241,7 @@ extension UniqueArray { /// then this reallocates the array's storage to extend its capacity, using a /// geometric growth rate. /// - /// - Parameters + /// - Parameters: /// - newElements: The new elements to insert into the array. The buffer /// must be fully initialized. /// - index: The position at which to insert the new elements. It must be @@ -257,7 +271,7 @@ extension UniqueArray { /// then this reallocates the array's storage to extend its capacity, using a /// geometric growth rate. /// - /// - Parameters + /// - Parameters: /// - newElements: The new elements to insert into the array. The buffer /// must be fully initialized. /// - index: The position at which to insert the new elements. It must be @@ -285,7 +299,7 @@ extension UniqueArray { /// then this reallocates the array's storage to extend its capacity, using a /// geometric growth rate. /// - /// - Parameters + /// - Parameters: /// - newElements: The new elements to insert into the array. /// - index: The position at which to insert the new elements. It must be /// a valid index of the array. @@ -315,7 +329,7 @@ extension UniqueArray { /// then this reallocates the array's storage to extend its capacity, using a /// geometric growth rate. /// - /// - Parameters + /// - Parameters: /// - newElements: The new elements to insert into the array. /// - index: The position at which to insert the new elements. It must be /// a valid index of the array. @@ -350,7 +364,7 @@ extension UniqueArray { /// then this reallocates the array's storage to extend its capacity, using a /// geometric growth rate. /// - /// - Parameters + /// - Parameters: /// - newElements: The new elements to insert into the array. /// - index: The position at which to insert the new elements. It must be /// a valid index of the array. @@ -382,7 +396,7 @@ extension UniqueArray { /// then this reallocates the array's storage to extend its capacity, using a /// geometric growth rate. /// - /// - Parameters + /// - Parameters: /// - newElements: The new elements to insert into the array. /// - index: The position at which to insert the new elements. It must be /// a valid index of the array. diff --git a/Sources/BasicContainers/UniqueArray+Removals.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Removals.swift similarity index 63% rename from Sources/BasicContainers/UniqueArray+Removals.swift rename to Sources/BasicContainers/UniqueArray/UniqueArray+Removals.swift index 376cf430..ac8261a5 100644 --- a/Sources/BasicContainers/UniqueArray+Removals.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Removals.swift @@ -121,57 +121,4 @@ extension UniqueArray where Element: ~Copyable { } } -#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW -@available(SwiftStdlib 5.0, *) -extension UniqueArray where Element: ~Copyable { - /// Remove all items currently in this array, returning an input span to - /// allow them to be consumed in place. - /// The input span extends the exclusive mutating access initiated by this - /// operation to cover the span's lifetime. Once the span is destroyed, - /// the array becomes empty, but it preserves its original storage. - /// - /// - Complexity: O(*n*), where *n* is the original count of the array. - @_lifetime(&self) - @_alwaysEmitIntoClient - public mutating func consumeAll() -> InputSpan { - _storage.consumeAll() - } - - /// Remove the specified number of items from the end of this array, - /// returning an input span to allow them to be consumed in place. - /// The input span extends the exclusive mutating access initiated by this - /// operation to cover the span's lifetime. - /// - /// - Parameter n: The number of items to consume from the end of the array. - /// `n` must be greater than or equal to zero and must not exceed - /// the count of the array. - /// - /// - Complexity: O(`n`) - @_lifetime(&self) - @_alwaysEmitIntoClient - public mutating func consumeLast(_ count: Int) -> InputSpan { - _storage.consumeLast(count) - } - - /// Remove the specified subrange of items from this array, - /// passing an input span to the given function to consume them in place. - /// - /// - Parameter bounds: The subrange of items to consume from this array. - /// - Parameter body: A function taking an input span of the removed items, - /// allowing them to be consumed straight out of the array's storage. - /// The function is not required to consume all items in the span; - /// however, the span's remaining items will still be removed from - /// the array. - /// - /// - Complexity: O(`self.count`) - @_alwaysEmitIntoClient - public mutating func consumeSubrange( - _ bounds: Range, - consumingWith body: (inout InputSpan) throws(E) -> Result - ) throws(E) -> Result { - try _storage.consumeSubrange(bounds, consumingWith: body) - } -} -#endif - #endif diff --git a/Sources/BasicContainers/UniqueArray+Replacements.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Replacements.swift similarity index 74% rename from Sources/BasicContainers/UniqueArray+Replacements.swift rename to Sources/BasicContainers/UniqueArray/UniqueArray+Replacements.swift index b52b020d..aa6af999 100644 --- a/Sources/BasicContainers/UniqueArray+Replacements.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Replacements.swift @@ -22,49 +22,130 @@ extension UniqueArray where Element: ~Copyable { /// using a callback to directly initialize array storage by populating /// an output span. /// - /// This method has the effect of removing the specified range of elements - /// from the array and inserting room for the new elements starting at the - /// same location. The number of new elements need not match the number - /// of elements being removed. + /// The number of new items need not match the number of elements being + /// removed. + /// + /// This method has the same overall effect as calling + /// + /// try array.removeSubrange(subrange) + /// try array.insert( + /// addingCount: newItemCount, + /// at: subrange.lowerBound, + /// initializingWith: initializer) + /// + /// Except it performs faster (by a constant factor), by avoiding moving + /// some items in the array twice. /// /// If the array does not have sufficient capacity to perform the replacement, /// then this reallocates storage to extend its capacity, using a geometric /// growth rate. /// - /// If you pass a zero-length range as the `subrange` parameter, then - /// this method is equivalent to calling - /// `insert(count: newCount, initializingWith: body)`. + /// If the callback fails to fully populate its output span or if + /// it throws an error, then the array keeps all items that were + /// successfully initialized before the callback terminated the prepend. /// - /// Likewise, if you pass a zero for `newCount`, then this method - /// removes the elements in the given subrange without any replacement. - /// Calling `removeSubrange(subrange)` is preferred in this case. + /// Partial insertions create a gap in array storage that needs to be + /// closed by moving newly inserted items to their correct positions given + /// the adjusted count. This adds some overhead compared to adding exactly as + /// many items as promised. /// - /// - Parameters + /// - Parameters: /// - subrange: The subrange of the array to replace. The bounds of /// the range must be valid indices in the array. - /// - newCount: the number of items to replace the old subrange. - /// - body: A callback that gets called precisely once to directly + /// - newItemCount: the maximum number of items to replace the old subrange. + /// - initializer: A callback that gets called at most once to directly /// populate newly reserved storage within the array. The function - /// is called with an empty output span of capacity `newCount`, - /// and it must fully populate it before returning. + /// is always called with an empty output span. /// - /// - Complexity: O(`self.count` + `newCount`) + /// - Complexity: O(`self.count` + `newItemCount`) in addition to the complexity + /// of the callback invocations. @inlinable - public mutating func replaceSubrange( - _ subrange: Range, - newCount: Int, - initializingWith body: (inout OutputSpan) -> Result - ) -> Result { - // FIXME: Should we allow throwing (and a partially filled output span)? - // FIXME: Should we have a version of this with two closures, to allow custom-consuming the old items? - // replaceSubrange(5..<10, newCount: 3, consumingWith: {...}, initializingWith: {...}) - // FIXME: Avoid moving the subsequent elements twice. - _ensureFreeCapacity(newCount - subrange.count) - return _storage.replaceSubrange( - subrange, newCount: newCount, initializingWith: body) + public mutating func replace( + removing subrange: Range, + addingCount newItemCount: Int, + initializingWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) -> Void { + _storage._checkValidBounds(subrange) + precondition(newItemCount >= 0, "Cannot add a negative number of items") + // FIXME: Avoid moving the subsequent elements twice on resize. + _ensureFreeCapacity(newItemCount - subrange.count) + try _storage._uncheckedReplace( + removing: subrange, + addingCount: newItemCount, + initializingWith: initializer) } } +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Replaces the specified range of elements by a given count of new items, + /// using callbacks to consume old items, and to then insert new ones. + /// + /// The number of new items need not match the number of elements being + /// removed. + /// + /// This method has the same overall effect as calling + /// + /// try array.consume(subrange, consumingWith: consumer) + /// try array.insert( + /// addingCount: newItemCount, + /// at: subrange.lowerBound, + /// initializingWith: initializer) + /// + /// Except it performs faster (by a constant factor), by avoiding moving + /// some items in the deque twice. + /// + /// If the array does not have sufficient capacity to perform the replacement, + /// then this reallocates storage to extend its capacity, using a geometric + /// growth rate. + /// + /// The `consumer` callback is not required to fully depopulate its input + /// span. Any items the callback leaves in the span still get removed and + /// discarded from the array before insertions begin. + /// + /// The `initializer` callback is not required to fully populate its + /// output span, and it is allowed to throw an error. In such cases, the + /// deque keeps all items that were successfully initialized before the + /// callback terminated. + /// + /// Partial insertions create a gap in array storage that needs to be + /// closed by moving newly inserted items to their correct positions given + /// the adjusted count. This adds some overhead compared to adding exactly as + /// many items as promised. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - consumer: A callback that gets called at most once to consume + /// the elements to be removed directly from the deque's storage. The + /// function is always called with a non-empty input span. + /// - newItemCount: the maximum number of items to replace the old subrange. + /// - initializer: A callback that gets called at most once to directly + /// populate newly reserved storage within the deque. The function + /// is always called with an empty output span. + /// + /// - Complexity: O(`self.count` + `newItemCount`) in addition to the + /// complexity of the callback invocations. + @inlinable + public mutating func replace( + removing subrange: Range, + consumingWith consumer: (inout InputSpan) -> Void, + addingCount newItemCount: Int, + initializingWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) -> Void { + _storage._checkValidBounds(subrange) + precondition(newItemCount >= 0, "Cannot add a negative number of items") + _ensureFreeCapacity(newItemCount - subrange.count) + try _storage._uncheckedReplace( + removing: subrange, + consumingWith: consumer, + addingCount: newItemCount, + initializingWith: initializer) + } +#endif +} + @available(SwiftStdlib 5.0, *) extension UniqueArray where Element: ~Copyable { /// Replaces the specified range of elements by moving the elements of a @@ -89,7 +170,7 @@ extension UniqueArray where Element: ~Copyable { /// without replacement. Calling the `removeSubrange(_:)` method instead is /// preferred in this case. /// - /// - Parameters + /// - Parameters: /// - subrange: The subrange of the array to replace. The bounds of /// the range must be valid indices in the array. /// - newElements: A fully initialized buffer whose contents to move into @@ -97,13 +178,13 @@ extension UniqueArray where Element: ~Copyable { /// /// - Complexity: O(`self.count` + `newElements.count`) @_alwaysEmitIntoClient - public mutating func replaceSubrange( - _ subrange: Range, + public mutating func replace( + removing subrange: Range, moving newElements: UnsafeMutableBufferPointer, ) { // FIXME: Avoid moving the subsequent elements twice. _ensureFreeCapacity(newElements.count - subrange.count) - _storage.replaceSubrange(subrange, moving: newElements) + _storage.replace(removing: subrange, moving: newElements) } #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW @@ -128,20 +209,20 @@ extension UniqueArray where Element: ~Copyable { /// without replacement. Calling the `removeSubrange(_:)` method instead is /// preferred in this case. /// - /// - Parameters + /// - Parameters: /// - subrange: The subrange of the array to replace. The bounds of /// the range must be valid indices in the array. /// - items: An input span whose contents are to be moved into the array. /// /// - Complexity: O(`self.count` + `items.count`) @_alwaysEmitIntoClient - public mutating func replaceSubrange( - _ subrange: Range, + public mutating func replace( + removing subrange: Range, moving items: inout InputSpan ) { // FIXME: Avoid moving the subsequent elements twice. _ensureFreeCapacity(items.count - subrange.count) - _storage.replaceSubrange(subrange, moving: &items) + _storage.replace(removing: subrange, moving: &items) } #endif @@ -166,20 +247,20 @@ extension UniqueArray where Element: ~Copyable { /// without replacement. Calling the `removeSubrange(_:)` method instead is /// preferred in this case. /// - /// - Parameters + /// - Parameters: /// - subrange: The subrange of the array to replace. The bounds of /// the range must be valid indices in the array. /// - items: An output span whose contents are to be moved into the array. /// /// - Complexity: O(`self.count` + `items.count`) @_alwaysEmitIntoClient - public mutating func replaceSubrange( - _ subrange: Range, + public mutating func replace( + removing subrange: Range, moving items: inout OutputSpan ) { // FIXME: Avoid moving the subsequent elements twice. _ensureFreeCapacity(items.count - subrange.count) - _storage.replaceSubrange(subrange, moving: &items) + _storage.replace(removing: subrange, moving: &items) } /// Replaces the specified range of elements by moving the elements of a @@ -205,20 +286,20 @@ extension UniqueArray where Element: ~Copyable { /// without replacement. Calling the `removeSubrange(_:)` method instead is /// preferred in this case. /// - /// - Parameters + /// - Parameters: /// - subrange: The subrange of the array to replace. The bounds of /// the range must be valid indices in the array. /// - newElements: An array whose contents to move into `self`. /// /// - Complexity: O(`self.count` + `newElements.count`) @_alwaysEmitIntoClient - public mutating func replaceSubrange( - _ subrange: Range, + public mutating func replace( + removing subrange: Range, moving newElements: inout RigidArray, ) { // FIXME: Avoid moving the subsequent elements twice. _ensureFreeCapacity(newElements.count - subrange.count) - _storage.replaceSubrange(subrange, moving: &newElements) + _storage.replace(removing: subrange, moving: &newElements) } } @@ -245,18 +326,18 @@ extension UniqueArray where Element: ~Copyable { /// without replacement. Calling the `removeSubrange(_:)` method instead is /// preferred in this case. /// - /// - Parameters + /// - Parameters: /// - subrange: The subrange of the array to replace. The bounds of /// the range must be valid indices in the array. /// - newElements: An array whose contents to move into `self`. /// /// - Complexity: O(`self.count` + `newElements.count`) @_alwaysEmitIntoClient - public mutating func replaceSubrange( - _ subrange: Range, + public mutating func replace( + removing subrange: Range, consuming newElements: consuming RigidArray, ) { - replaceSubrange(subrange, moving: &newElements) + replace(removing: subrange, moving: &newElements) } } @@ -292,13 +373,13 @@ extension UniqueArray { /// *m* is the count of `newElements`. @inlinable @inline(__always) - public mutating func replaceSubrange( - _ subrange: Range, + public mutating func replace( + removing subrange: Range, copying newElements: UnsafeBufferPointer ) { // FIXME: Avoid moving the subsequent elements twice. _ensureFreeCapacity(newElements.count) - unsafe _storage.replaceSubrange(subrange, copying: newElements) + unsafe _storage.replace(removing: subrange, copying: newElements) } /// Replaces the specified subrange of elements by copying the elements of @@ -331,12 +412,13 @@ extension UniqueArray { /// *m* is the count of `newElements`. @inlinable @inline(__always) - public mutating func replaceSubrange( - _ subrange: Range, + public mutating func replace( + removing subrange: Range, copying newElements: UnsafeMutableBufferPointer ) { - unsafe self.replaceSubrange( - subrange, copying: UnsafeBufferPointer(newElements)) + unsafe self.replace( + removing: subrange, + copying: UnsafeBufferPointer(newElements)) } /// Replaces the specified subrange of elements by copying the elements of @@ -368,13 +450,13 @@ extension UniqueArray { /// - Complexity: O(*n* + *m*), where *n* is count of this array and /// *m* is the count of `newElements`. @inlinable - public mutating func replaceSubrange( - _ subrange: Range, + public mutating func replace( + removing subrange: Range, copying newElements: Span ) { // FIXME: Avoid moving the subsequent elements twice. _ensureFreeCapacity(newElements.count) - _storage.replaceSubrange(subrange, copying: newElements) + _storage.replace(removing: subrange, copying: newElements) } #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW @@ -408,17 +490,19 @@ extension UniqueArray { /// *m* is the count of `newElements`. @inlinable @inline(__always) - public mutating func replaceSubrange< + public mutating func replace< C: Container & ~Copyable & ~Escapable >( - _ subrange: Range, + removing subrange: Range, copying newElements: borrowing C ) { // FIXME: Avoid moving the subsequent elements twice. let c = newElements.count _ensureFreeCapacity(c - subrange.count) - _storage._replaceSubrange( - subrange, copyingContainer: newElements, newCount: c) + _storage._replace( + removing: subrange, + copyingContainer: newElements, + newCount: c) } #endif @@ -452,15 +536,17 @@ extension UniqueArray { /// *m* is the count of `newElements`. @inlinable @inline(__always) - public mutating func replaceSubrange( - _ subrange: Range, + public mutating func replace( + removing subrange: Range, copying newElements: __owned some Collection ) { // FIXME: Avoid moving the subsequent elements twice. let c = newElements.count _ensureFreeCapacity(c) - _storage._replaceSubrange( - subrange, copyingCollection: newElements, newCount: c) + _storage._replace( + removing: subrange, + copyingCollection: newElements, + newCount: c) } #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW @@ -503,8 +589,10 @@ extension UniqueArray { // FIXME: Avoid moving the subsequent elements twice. let c = newElements.count _ensureFreeCapacity(c - subrange.count) - _storage._replaceSubrange( - subrange, copyingContainer: newElements, newCount: c) + _storage._replace( + removing: subrange, + copyingContainer: newElements, + newCount: c) } #endif } diff --git a/Sources/BasicContainers/UniqueArray.swift b/Sources/BasicContainers/UniqueArray/UniqueArray.swift similarity index 70% rename from Sources/BasicContainers/UniqueArray.swift rename to Sources/BasicContainers/UniqueArray/UniqueArray.swift index 8bf93ab1..404c7c15 100644 --- a/Sources/BasicContainers/UniqueArray.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors +// Copyright (c) 2024 - 2026 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information @@ -37,42 +37,37 @@ public struct UniqueArray: ~Copyable { /// /// `UniqueArray` instances automatically resize their underlying storage as /// needed to accommodate newly inserted items, using a geometric growth curve. -/// This frees code using `UniqueArray` from having to allocate enough +/// This lets code using `UniqueArray` avoid having to allocate enough /// capacity in advance; on the other hand, it makes it difficult to tell /// when and where such reallocations may happen. /// -/// For example, appending an element to a dynamic array has highly variable +/// For example, appending an element to a `UniqueArray` has highly variable /// complexity; often, it runs at a constant cost, but if the operation has to /// resize storage, then the cost of an individual append suddenly becomes /// proportional to the size of the whole array. /// /// The geometric growth curve allows the cost of such latency spikes to /// get amortized across repeated invocations, bringing the average cost back -/// to O(1); but they make this construct less suitable for use cases that +/// to O(1); but the spikes make this construct less suitable for use cases that /// expect predictable, consistent performance on every operation. /// /// Implicit growth also makes it more difficult to predict/analyze the amount /// of memory an algorithm would need. Developers targeting environments with /// stringent limits on heap allocations may prefer to avoid using dynamically -/// resizing array types as a matter of policy. The type `RigidArray` provides +/// resizing container types as a matter of policy. The type `RigidArray` provides /// a fixed-capacity array variant that caters specifically for these use cases, /// trading ease-of-use for more consistent/predictable execution. +/// For copyable elements, the copy-on-write `Array` type is an +/// even more convenient and expressive choice. @available(SwiftStdlib 5.0, *) @frozen public struct UniqueArray: ~Copyable { @usableFromInline internal var _storage: RigidArray - /// Initializes a new unique array with the specified capacity and no elements. - @inlinable - public init(capacity: Int) { - _storage = .init(capacity: capacity) - } - - /// Initializes a new unique array with no elements. - @inlinable - public init() { - _storage = .init(capacity: 0) + @_alwaysEmitIntoClient + package init(_storage: consuming RigidArray) { + self._storage = _storage } } @@ -83,8 +78,10 @@ extension UniqueArray: Sendable where Element: Sendable & ~Copyable {} @available(SwiftStdlib 5.0, *) extension UniqueArray where Element: ~Copyable { - /// The maximum number of elements this array can hold without reallocating - /// its storage. + /// The maximum number of elements this array can hold without having to + /// reallocate its storage. + /// + /// - Complexity: O(1) @inlinable @inline(__always) public var capacity: Int { _assumeNonNegative(_storage.capacity) } @@ -133,7 +130,7 @@ extension UniqueArray where Element: ~Copyable { extension UniqueArray where Element: ~Copyable { /// Arbitrarily edit the storage underlying this array by invoking a /// user-supplied closure with a mutable `OutputSpan` view over it. - /// This method calls its function argument precisely once, allowing it to + /// This method calls its function argument at most once, allowing it to /// arbitrarily modify the contents of the output span it is given. /// The argument is free to add, remove or reorder any items; however, /// it is not allowed to replace the span or change its capacity. @@ -144,7 +141,7 @@ extension UniqueArray where Element: ~Copyable { /// /// - Parameter body: A function that edits the contents of this array through /// an `OutputSpan` argument. This method invokes this function - /// precisely once. + /// at most once. /// - Returns: This method returns the result of its function argument. /// - Complexity: Adds O(1) overhead to the complexity of the function /// argument. @@ -158,104 +155,6 @@ extension UniqueArray where Element: ~Copyable { //MARK: - Container primitives -@available(SwiftStdlib 5.0, *) -extension UniqueArray where Element: ~Copyable { - /// A Boolean value indicating whether this array contains no elements. - /// - /// - Complexity: O(1) - @inlinable - @inline(__always) - public var isEmpty: Bool { _storage.isEmpty } - - /// The number of elements in this array. - /// - /// - Complexity: O(1) - @inlinable - @inline(__always) - public var count: Int { _storage.count } -} - -#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW -@available(SwiftStdlib 5.0, *) -extension UniqueArray: Container where Element: ~Copyable { - public typealias BorrowIterator = RigidArray.BorrowIterator - - @_alwaysEmitIntoClient - @inline(__always) - public func startBorrowIteration() -> Span { - self._storage.startBorrowIteration() - } -} -#endif - -@available(SwiftStdlib 5.0, *) -extension UniqueArray where Element: ~Copyable { - /// A type that represents a position in the array: an integer offset from the - /// start. - /// - /// Valid indices consist of the position of every element and a "past the - /// end” position that’s not valid for use as a subscript argument. - public typealias Index = Int - - /// The position of the first element in a nonempty array. This is always zero. - /// - /// - Complexity: O(1) - @inlinable - @inline(__always) - public var startIndex: Int { _storage.startIndex } - - /// The array’s "past the end” position—that is, the position one greater than - /// the last valid subscript argument. This is always equal to array's count. - /// - /// - Complexity: O(1) - @inlinable - @inline(__always) - public var endIndex: Int { _storage.count } - - /// The range of indices that are valid for subscripting the array. - /// - /// - Complexity: O(1) - @inlinable - @inline(__always) - public var indices: Range { _storage.indices } - - /// Accesses the element at the specified position. - /// - /// - Parameter position: The position of the element to access. - /// The position must be a valid index of the array that is not equal - /// to the `endIndex` property. - /// - /// - Complexity: O(1) - @inlinable - public subscript(position: Int) -> Element { - @inline(__always) - unsafeAddress { - _storage._ptr(to: position) - } - @inline(__always) - unsafeMutableAddress { - _storage._mutablePtr(to: position) - } - } -} - -@available(SwiftStdlib 5.0, *) -extension UniqueArray where Element: ~Copyable { - /// Exchanges the values at the specified indices of the array. - /// - /// Both parameters must be valid indices of the array and not equal to - /// endIndex. Passing the same index as both `i` and `j` has no effect. - /// - /// - Parameter i: The index of the first value to swap. - /// - Parameter j: The index of the second valud to swap. - /// - /// - Complexity: O(1) - @inlinable - public mutating func swapAt(_ i: Int, _ j: Int) { - _storage.swapAt(i, j) - } -} - @available(SwiftStdlib 5.0, *) extension UniqueArray where Element: ~Copyable { /// Return a borrowing span over the maximal storage chunk following the @@ -320,7 +219,7 @@ extension UniqueArray where Element: ~Copyable { @_alwaysEmitIntoClient @_transparent -internal func _growDynamicArrayCapacity(_ capacity: Int) -> Int { +internal func _growUniqueArrayCapacity(_ capacity: Int) -> Int { // A growth factor of 1.5 seems like a reasonable compromise between // over-allocating memory and wasting cycles on repeatedly resizing storage. let c = (3 &* UInt(bitPattern: capacity) &+ 1) / 2 @@ -340,7 +239,7 @@ extension UniqueArray where Element: ~Copyable { /// greater than or equal to the current count. /// /// - Complexity: O(`count`) - @inlinable @inline(never) + @inlinable public mutating func reallocate(capacity: Int) { _storage.reallocate(capacity: capacity) } @@ -353,7 +252,7 @@ extension UniqueArray where Element: ~Copyable { /// Otherwise the array is left as is. /// /// - Complexity: O(`count`) - @inlinable @inline(never) + @inlinable public mutating func reserveCapacity(_ n: Int) { _storage.reserveCapacity(n) } @@ -370,7 +269,7 @@ extension UniqueArray where Element: ~Copyable { internal func _grow(freeCapacity: Int) -> Int { Swift.max( count + freeCapacity, - _growDynamicArrayCapacity(capacity)) + _growUniqueArrayCapacity(capacity)) } @inlinable @@ -388,12 +287,11 @@ extension UniqueArray { /// instance with just enough capacity to hold all its elements. /// /// - Complexity: O(`count`) - @inlinable - @inline(__always) - public func copy() -> Self { - UniqueArray(consuming: _storage.copy()) + @_alwaysEmitIntoClient + public func clone() -> Self { + UniqueArray(consuming: _storage.clone()) } - + /// Copy the contents of this array into a newly allocated unique array /// instance with the specified capacity. /// @@ -403,11 +301,8 @@ extension UniqueArray { /// - Complexity: O(`count`) @inlinable @inline(__always) - public func copy(capacity: Int) -> Self { - UniqueArray(consuming: _storage.copy(capacity: capacity)) + public func clone(capacity: Int) -> Self { + UniqueArray(consuming: _storage.clone(capacity: capacity)) } } - - - #endif diff --git a/Sources/BitCollections/BitArray/BinaryInteger extensions.swift b/Sources/BitCollections/BitArray/BinaryInteger extensions.swift new file mode 100644 index 00000000..57b1187c --- /dev/null +++ b/Sources/BitCollections/BitArray/BinaryInteger extensions.swift @@ -0,0 +1,216 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021 - 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +#endif + +extension BitArray { + @inlinable + package func _convert( + to type: T.Type + ) -> ( + value: T, + isNegative: Bool + ) { + var value: T = .zero + let isNegative = self._foreachTwosComplementWordDownward( + isSigned: T.isSigned + ) { _, word in + value <<= UInt.bitWidth + value |= T(truncatingIfNeeded: word) + return true + } + return (value, isNegative) + } + + @inlinable + package func _convertTruncating(to type: T.Type) -> T { + self._convert(to: T.self).value + } + + @inlinable + package func _convertExactly(to type: T.Type) -> T? { + let (value, isNegative) = self._convert(to: T.self) + guard isNegative == (value < 0) else { return nil } + let words = value.words + var equal = true + _ = self._foreachTwosComplementWordDownward(isSigned: T.isSigned) { i, word in + assert(equal) + let w = ( + i < words.count ? words[i] + : isNegative ? UInt.max + : UInt.zero) + equal = (w == word) + return equal + } + guard equal else { return nil } + return value + } + + @inlinable + package func _convertForced(to type: T.Type) -> T { + guard let value = _convertExactly(to: T.self) else { + fatalError(""" + BitArray value cannot be converted to \(Self.self) because it is \ + outside the representable range + """) + } + return value + } +} + +extension BinaryInteger { + /// Creates a new instance by truncating or extending the bits in the given + /// bit array, as needed. The bit at position 0 in `source` will correspond + /// to the least-significant bit in the result. + /// + /// If `Self` is an unsigned integer type, then the result will contain as + /// many bits from `source` it can accommodate, truncating off any extras. + /// + /// UInt8(truncatingIfNeeded: "" as BitArray) // 0 + /// UInt8(truncatingIfNeeded: "0" as BitArray) // 0 + /// UInt8(truncatingIfNeeded: "1" as BitArray) // 1 + /// UInt8(truncatingIfNeeded: "11" as BitArray) // 3 + /// UInt8(truncatingIfNeeded: "11111111" as BitArray) // 255 + /// UInt8(truncatingIfNeeded: "1100000001" as BitArray) // 1 + /// UInt8(truncatingIfNeeded: "1100000101" as BitArray) // 5 + /// + /// If `Self` is a signed integer type, then the contents of the bit array + /// are interpreted to be a two's complement representation of a signed + /// integer value, with the last bit in the array representing the sign of + /// the result. + /// + /// Int8(truncatingIfNeeded: "" as BitArray) // 0 + /// Int8(truncatingIfNeeded: "0" as BitArray) // 0 + /// Int8(truncatingIfNeeded: "1" as BitArray) // -1 + /// Int8(truncatingIfNeeded: "01" as BitArray) // 1 + /// Int8(truncatingIfNeeded: "101" as BitArray) // -3 + /// Int8(truncatingIfNeeded: "0101" as BitArray) // 5 + /// + /// Int8(truncatingIfNeeded: "00000001" as BitArray) // 1 + /// Int8(truncatingIfNeeded: "00000101" as BitArray) // 5 + /// Int8(truncatingIfNeeded: "01111111" as BitArray) // 127 + /// Int8(truncatingIfNeeded: "10000000" as BitArray) // -128 + /// Int8(truncatingIfNeeded: "11111111" as BitArray) // -1 + /// + /// Int8(truncatingIfNeeded: "000011111111" as BitArray) // -1 + /// Int8(truncatingIfNeeded: "111100000000" as BitArray) // 0 + /// Int8(truncatingIfNeeded: "111100000001" as BitArray) // 1 + @inlinable + @inline(__always) + public init(truncatingIfNeeded source: BitArray) { + self = source._convertTruncating(to: Self.self) + } + + /// Creates a new instance from the bits in the given bit array, if the + /// corresponding integer value can be represented exactly. + /// If the value is not representable exactly, then the result is `nil`. + /// + /// If `Self` is an unsigned integer type, then the contents of the bit array + /// are interpreted to be the binary representation of a nonnegative + /// integer value. The bit array is allowed to contain bits in unrepresentable + /// positions, as long as they are all cleared. + /// + /// UInt8(exactly: "" as BitArray) // 0 + /// UInt8(exactly: "0" as BitArray) // 0 + /// UInt8(exactly: "1" as BitArray) // 1 + /// UInt8(exactly: "10" as BitArray) // 2 + /// UInt8(exactly: "00000000" as BitArray) // 0 + /// UInt8(exactly: "11111111" as BitArray) // 255 + /// UInt8(exactly: "0000000000000" as BitArray) // 0 + /// UInt8(exactly: "0000011111111" as BitArray) // 255 + /// UInt8(exactly: "0000100000000" as BitArray) // nil + /// UInt8(exactly: "1111111111111" as BitArray) // nil + /// + /// If `Self` is a signed integer type, then the contents of the bit array + /// are interpreted to be a two's complement representation of a signed + /// integer value, with the last bit in the array representing the sign of + /// the result. + /// + /// Int8(exactly: "" as BitArray) // 0 + /// Int8(exactly: "0" as BitArray) // 0 + /// Int8(exactly: "1" as BitArray) // -1 + /// Int8(exactly: "01" as BitArray) // 1 + /// Int8(exactly: "101" as BitArray) // -3 + /// Int8(exactly: "0101" as BitArray) // 5 + /// + /// Int8(exactly: "00000001" as BitArray) // 1 + /// Int8(exactly: "00000101" as BitArray) // 5 + /// Int8(exactly: "01111111" as BitArray) // 127 + /// Int8(exactly: "10000000" as BitArray) // -128 + /// Int8(exactly: "11111111" as BitArray) // -1 + /// + /// Int8(exactly: "00000000000" as BitArray) // 0 + /// Int8(exactly: "00001111111" as BitArray) // 127 + /// Int8(exactly: "00010000000" as BitArray) // nil + /// Int8(exactly: "11101111111" as BitArray) // nil + /// Int8(exactly: "11110000000" as BitArray) // -128 + /// Int8(exactly: "11111111111" as BitArray) // -1 + @inlinable + @inline(__always) + public init?(exactly source: BitArray) { + guard let v = source._convertExactly(to: Self.self) else { return nil } + self = v + } + + /// Creates a new instance from the bits in the given bit array, if the + /// corresponding integer value can be represented exactly. + /// If the value is not representable exactly, then a runtime error will + /// occur. + /// + /// If `Self` is an unsigned integer type, then the contents of the bit array + /// are interpreted to be the binary representation of a nonnegative + /// integer value. The bit array is allowed to contain bits in unrepresentable + /// positions, as long as they are all cleared. + /// + /// UInt8("" as BitArray) // 0 + /// UInt8("0" as BitArray) // 0 + /// UInt8("1" as BitArray) // 1 + /// UInt8("10" as BitArray) // 2 + /// UInt8("00000000" as BitArray) // 0 + /// UInt8("11111111" as BitArray) // 255 + /// UInt8("0000000000000" as BitArray) // 0 + /// UInt8("0000011111111" as BitArray) // 255 + /// UInt8("0000100000000" as BitArray) // ERROR + /// UInt8("1111111111111" as BitArray) // ERROR + /// + /// If `Self` is a signed integer type, then the contents of the bit array + /// are interpreted to be a two's complement representation of a signed + /// integer value, with the last bit in the array representing the sign of + /// the result. + /// + /// Int8("" as BitArray) // 0 + /// Int8("0" as BitArray) // 0 + /// Int8("1" as BitArray) // -1 + /// Int8("01" as BitArray) // 1 + /// Int8("101" as BitArray) // -3 + /// Int8("0101" as BitArray) // 5 + /// + /// Int8("00000001" as BitArray) // 1 + /// Int8("00000101" as BitArray) // 5 + /// Int8("01111111" as BitArray) // 127 + /// Int8("10000000" as BitArray) // -128 + /// Int8("11111111" as BitArray) // -1 + /// + /// Int8("00000000000" as BitArray) // 0 + /// Int8("00001111111" as BitArray) // 127 + /// Int8("00010000000" as BitArray) // ERROR + /// Int8("11101111111" as BitArray) // ERROR + /// Int8("11110000000" as BitArray) // -128 + /// Int8("11111111111" as BitArray) // -1 + @inlinable + @inline(__always) + public init(_ source: BitArray) { + self = source._convertForced(to: Self.self) + } +} + diff --git a/Sources/BitCollections/BitArray/BitArray+Extras.swift b/Sources/BitCollections/BitArray/BitArray+Extras.swift index 6a41c875..a96b94e6 100644 --- a/Sources/BitCollections/BitArray/BitArray+Extras.swift +++ b/Sources/BitCollections/BitArray/BitArray+Extras.swift @@ -20,7 +20,7 @@ extension BitArray { toCount count: Int, with padding: Bool = false ) { - precondition(count >= 0, "Negative count") + precondition(count >= 0, "Cannot set a negative count") if count < _count { _removeLast(self.count - count) } else if count > _count { @@ -35,7 +35,7 @@ extension BitArray { count: Int, at index: Int ) { - precondition(count >= 0, "Can't insert a negative number of values") + precondition(count >= 0, "Cannot add a negative number of items") precondition(index >= 0 && index <= count, "Index out of bounds") guard count > 0 else { return } _extend(by: count, with: false) @@ -44,7 +44,7 @@ extension BitArray { } public mutating func append(repeating value: Bool, count: Int) { - precondition(count >= 0, "Can't append a negative number of values") + precondition(count >= 0, "Cannot add a negative number of items") guard count > 0 else { return } _extend(by: count, with: value) } diff --git a/Sources/BitCollections/BitArray/BitArray+Initializers.swift b/Sources/BitCollections/BitArray/BitArray+Initializers.swift index d2ec9c8d..c8870d79 100644 --- a/Sources/BitCollections/BitArray/BitArray+Initializers.swift +++ b/Sources/BitCollections/BitArray/BitArray+Initializers.swift @@ -67,183 +67,6 @@ extension BitArray { } } -extension BinaryInteger { - @inlinable - internal static func _convert( - _ source: BitArray - ) -> (value: Self, isNegative: Bool) { - var value: Self = .zero - let isNegative = source._foreachTwosComplementWordDownward( - isSigned: Self.isSigned - ) { _, word in - value <<= UInt.bitWidth - value |= Self(truncatingIfNeeded: word) - return true - } - return (value, isNegative) - } - - /// Creates a new instance by truncating or extending the bits in the given - /// bit array, as needed. The bit at position 0 in `source` will correspond - /// to the least-significant bit in the result. - /// - /// If `Self` is an unsigned integer type, then the result will contain as - /// many bits from `source` it can accommodate, truncating off any extras. - /// - /// UInt8(truncatingIfNeeded: "" as BitArray) // 0 - /// UInt8(truncatingIfNeeded: "0" as BitArray) // 0 - /// UInt8(truncatingIfNeeded: "1" as BitArray) // 1 - /// UInt8(truncatingIfNeeded: "11" as BitArray) // 3 - /// UInt8(truncatingIfNeeded: "11111111" as BitArray) // 255 - /// UInt8(truncatingIfNeeded: "1100000001" as BitArray) // 1 - /// UInt8(truncatingIfNeeded: "1100000101" as BitArray) // 5 - /// - /// If `Self` is a signed integer type, then the contents of the bit array - /// are interpreted to be a two's complement representation of a signed - /// integer value, with the last bit in the array representing the sign of - /// the result. - /// - /// Int8(truncatingIfNeeded: "" as BitArray) // 0 - /// Int8(truncatingIfNeeded: "0" as BitArray) // 0 - /// Int8(truncatingIfNeeded: "1" as BitArray) // -1 - /// Int8(truncatingIfNeeded: "01" as BitArray) // 1 - /// Int8(truncatingIfNeeded: "101" as BitArray) // -3 - /// Int8(truncatingIfNeeded: "0101" as BitArray) // 5 - /// - /// Int8(truncatingIfNeeded: "00000001" as BitArray) // 1 - /// Int8(truncatingIfNeeded: "00000101" as BitArray) // 5 - /// Int8(truncatingIfNeeded: "01111111" as BitArray) // 127 - /// Int8(truncatingIfNeeded: "10000000" as BitArray) // -128 - /// Int8(truncatingIfNeeded: "11111111" as BitArray) // -1 - /// - /// Int8(truncatingIfNeeded: "000011111111" as BitArray) // -1 - /// Int8(truncatingIfNeeded: "111100000000" as BitArray) // 0 - /// Int8(truncatingIfNeeded: "111100000001" as BitArray) // 1 - @inlinable - public init(truncatingIfNeeded source: BitArray) { - self = Self._convert(source).value - } - - /// Creates a new instance from the bits in the given bit array, if the - /// corresponding integer value can be represented exactly. - /// If the value is not representable exactly, then the result is `nil`. - /// - /// If `Self` is an unsigned integer type, then the contents of the bit array - /// are interpreted to be the binary representation of a nonnegative - /// integer value. The bit array is allowed to contain bits in unrepresentable - /// positions, as long as they are all cleared. - /// - /// UInt8(exactly: "" as BitArray) // 0 - /// UInt8(exactly: "0" as BitArray) // 0 - /// UInt8(exactly: "1" as BitArray) // 1 - /// UInt8(exactly: "10" as BitArray) // 2 - /// UInt8(exactly: "00000000" as BitArray) // 0 - /// UInt8(exactly: "11111111" as BitArray) // 255 - /// UInt8(exactly: "0000000000000" as BitArray) // 0 - /// UInt8(exactly: "0000011111111" as BitArray) // 255 - /// UInt8(exactly: "0000100000000" as BitArray) // nil - /// UInt8(exactly: "1111111111111" as BitArray) // nil - /// - /// If `Self` is a signed integer type, then the contents of the bit array - /// are interpreted to be a two's complement representation of a signed - /// integer value, with the last bit in the array representing the sign of - /// the result. - /// - /// Int8(exactly: "" as BitArray) // 0 - /// Int8(exactly: "0" as BitArray) // 0 - /// Int8(exactly: "1" as BitArray) // -1 - /// Int8(exactly: "01" as BitArray) // 1 - /// Int8(exactly: "101" as BitArray) // -3 - /// Int8(exactly: "0101" as BitArray) // 5 - /// - /// Int8(exactly: "00000001" as BitArray) // 1 - /// Int8(exactly: "00000101" as BitArray) // 5 - /// Int8(exactly: "01111111" as BitArray) // 127 - /// Int8(exactly: "10000000" as BitArray) // -128 - /// Int8(exactly: "11111111" as BitArray) // -1 - /// - /// Int8(exactly: "00000000000" as BitArray) // 0 - /// Int8(exactly: "00001111111" as BitArray) // 127 - /// Int8(exactly: "00010000000" as BitArray) // nil - /// Int8(exactly: "11101111111" as BitArray) // nil - /// Int8(exactly: "11110000000" as BitArray) // -128 - /// Int8(exactly: "11111111111" as BitArray) // -1 - @inlinable - public init?(exactly source: BitArray) { - let (value, isNegative) = Self._convert(source) - guard isNegative == (value < 0) else { return nil } - let words = value.words - var equal = true - _ = source._foreachTwosComplementWordDownward(isSigned: Self.isSigned) { i, word in - assert(equal) - let w = ( - i < words.count ? words[i] - : isNegative ? UInt.max - : UInt.zero) - equal = (w == word) - return equal - } - guard equal else { return nil } - self = value - } - - /// Creates a new instance from the bits in the given bit array, if the - /// corresponding integer value can be represented exactly. - /// If the value is not representable exactly, then a runtime error will - /// occur. - /// - /// If `Self` is an unsigned integer type, then the contents of the bit array - /// are interpreted to be the binary representation of a nonnegative - /// integer value. The bit array is allowed to contain bits in unrepresentable - /// positions, as long as they are all cleared. - /// - /// UInt8("" as BitArray) // 0 - /// UInt8("0" as BitArray) // 0 - /// UInt8("1" as BitArray) // 1 - /// UInt8("10" as BitArray) // 2 - /// UInt8("00000000" as BitArray) // 0 - /// UInt8("11111111" as BitArray) // 255 - /// UInt8("0000000000000" as BitArray) // 0 - /// UInt8("0000011111111" as BitArray) // 255 - /// UInt8("0000100000000" as BitArray) // ERROR - /// UInt8("1111111111111" as BitArray) // ERROR - /// - /// If `Self` is a signed integer type, then the contents of the bit array - /// are interpreted to be a two's complement representation of a signed - /// integer value, with the last bit in the array representing the sign of - /// the result. - /// - /// Int8("" as BitArray) // 0 - /// Int8("0" as BitArray) // 0 - /// Int8("1" as BitArray) // -1 - /// Int8("01" as BitArray) // 1 - /// Int8("101" as BitArray) // -3 - /// Int8("0101" as BitArray) // 5 - /// - /// Int8("00000001" as BitArray) // 1 - /// Int8("00000101" as BitArray) // 5 - /// Int8("01111111" as BitArray) // 127 - /// Int8("10000000" as BitArray) // -128 - /// Int8("11111111" as BitArray) // -1 - /// - /// Int8("00000000000" as BitArray) // 0 - /// Int8("00001111111" as BitArray) // 127 - /// Int8("00010000000" as BitArray) // ERROR - /// Int8("11101111111" as BitArray) // ERROR - /// Int8("11110000000" as BitArray) // -128 - /// Int8("11111111111" as BitArray) // -1 - @inlinable - public init(_ source: BitArray) { - guard let value = Self(exactly: source) else { - fatalError(""" - BitArray value cannot be converted to \(Self.self) because it is \ - outside the representable range - """) - } - self = value - } -} - extension BitArray { @usableFromInline internal func _foreachTwosComplementWordDownward( diff --git a/Sources/BitCollections/BitSet/BitSet+Extras.swift b/Sources/BitCollections/BitSet/BitSet+Extras.swift index 15b8a391..b4fcf3d5 100644 --- a/Sources/BitCollections/BitSet/BitSet+Extras.swift +++ b/Sources/BitCollections/BitSet/BitSet+Extras.swift @@ -66,7 +66,7 @@ extension BitSet { } set { guard let member = UInt(exactly: member) else { - precondition(!newValue, "Can't insert a negative value to a BitSet") + precondition(!newValue, "Cannot insert a negative value to a BitSet") return } if newValue { diff --git a/Sources/BitCollections/CMakeLists.txt b/Sources/BitCollections/CMakeLists.txt index 9ca7a2d4..39523e27 100644 --- a/Sources/BitCollections/CMakeLists.txt +++ b/Sources/BitCollections/CMakeLists.txt @@ -1,7 +1,7 @@ #[[ This source file is part of the Swift Collections Open Source Project -Copyright (c) 2022 - 2024 Apple Inc. and the Swift project authors +Copyright (c) 2022 - 2026 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See https://swift.org/LICENSE.txt for license information @@ -23,6 +23,7 @@ else() endif() target_sources(${module_name} PRIVATE + "BitArray/BinaryInteger extensions.swift" "BitArray/BitArray+BitwiseOperations.swift" "BitArray/BitArray+ChunkedBitsIterators.swift" "BitArray/BitArray+Codable.swift" diff --git a/Sources/Collections/BitCollections reexports.swift b/Sources/Collections/BitCollections reexports.swift new file mode 100644 index 00000000..ce1a1641 --- /dev/null +++ b/Sources/Collections/BitCollections reexports.swift @@ -0,0 +1,164 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021 - 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import BitCollections + +public typealias BitSet = BitCollections.BitSet +public typealias BitArray = BitCollections.BitArray + +extension BinaryInteger { + /// Creates a new instance by truncating or extending the bits in the given + /// bit array, as needed. The bit at position 0 in `source` will correspond + /// to the least-significant bit in the result. + /// + /// If `Self` is an unsigned integer type, then the result will contain as + /// many bits from `source` it can accommodate, truncating off any extras. + /// + /// UInt8(truncatingIfNeeded: "" as BitArray) // 0 + /// UInt8(truncatingIfNeeded: "0" as BitArray) // 0 + /// UInt8(truncatingIfNeeded: "1" as BitArray) // 1 + /// UInt8(truncatingIfNeeded: "11" as BitArray) // 3 + /// UInt8(truncatingIfNeeded: "11111111" as BitArray) // 255 + /// UInt8(truncatingIfNeeded: "1100000001" as BitArray) // 1 + /// UInt8(truncatingIfNeeded: "1100000101" as BitArray) // 5 + /// + /// If `Self` is a signed integer type, then the contents of the bit array + /// are interpreted to be a two's complement representation of a signed + /// integer value, with the last bit in the array representing the sign of + /// the result. + /// + /// Int8(truncatingIfNeeded: "" as BitArray) // 0 + /// Int8(truncatingIfNeeded: "0" as BitArray) // 0 + /// Int8(truncatingIfNeeded: "1" as BitArray) // -1 + /// Int8(truncatingIfNeeded: "01" as BitArray) // 1 + /// Int8(truncatingIfNeeded: "101" as BitArray) // -3 + /// Int8(truncatingIfNeeded: "0101" as BitArray) // 5 + /// + /// Int8(truncatingIfNeeded: "00000001" as BitArray) // 1 + /// Int8(truncatingIfNeeded: "00000101" as BitArray) // 5 + /// Int8(truncatingIfNeeded: "01111111" as BitArray) // 127 + /// Int8(truncatingIfNeeded: "10000000" as BitArray) // -128 + /// Int8(truncatingIfNeeded: "11111111" as BitArray) // -1 + /// + /// Int8(truncatingIfNeeded: "000011111111" as BitArray) // -1 + /// Int8(truncatingIfNeeded: "111100000000" as BitArray) // 0 + /// Int8(truncatingIfNeeded: "111100000001" as BitArray) // 1 + @inlinable + @inline(__always) + public init(truncatingIfNeeded source: BitArray) { + self = source._convertTruncating(to: Self.self) + } + + /// Creates a new instance from the bits in the given bit array, if the + /// corresponding integer value can be represented exactly. + /// If the value is not representable exactly, then the result is `nil`. + /// + /// If `Self` is an unsigned integer type, then the contents of the bit array + /// are interpreted to be the binary representation of a nonnegative + /// integer value. The bit array is allowed to contain bits in unrepresentable + /// positions, as long as they are all cleared. + /// + /// UInt8(exactly: "" as BitArray) // 0 + /// UInt8(exactly: "0" as BitArray) // 0 + /// UInt8(exactly: "1" as BitArray) // 1 + /// UInt8(exactly: "10" as BitArray) // 2 + /// UInt8(exactly: "00000000" as BitArray) // 0 + /// UInt8(exactly: "11111111" as BitArray) // 255 + /// UInt8(exactly: "0000000000000" as BitArray) // 0 + /// UInt8(exactly: "0000011111111" as BitArray) // 255 + /// UInt8(exactly: "0000100000000" as BitArray) // nil + /// UInt8(exactly: "1111111111111" as BitArray) // nil + /// + /// If `Self` is a signed integer type, then the contents of the bit array + /// are interpreted to be a two's complement representation of a signed + /// integer value, with the last bit in the array representing the sign of + /// the result. + /// + /// Int8(exactly: "" as BitArray) // 0 + /// Int8(exactly: "0" as BitArray) // 0 + /// Int8(exactly: "1" as BitArray) // -1 + /// Int8(exactly: "01" as BitArray) // 1 + /// Int8(exactly: "101" as BitArray) // -3 + /// Int8(exactly: "0101" as BitArray) // 5 + /// + /// Int8(exactly: "00000001" as BitArray) // 1 + /// Int8(exactly: "00000101" as BitArray) // 5 + /// Int8(exactly: "01111111" as BitArray) // 127 + /// Int8(exactly: "10000000" as BitArray) // -128 + /// Int8(exactly: "11111111" as BitArray) // -1 + /// + /// Int8(exactly: "00000000000" as BitArray) // 0 + /// Int8(exactly: "00001111111" as BitArray) // 127 + /// Int8(exactly: "00010000000" as BitArray) // nil + /// Int8(exactly: "11101111111" as BitArray) // nil + /// Int8(exactly: "11110000000" as BitArray) // -128 + /// Int8(exactly: "11111111111" as BitArray) // -1 + @inlinable + @inline(__always) + public init?(exactly source: BitArray) { + guard let v = source._convertExactly(to: Self.self) else { return nil } + self = v + } + + /// Creates a new instance from the bits in the given bit array, if the + /// corresponding integer value can be represented exactly. + /// If the value is not representable exactly, then a runtime error will + /// occur. + /// + /// If `Self` is an unsigned integer type, then the contents of the bit array + /// are interpreted to be the binary representation of a nonnegative + /// integer value. The bit array is allowed to contain bits in unrepresentable + /// positions, as long as they are all cleared. + /// + /// UInt8("" as BitArray) // 0 + /// UInt8("0" as BitArray) // 0 + /// UInt8("1" as BitArray) // 1 + /// UInt8("10" as BitArray) // 2 + /// UInt8("00000000" as BitArray) // 0 + /// UInt8("11111111" as BitArray) // 255 + /// UInt8("0000000000000" as BitArray) // 0 + /// UInt8("0000011111111" as BitArray) // 255 + /// UInt8("0000100000000" as BitArray) // ERROR + /// UInt8("1111111111111" as BitArray) // ERROR + /// + /// If `Self` is a signed integer type, then the contents of the bit array + /// are interpreted to be a two's complement representation of a signed + /// integer value, with the last bit in the array representing the sign of + /// the result. + /// + /// Int8("" as BitArray) // 0 + /// Int8("0" as BitArray) // 0 + /// Int8("1" as BitArray) // -1 + /// Int8("01" as BitArray) // 1 + /// Int8("101" as BitArray) // -3 + /// Int8("0101" as BitArray) // 5 + /// + /// Int8("00000001" as BitArray) // 1 + /// Int8("00000101" as BitArray) // 5 + /// Int8("01111111" as BitArray) // 127 + /// Int8("10000000" as BitArray) // -128 + /// Int8("11111111" as BitArray) // -1 + /// + /// Int8("00000000000" as BitArray) // 0 + /// Int8("00001111111" as BitArray) // 127 + /// Int8("00010000000" as BitArray) // ERROR + /// Int8("11101111111" as BitArray) // ERROR + /// Int8("11110000000" as BitArray) // -128 + /// Int8("11111111111" as BitArray) // -1 + @inlinable + @inline(__always) + public init(_ source: BitArray) { + self = source._convertForced(to: Self.self) + } +} + +#endif diff --git a/Sources/Collections/CMakeLists.txt b/Sources/Collections/CMakeLists.txt index 9f534a46..d49d7584 100644 --- a/Sources/Collections/CMakeLists.txt +++ b/Sources/Collections/CMakeLists.txt @@ -1,20 +1,24 @@ #[[ This source file is part of the Swift Collections Open Source Project -Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors +Copyright (c) 2021 - 2026 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See https://swift.org/LICENSE.txt for license information #]] add_library(Collections - "Collections.swift") + "BitCollections reexports.swift" + "DequeModule reexports.swift" + "HashTreeCollections reexports.swift" + "HeapModule reexports.swift" + "OrderedCollections reexports.swift") target_link_libraries(Collections PRIVATE BitCollections DequeModule + HashTreeCollections HeapModule OrderedCollections - HashTreeCollections ) set_target_properties(Collections PROPERTIES INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY}) diff --git a/Sources/Collections/Collections.swift b/Sources/Collections/DequeModule reexports.swift similarity index 53% rename from Sources/Collections/Collections.swift rename to Sources/Collections/DequeModule reexports.swift index 33d5c8a1..6aad0586 100644 --- a/Sources/Collections/Collections.swift +++ b/Sources/Collections/DequeModule reexports.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors +// Copyright (c) 2021 - 2026 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information @@ -10,11 +10,7 @@ //===----------------------------------------------------------------------===// #if !COLLECTIONS_SINGLE_MODULE -@_exported import BitCollections -@_exported import DequeModule -@_exported import HashTreeCollections -@_exported import HeapModule -@_exported import OrderedCollections -// Note: _RopeModule is very intentionally not reexported, as its contents -// aren't part of this package's stable API surface (yet). +import DequeModule + +public typealias Deque = DequeModule.Deque #endif diff --git a/Sources/Collections/HashTreeCollections reexports.swift b/Sources/Collections/HashTreeCollections reexports.swift new file mode 100644 index 00000000..e83a2589 --- /dev/null +++ b/Sources/Collections/HashTreeCollections reexports.swift @@ -0,0 +1,17 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021 - 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import HashTreeCollections + +public typealias TreeSet = HashTreeCollections.TreeSet +public typealias TreeDictionary = HashTreeCollections.TreeDictionary +#endif diff --git a/Sources/Collections/HeapModule reexports.swift b/Sources/Collections/HeapModule reexports.swift new file mode 100644 index 00000000..a99ce48f --- /dev/null +++ b/Sources/Collections/HeapModule reexports.swift @@ -0,0 +1,16 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021 - 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import HeapModule + +public typealias Heap = HeapModule.Heap +#endif diff --git a/Sources/Collections/OrderedCollections reexports.swift b/Sources/Collections/OrderedCollections reexports.swift new file mode 100644 index 00000000..f64b9927 --- /dev/null +++ b/Sources/Collections/OrderedCollections reexports.swift @@ -0,0 +1,17 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021 - 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import OrderedCollections + +public typealias OrderedSet = OrderedCollections.OrderedSet +public typealias OrderedDictionary = OrderedCollections.OrderedDictionary +#endif diff --git a/Sources/ContainersPreview/BorrowIteratorProtocol.swift b/Sources/ContainersPreview/BorrowIteratorProtocol.swift deleted file mode 100644 index f3452512..00000000 --- a/Sources/ContainersPreview/BorrowIteratorProtocol.swift +++ /dev/null @@ -1,105 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift Collections open source project -// -// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// -//===----------------------------------------------------------------------===// - -#if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW -@available(SwiftStdlib 5.0, *) -public protocol BorrowIteratorProtocol: ~Copyable, ~Escapable { - associatedtype Element: ~Copyable /*& ~Escapable*/ - - /// Advance the iterator to the next storage chunk, returning a span over it. - /// - /// If the iterator has not yet reached the end of the underlying container, - /// then this method returns a non-empty span over the container's storage - /// that begins with the element at the iterator's current position and - /// extends to the end of the contiguous storage chunk that contains that - /// item, but at most `maximumCount` items. On return, the iterator's current - /// position is updated to the slot following the last item in the returned - /// span. - /// - /// If the iterator's current position is at the end of the container, then - /// this method returns an empty span without updating the position. - /// - /// This method can be used to efficiently process the items of a container - /// in bulk, by directly iterating over its piecewise contiguous pieces of - /// storage: - /// - /// var it = items.startBorrowIteration() - /// while true { - /// let span = it.nextSpan(after: &index) - /// if span.isEmpty { break } - /// // Process items in `span` - /// } - /// - /// Note: The spans returned by this method are not guaranteed to be disjunct. - /// Some containers may use the same storage chunk (or parts of a storage - /// chunk) multiple times, for example to repeat their contents. - /// - /// Note: Repeatedly iterating over the same container is expected to return - /// the same items (collected in similarly sized span instances), but the - /// returned spans are not guaranteed to be identical. (For example, this is - /// the case with containers that can store contents within their direct - /// representation. Such containers may not always have a unique address in - /// memory, and so the locations of the spans exposed by this method may vary - /// between different borrows of the same container.) - /// - /// - Parameter maximumCount: The maximum count of items the caller is ready - /// to process, or nil if the caller is prepared to accept an arbitrarily - /// large span. If non-nil, the maximum must be greater than zero. - /// - Returns: A span over a piece of contiguous storage in the underlying - /// container. It the iterator is at the end of the container, then - /// this returns an empty span. Otherwise the result will contain at least - /// one element. - @_lifetime(copy self) - @_lifetime(self: copy self) - mutating func nextSpan(maximumCount: Int?) -> Span - - @_lifetime(self: copy self) - mutating func skip(by offset: Int) -> Int -} - -@available(SwiftStdlib 5.0, *) -extension BorrowIteratorProtocol where Self: ~Copyable & ~Escapable { - @_lifetime(self: copy self) - @inlinable - public mutating func skip(by offset: Int) -> Int { - var remainder = offset - while remainder > 0 { - let span = nextSpan(maximumCount: remainder) - if span.isEmpty { break } - remainder &-= span.count - } - return offset &- remainder - } -} - -@available(SwiftStdlib 5.0, *) -extension BorrowIteratorProtocol where Self: ~Copyable & ~Escapable { - @_lifetime(copy self) - @_lifetime(self: copy self) - @_transparent - public mutating func nextSpan() -> Span { - nextSpan(maximumCount: nil) - } -} - -@available(SwiftStdlib 5.0, *) -extension Span: BorrowIteratorProtocol where Element: ~Copyable { - @_lifetime(copy self) - @_lifetime(self: copy self) - public mutating func nextSpan(maximumCount: Int?) -> Span { - let c = maximumCount ?? self.count - let result = self.extracting(first: c) - self = self.extracting(droppingFirst: c) - return result - } -} - -#endif diff --git a/Sources/ContainersPreview/CMakeLists.txt b/Sources/ContainersPreview/CMakeLists.txt index d24327e6..2dedb02a 100644 --- a/Sources/ContainersPreview/CMakeLists.txt +++ b/Sources/ContainersPreview/CMakeLists.txt @@ -23,12 +23,19 @@ else() endif() target_sources(${module_name} PRIVATE - "BorrowIteratorProtocol.swift" - "Box.swift" - "Container.swift" - "Container+Utilities.swift" - "InputSpan.swift" - "Mut.swift" - "Ref.swift" - "Shared.swift" + "Extensions/OutputSpan+Extras.swift" + "Extensions/TemporaryAllocation.swift" + "Protocols/BorrowingIteratorProtocol.swift" + "Protocols/BorrowingSequence.swift" + "Protocols/BorrowingSequence+Standard Conformances.swift" + "Protocols/BorrowingSequence+Utilities.swift" + "Protocols/Container.swift" + "Protocols/ContainerAlgorithms.swift" + "Protocols/Drain.swift" + "Protocols/Producer.swift" + "Types/Borrow.swift" + "Types/Box.swift" + "Types/Inout.swift" + "Types/InputSpan.swift" + "Types/Shared.swift" ) diff --git a/Sources/ContainersPreview/Container+Utilities.swift b/Sources/ContainersPreview/Container+Utilities.swift deleted file mode 100644 index 407594ad..00000000 --- a/Sources/ContainersPreview/Container+Utilities.swift +++ /dev/null @@ -1,135 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift Collections open source project -// -// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// -//===----------------------------------------------------------------------===// - -#if !COLLECTIONS_SINGLE_MODULE -import InternalCollectionsUtilities -#endif - -#if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW - -@available(SwiftStdlib 5.0, *) -extension Container where Self: ~Copyable & ~Escapable, Element: Copyable { - @inlinable - package func _copyContents( - intoPrefixOf buffer: UnsafeMutableBufferPointer - ) -> Int { - var target = buffer - var it = self.startBorrowIteration() - while target.count != 0 { - let span = it.nextSpan(maximumCount: target.count) - if span.isEmpty { - return buffer.count - target.count - } - target._initializeAndDropPrefix(copying: span) - } - let test = it.nextSpan() - precondition(test.isEmpty, "Contents do not fit in target buffer") - return buffer.count - } -} - -@available(SwiftStdlib 5.0, *) -extension Container where Self: ~Copyable & ~Escapable { - @inlinable - @discardableResult - internal func _spanwiseZip< - Other: Container & ~Copyable & ~Escapable, - State: ~Copyable, E: Error - >( - state: inout State, - with other: borrowing Other, - by process: (inout State, Span, Span) throws(E) -> Bool - ) throws(E) -> Int { - var it1 = self.startBorrowIteration() - var it2 = other.startBorrowIteration() - var a = it1.nextSpan() - var b = it2.nextSpan() - var offset = 0 // Offset of the start of the current spans - loop: - while true { - if a.isEmpty { - a = it1.nextSpan() - } - if b.isEmpty { - b = it2.nextSpan() - } - if a.isEmpty || b.isEmpty { - return offset - } - - let c = Swift.min(a.count, b.count) - guard try process(&state, a.extracting(first: c), b.extracting(first: c)) else { - return offset - } - a = a.extracting(droppingFirst: c) - b = b.extracting(droppingFirst: c) - offset += c - } - } - - /// Returns a Boolean value indicating whether this container and another - /// container contain equivalent elements in the same order, using the given - /// predicate as the equivalence test. - /// - /// The predicate must form an *equivalence relation* over the elements. That - /// is, for any elements `a`, `b`, and `c`, the following conditions must - /// hold: - /// - /// - `areEquivalent(a, a)` is always `true`. (Reflexivity) - /// - `areEquivalent(a, b)` implies `areEquivalent(b, a)`. (Symmetry) - /// - If `areEquivalent(a, b)` and `areEquivalent(b, c)` are both `true`, then - /// `areEquivalent(a, c)` is also `true`. (Transitivity) - /// - /// - Parameters: - /// - other: A container to compare to this container. - /// - areEquivalent: A predicate that returns `true` if its two arguments - /// are equivalent; otherwise, `false`. - /// - Returns: `true` if this container and `other` contain equivalent items, - /// using `areEquivalent` as the equivalence test; otherwise, `false.` - /// - /// - Complexity: O(*m*), where *m* is the count of the longer of the input containers. - @inlinable - public func borrowingElementsEqual< - E: Error, - Other: Container & ~Copyable & ~Escapable - >( - _ other: borrowing Other, - by areEquivalent: (borrowing Element, borrowing Other.Element) throws(E) -> Bool - ) throws(E) -> Bool { - guard self.count == other.count else { return false } - var result = true - try _spanwiseZip(state: &result, with: other) { state, a, b throws(E) in - assert(a.count == b.count) - for i in a.indices { - guard try areEquivalent(a[i], b[i]) else { - state = false - return false - } - } - return true - } - return result - } -} - -@available(SwiftStdlib 5.0, *) -extension Container where Self: ~Copyable & ~Escapable, Element: Equatable { - @inlinable - public func borrowingElementsEqual< - Other: Container & ~Copyable & ~Escapable - >( - _ other: borrowing Other, - ) -> Bool { - self.borrowingElementsEqual(other, by: ==) - } -} - -#endif diff --git a/Sources/ContainersPreview/Extensions/OutputSpan+Extras.swift b/Sources/ContainersPreview/Extensions/OutputSpan+Extras.swift new file mode 100644 index 00000000..77318a9c --- /dev/null +++ b/Sources/ContainersPreview/Extensions/OutputSpan+Extras.swift @@ -0,0 +1,129 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2024 - 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.2) + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +#endif + +@available(SwiftStdlib 5.0, *) +@_alwaysEmitIntoClient +package func withTemporaryOutputSpan( + of type: Element.Type, + capacity: Int, + _ body: (inout OutputSpan) throws(E) -> R +) throws(E) -> R { + try _withUnsafeTemporaryAllocation( + of: Element.self, capacity: capacity + ) { buffer throws(E) in + var span = OutputSpan(buffer: buffer, initializedCount: 0) + return try body(&span) + } +} + +@available(SwiftStdlib 5.0, *) +extension OutputSpan where Element: ~Copyable { + /// Removes and returns the last element of this output span, if it exists. + /// + /// - Returns: The last element of the original span if it wasn't empty; + /// otherwise, `nil`. + /// + /// - Complexity: O(1) + @inlinable + package mutating func _popLast() -> Element? { + // FIXME: This needs to be in the stdlib. + withUnsafeMutableBufferPointer { buffer, count in + guard count > 0 else { return nil } + count &-= 1 + return buffer.moveElement(from: count) + } + } +} + +@available(SwiftStdlib 5.0, *) +extension OutputSpan where Element: ~Copyable { + @inlinable + @inline(__always) + @_lifetime(self: copy self) + package mutating func _append( + moving source: UnsafeMutableBufferPointer + ) { + // FIXME: This needs to be in the stdlib. + guard source.count > 0 else { return } + self.withUnsafeMutableBufferPointer { dst, dstCount in + let dstEnd = dstCount + source.count + precondition(dstEnd <= dst.count, "OutputSpan capacity overflow") + dst + ._extracting(uncheckedFrom: dstCount, to: dstEnd) + .moveInitializeAll(fromContentsOf: source) + dstCount &+= source.count + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @_lifetime(source: copy source) + @inlinable + @inline(__always) + @_lifetime(self: copy self) + package mutating func _append(moving source: inout InputSpan) { + // FIXME: This needs to be in the stdlib. + source.withUnsafeMutableBufferPointer { src, srcCount in + let srcItems = src._extracting( + uncheckedFrom: src.count &- srcCount, + to: src.count) + self._append(moving: srcItems) + srcCount = 0 + } + } +#endif + + @_lifetime(source: copy source) + @inlinable + @inline(__always) + @_lifetime(self: copy self) + package mutating func _append(moving source: inout OutputSpan) { + // FIXME: This needs to be in the stdlib. + source.withUnsafeMutableBufferPointer { src, srcCount in + let items = src._extracting(uncheckedFrom: 0, to: srcCount) + self._append(moving: items) + srcCount = 0 + } + } +} + +@available(SwiftStdlib 5.0, *) +extension OutputSpan /*where Element: Copyable*/ { + @inlinable + @_lifetime(self: copy self) + package mutating func _append(copying source: UnsafeBufferPointer) { + // FIXME: This needs to be in the stdlib. + self.withUnsafeMutableBufferPointer { dst, dstCount in + let dstEnd = dstCount + source.count + precondition(dstEnd <= dst.count, "OutputSpan capacity overflow") + dst + ._extracting(uncheckedFrom: dstCount, to: dstEnd) + .initializeAll(fromContentsOf: source) + dstCount &+= source.count + } + } + + @inlinable + @_lifetime(self: copy self) + package mutating func _append(copying source: Span) { + // FIXME: This needs to be in the stdlib. + source.withUnsafeBufferPointer { buffer in + self._append(copying: buffer) + } + } +} + +#endif diff --git a/Sources/ContainersPreview/Extensions/TemporaryAllocation.swift b/Sources/ContainersPreview/Extensions/TemporaryAllocation.swift new file mode 100644 index 00000000..6ec7b5fe --- /dev/null +++ b/Sources/ContainersPreview/Extensions/TemporaryAllocation.swift @@ -0,0 +1,36 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2024 - 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.2) + +/// A polyfill of the typed-throws supporting `withUnsafeTemporaryAllocation` in the 6.3 stdlib. +@_alwaysEmitIntoClient @_transparent +package func _withUnsafeTemporaryAllocation< + T: ~Copyable, R: ~Copyable, + E: Error +>( + of type: T.Type, + capacity: Int, + _ body: (UnsafeMutableBufferPointer) throws(E) -> R +) throws(E) -> R { +#if compiler(>=6.3) + try withUnsafeTemporaryAllocation(of: type, capacity: capacity, body) +#else + let r: Result = withUnsafeTemporaryAllocation( + of: T.self, capacity: capacity + ) { buffer in + return Result(catching: { () throws(E) in try body(buffer) }) + } + return try r.get() +#endif +} + +#endif diff --git a/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol.swift b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol.swift new file mode 100644 index 00000000..651937d9 --- /dev/null +++ b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol.swift @@ -0,0 +1,197 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2024 - 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +#endif + +@available(SwiftStdlib 5.0, *) +public protocol BorrowingIteratorProtocol: ~Copyable, ~Escapable { + associatedtype Element: ~Copyable + + // FIXME: This ought to be a core requirement, but `Ref` is not a thing yet. +// @_lifetime(&self) +// @_lifetime(self: copy self) +// mutating func next() -> Ref? + + /// Advance the iterator, returning an ephemeral span over the elements + /// that are ready to be visited. + /// + /// If the underlying sequence is a container type, then the returned span + /// typically directly addresses one of its storage buffers. On the other + /// hand, if the underlying sequence materializes its elements on demand, + /// then the returned span addresses some temporary buffer associated with + /// the iterator itself. Consequently, the returned span is tied to this + /// particular invocation of `nextSpan`, and it cannot survive until the next + /// invocation of it. + /// + /// If the iterator has not yet reached the end of the underlying sequence, + /// then this method returns a non-empty span of at most `maximumCount` + /// elements, and updates the iterator's current position to the element + /// following the last item in the returned span (or the end, if there is + /// none). The `maximumCount` argument allows callers to avoid getting more + /// items that they are able to process in one go, simplifying usage, and + /// avoiding materializing more elements than needed. + /// + /// If the iterator's current position is at the end of the container, then + /// this method returns an empty span without updating the position. + /// + /// This method can be used to efficiently process the items of a container + /// in bulk, by directly iterating over its piecewise contiguous pieces of + /// storage: + /// + /// var it = items.makeBorrowingIterator() + /// while true { + /// let span = it.nextSpan(after: &index) + /// if span.isEmpty { break } + /// // Process items in `span` + /// } + /// + /// Note: The spans returned by this method are not guaranteed to be disjunct. + /// Iterators that materialize elements on demand typically reuse the same + /// buffer over and over again; and even some proper containers may link to a + /// single storage chunk (or parts of a storage chunk) multiple times, for + /// example to repeat their contents. + /// + /// Note: Repeatedly iterating over the same container is expected to return + /// the same items (collected in similarly sized span instances), but the + /// returned spans are not guaranteed to be identical. For example, this is + /// the case with containers that store some of their contents within their + /// direct representation. Such containers may not always have a unique + /// address in memory, and so the locations of the spans exposed by this + /// method may vary between different borrows of the same container.) + @_lifetime(&self) + @_lifetime(self: copy self) + mutating func nextSpan(maximumCount: Int) -> Span + + /// Advance the position of this iterator by the specified offset, or until + /// the end of the underlying sequence. + /// + /// Returns the number of items that were skipped. If this is less than + /// `maximumOffset`, then the sequence did not have enough elements left to + /// skip the requested number of items. In this case, the iterator's current + /// position is set to the end of the sequence. + /// + /// `maximumOffset` must be nonnegative, unless this is a bidirectional + /// or random-access iterator. + @_lifetime(self: copy self) + mutating func skip(by maximumOffset: Int) -> Int + + // FIXME: Add BidirectionalBorrowingIteratorProtocol and RandomAccessBorrowingIteratorProtocol. + // BidirectionalBorrowingIteratorProtocol would need to have a `previousSpan` + // method, which considerably complicates implementation. + // Perhaps these would be better left to as variants of protocol Container, + // which do not need a separate iterator concept. +} + +@available(SwiftStdlib 5.0, *) +extension BorrowingIteratorProtocol where Self: ~Copyable & ~Escapable { + @_lifetime(&self) + @_lifetime(self: copy self) + @_transparent + public mutating func nextSpan() -> Span { + nextSpan(maximumCount: Int.max) + } +} + +@available(SwiftStdlib 5.0, *) +extension BorrowingIteratorProtocol where Self: ~Copyable & ~Escapable { + @_lifetime(self: copy self) + @inlinable + public mutating func skip(by offset: Int) -> Int { + var remainder = offset + while remainder > 0 { + let span = nextSpan(maximumCount: remainder) + if span.isEmpty { break } + remainder &-= span.count + } + return offset &- remainder + } +} + +@available(SwiftStdlib 5.0, *) +extension BorrowingIteratorProtocol where Self: ~Copyable & ~Escapable { +#if false // FIXME: This doesn't work, but it should? + @_lifetime(&self) + @_lifetime(self: copy self) + public mutating func next() -> Ref? { + let span = nextSpan(maximumCount: 1) + guard !span.isEmpty else { return nil } + return Ref(_borrowing: span[unchecked: 0]) + } +#endif + + // @_lifetime(&self) + // @_lifetime(self: copy self) + // public mutating func nextSpan(maximumCount: Int) -> Span { + // guard let ref = next() else { return Span() } + // return ref.span // FIXME + // } +} + +@available(SwiftStdlib 5.0, *) +extension BorrowingIteratorProtocol +where Self: ~Copyable & ~Escapable, Element: Copyable +{ + @_lifetime(self: copy self) + @_transparent + public mutating func copyContents(into target: inout OutputSpan) { + target.withUnsafeMutableBufferPointer { dst, dstCount in + var tail = dst._extracting(droppingFirst: dstCount) + while !tail.isEmpty { + let src = nextSpan(maximumCount: tail.count) + if src.isEmpty { break } + tail._initializeAndDropPrefix(copying: src) + dstCount += src.count + } + } + } +} + +@available(SwiftStdlib 5.0, *) +extension Span: BorrowingIteratorProtocol where Element: ~Copyable { + @_lifetime(copy self) + @_lifetime(self: copy self) + @inlinable + public mutating func nextSpan(maximumCount: Int) -> Span { + _trim(first: maximumCount) + } +} + +// FIXME: Decide if we want UnsafeBufferPointer types to be borrow iterators + +#if false // FIXME: Implement this +@available(SwiftStdlib 5.0, *) +extension MutableSpan: BorrowingIteratorProtocol where Element: ~Copyable { + @_lifetime(copy self) + @_lifetime(self: copy self) + @inlinable + public mutating func nextSpan(maximumCount: Int) -> Span { + //??? + } +} +#endif + +#if false // FIXME: Implement this +@available(SwiftStdlib 5.0, *) +extension OutputSpan: BorrowingIteratorProtocol where Element: ~Copyable { + @_lifetime(copy self) + @_lifetime(self: copy self) + @inlinable + public mutating func nextSpan(maximumCount: Int) -> Span { + //??? + } +} +#endif + +#endif diff --git a/Sources/ContainersPreview/Protocols/BorrowingSequence+Standard Conformances.swift b/Sources/ContainersPreview/Protocols/BorrowingSequence+Standard Conformances.swift new file mode 100644 index 00000000..d43216c7 --- /dev/null +++ b/Sources/ContainersPreview/Protocols/BorrowingSequence+Standard Conformances.swift @@ -0,0 +1,202 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2025 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + +@available(SwiftStdlib 5.0, *) +extension Span: BorrowingSequence where Element: ~Copyable { + // FIXME: This simple definition cannot also be a backward (or bidirectional) + // iterator, nor a random-access iterator. If we want to go in that direction, + // we'll need to rather introduce a type more like `RigidArray.BorrowingIterator`. + public typealias BorrowingIterator = Self + + @inlinable + public var estimatedCount: EstimatedCount { + .exactly(count) + } + + @_lifetime(copy self) + @inlinable + public func makeBorrowingIterator() -> Span { + self + } +} + +@available(SwiftStdlib 5.0, *) +extension MutableSpan: BorrowingSequence where Element: ~Copyable { + public typealias BorrowingIterator = Span.BorrowingIterator + + @inlinable + public var estimatedCount: EstimatedCount { + .exactly(count) + } + + @_lifetime(borrow self) + @inlinable + public func makeBorrowingIterator() -> Span { + self.span + } +} + +@available(SwiftStdlib 5.0, *) +extension OutputSpan: BorrowingSequence where Element: ~Copyable { + public typealias BorrowingIterator = Span.BorrowingIterator + + @inlinable + public var estimatedCount: EstimatedCount { + .exactly(count) + } + + @_lifetime(borrow self) + @inlinable + public func makeBorrowingIterator() -> Span { + self.span + } +} + +@available(SwiftStdlib 5.0, *) +extension InputSpan: BorrowingSequence where Element: ~Copyable { + public typealias BorrowingIterator = Span.BorrowingIterator + + @inlinable + public var estimatedCount: EstimatedCount { + .exactly(count) + } + + @_lifetime(borrow self) + @inlinable + public func makeBorrowingIterator() -> Span { + self.span + } +} + +@available(SwiftStdlib 6.2, *) +extension Array: BorrowingSequence { + public typealias BorrowingIterator = Span.BorrowingIterator + + @inlinable + public var estimatedCount: EstimatedCount { + .exactly(count) + } + + @_lifetime(borrow self) + @inlinable + public func makeBorrowingIterator() -> Span { + self.span + } +} + +@available(SwiftStdlib 6.2, *) +extension Range: BorrowingSequence +where Bound: Strideable, Bound.Stride: SignedInteger +{ + public typealias Element = Bound + + @frozen + public struct BorrowingIterator: BorrowingIteratorProtocol, ~Copyable { + @usableFromInline + internal var _current: InlineArray<1, Bound> + + @usableFromInline + internal var _end: Bound + + @usableFromInline + internal var _progress: Bool + + @inlinable + internal init(_ base: Range) { + self._current = .init(repeating: base.lowerBound) + self._end = base.upperBound + self._progress = false + } + @inlinable + @_lifetime(&self) + public mutating func nextSpan(maximumCount: Int) -> Span { + if _progress { + _current[0] = _current[0].advanced(by: 1) + } + guard _current[0] < _end else { + _progress = false + return .init() + } + _progress = true + return _current.span + } + } + + @inlinable + public var estimatedCount: EstimatedCount { + if let count = Int(exactly: lowerBound.distance(to: upperBound)) { + return .exactly(count) + } + return .unknown + } + + @inlinable + public func makeBorrowingIterator() -> BorrowingIterator { + BorrowingIterator(self) + } +} + +@available(SwiftStdlib 6.2, *) +extension ClosedRange: BorrowingSequence +where Bound: Strideable, Bound.Stride: SignedInteger +{ + public typealias Element = Bound + + @frozen + public struct BorrowingIterator: BorrowingIteratorProtocol, ~Copyable { + @usableFromInline + internal var _current: InlineArray<1, Bound> + + @usableFromInline + internal var _last: Bound + + @usableFromInline + internal var _progress: Bool + + @inlinable + internal init(_ base: ClosedRange) { + self._current = .init(repeating: base.lowerBound) + self._last = base.upperBound + self._progress = false + } + @inlinable + @_lifetime(&self) + public mutating func nextSpan(maximumCount: Int) -> Span { + if _progress { + _current[0] = _current[0].advanced(by: 1) + } + guard _current[0] <= _last else { + _progress = false + return .init() + } + _progress = true + return _current.span + } + } + + @inlinable + public var estimatedCount: EstimatedCount { + guard let distance = Int(exactly: lowerBound.distance(to: upperBound)) + else { return .unknown } + let advanced = distance.addingReportingOverflow(1) + guard !advanced.overflow else { return .unknown } + return .exactly(advanced.partialValue) + } + + @inlinable + public func makeBorrowingIterator() -> BorrowingIterator { + BorrowingIterator(self) + } +} + +#endif diff --git a/Sources/ContainersPreview/Protocols/BorrowingSequence+Utilities.swift b/Sources/ContainersPreview/Protocols/BorrowingSequence+Utilities.swift new file mode 100644 index 00000000..1bd60bfd --- /dev/null +++ b/Sources/ContainersPreview/Protocols/BorrowingSequence+Utilities.swift @@ -0,0 +1,265 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +#endif + +#if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + +@available(SwiftStdlib 5.0, *) +extension BorrowingSequence where Self: ~Copyable & ~Escapable, Element: Copyable { + @inlinable + package func _copyContents( + intoPrefixOf buffer: UnsafeMutableBufferPointer + ) -> Int { + var target = buffer + var it = self.makeBorrowingIterator() + while target.count != 0 { + let span = it.nextSpan(maximumCount: target.count) + if span.isEmpty { + return buffer.count - target.count + } + target._initializeAndDropPrefix(copying: span) + } + let test = it.nextSpan() + precondition(test.isEmpty, "Contents do not fit in target buffer") + return buffer.count + } +} + +#if true // FIXME: rdar://150228920 +@available(SwiftStdlib 5.0, *) +extension BorrowingSequence where Self: ~Copyable & ~Escapable { + @inlinable + public func elementsEqual< + Other: BorrowingSequence & ~Copyable & ~Escapable + >( + _ other: borrowing Other, + ) -> Bool where Element: Equatable { + guard self.estimatedCount._mayBeEqual(to: other.estimatedCount) else { + return false + } + + var it1 = self.makeBorrowingIterator() + var it2 = other.makeBorrowingIterator() + while true { + let a = it1.nextSpan() + var i = 0 + if a.isEmpty { + return it2.nextSpan().isEmpty + } + while i < a.count { + let b = it2.nextSpan(maximumCount: a.count) + if b.isEmpty { + return false + } + precondition(b.count <= a.count - i) + + var j = 0 + while j < b.count { + guard a[unchecked: i] == b[unchecked: j] else { return false } + i &+= 1 + j &+= 1 + } + } + } + } +} + +@available(SwiftStdlib 5.0, *) +extension BorrowingSequence where Self: ~Copyable & ~Escapable { + /// Returns a Boolean value indicating whether two borrowing sequences contain + /// equivalent elements in the same order, using the given predicate as the + /// equivalence test. + /// + /// The predicate must form an *equivalence relation* over the elements. That + /// is, for any elements `a`, `b`, and `c`, the following conditions must + /// hold: + /// + /// - `areEquivalent(a, a)` is always `true`. (Reflexivity) + /// - `areEquivalent(a, b)` implies `areEquivalent(b, a)`. (Symmetry) + /// - If `areEquivalent(a, b)` and `areEquivalent(b, c)` are both `true`, then + /// `areEquivalent(a, c)` is also `true`. (Transitivity) + /// + /// - Parameters: + /// - other: A BorrowingSequence to compare to this BorrowingSequence. + /// - areEquivalent: A predicate that returns `true` if its two arguments + /// are equivalent; otherwise, `false`. + /// - Returns: `true` if this BorrowingSequence and `other` contain equivalent items, + /// using `areEquivalent` as the equivalence test; otherwise, `false.` + /// + /// - Complexity: O(*m*), where *m* is the count of the longer of the input sequences. + @inlinable + public func elementsEqual< + E: Error, + Other: BorrowingSequence & ~Copyable & ~Escapable + >( + _ other: borrowing Other, + by areEquivalent: (borrowing Element, borrowing Other.Element) throws(E) -> Bool + ) throws(E) -> Bool { + switch (self.estimatedCount, other.estimatedCount) { + case let (.exactly(a), .exactly(b)): + guard a == b else { return false } + default: + break + } + var it1 = self.makeBorrowingIterator() + var it2 = other.makeBorrowingIterator() + while true { + let a = it1.nextSpan() + var i = 0 + if a.isEmpty { + return it2.nextSpan().isEmpty + } + while i < a.count { + let b = it2.nextSpan(maximumCount: a.count) + if b.isEmpty { + return false + } + precondition(b.count <= a.count - i) + + var j = 0 + while j < b.count { + guard try areEquivalent(a[unchecked: i], b[unchecked: j]) else { + return false + } + i &+= 1 + j &+= 1 + } + } + } + } +} + +#else // rdar://150228920 +@available(SwiftStdlib 5.0, *) +extension BorrowingSequence where Self: ~Copyable & ~Escapable { + @inlinable + public func elementsEqual< + Other: BorrowingSequence & ~Copyable & ~Escapable + >( + _ other: borrowing Other, + ) -> Bool where Element: Equatable { + var it1 = self.makeBorrowingIterator() + var it2 = other.makeBorrowingIterator() + var a = Span() + var b = Span() + loop: + while true { + if a.isEmpty { + a = it1.nextSpan() + } + if b.isEmpty { + b = it2.nextSpan() + } + if a.isEmpty || b.isEmpty { + return a.isEmpty && b.isEmpty + } + + let c = Swift.min(a.count, b.count) + var i = 0 + while i < c { + guard a[unchecked: i] == b[unchecked: i] else { return false } + i &+= 1 + } + a = a.extracting(droppingFirst: c) + b = b.extracting(droppingFirst: c) + } + } +} + +@available(SwiftStdlib 5.0, *) +extension BorrowingSequence where Self: ~Copyable & ~Escapable { + @inlinable + @discardableResult + internal func _spanwiseZip< + Other: BorrowingSequence & ~Copyable & ~Escapable, + State: ~Copyable, E: Error + >( + state: inout State, + with other: borrowing Other, + by process: (inout State, Span, Span) throws(E) -> Bool + ) throws(E) -> Int { + var it1 = self.makeBorrowingIterator() + var it2 = other.makeBorrowingIterator() + var a = Span() + var b = Span() + var offset = 0 // Offset of the start of the current spans + loop: + while true { + if a.isEmpty { + a = it1.nextSpan() + } + if b.isEmpty { + b = it2.nextSpan() + } + if a.isEmpty || b.isEmpty { + return offset + } + + let c = Swift.min(a.count, b.count) + guard try process(&state, a.extracting(first: c), b.extracting(first: c)) else { + return offset + } + a = a.extracting(droppingFirst: c) + b = b.extracting(droppingFirst: c) + offset += c + } + } + + /// Returns a Boolean value indicating whether this BorrowingSequence and another + /// BorrowingSequence contain equivalent elements in the same order, using the given + /// predicate as the equivalence test. + /// + /// The predicate must form an *equivalence relation* over the elements. That + /// is, for any elements `a`, `b`, and `c`, the following conditions must + /// hold: + /// + /// - `areEquivalent(a, a)` is always `true`. (Reflexivity) + /// - `areEquivalent(a, b)` implies `areEquivalent(b, a)`. (Symmetry) + /// - If `areEquivalent(a, b)` and `areEquivalent(b, c)` are both `true`, then + /// `areEquivalent(a, c)` is also `true`. (Transitivity) + /// + /// - Parameters: + /// - other: A BorrowingSequence to compare to this BorrowingSequence. + /// - areEquivalent: A predicate that returns `true` if its two arguments + /// are equivalent; otherwise, `false`. + /// - Returns: `true` if this BorrowingSequence and `other` contain equivalent items, + /// using `areEquivalent` as the equivalence test; otherwise, `false.` + /// + /// - Complexity: O(*m*), where *m* is the count of the longer of the input sequences. + @inlinable + public func elementsEqual< + E: Error, + Other: BorrowingSequence & ~Copyable & ~Escapable + >( + _ other: borrowing Other, + by areEquivalent: (borrowing Element, borrowing Other.Element) throws(E) -> Bool + ) throws(E) -> Bool { + guard self.count == other.count else { return false } + var result = true + try _spanwiseZip(state: &result, with: other) { state, a, b throws(E) in + assert(a.count == b.count) + for i in a.indices { + guard try areEquivalent(a[i], b[i]) else { + state = false + return false + } + } + return true + } + return result + } +} +#endif + +#endif diff --git a/Sources/ContainersPreview/Container.swift b/Sources/ContainersPreview/Protocols/BorrowingSequence.swift similarity index 50% rename from Sources/ContainersPreview/Container.swift rename to Sources/ContainersPreview/Protocols/BorrowingSequence.swift index a804e5aa..16678a83 100644 --- a/Sources/ContainersPreview/Container.swift +++ b/Sources/ContainersPreview/Protocols/BorrowingSequence.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors +// Copyright (c) 2024 - 2026 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information @@ -11,26 +11,90 @@ #if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW -@available(SwiftStdlib 5.0, *) -public protocol Container: ~Copyable, ~Escapable { - associatedtype Element: ~Copyable /*& ~Escapable*/ - associatedtype BorrowIterator: BorrowIteratorProtocol & ~Copyable & ~Escapable +public enum EstimatedCount { + case infinite + case exactly(Int) + case unknown - var isEmpty: Bool { get } - var count: Int { get } - - @_lifetime(borrow self) - borrowing func startBorrowIteration() -> BorrowIterator + @inlinable + package func _mayBeEqual(to other: EstimatedCount) -> Bool { + switch (self, other) { + case let (.exactly(a), .exactly(b)): + return a == b + case (.exactly(_), .infinite): + return false + case (.infinite, .exactly(_)): + return false + default: + return true + } + } } @available(SwiftStdlib 5.0, *) -extension Container where Self: ~Copyable & ~Escapable { +public protocol BorrowingSequence: ~Copyable, ~Escapable { + associatedtype Element: ~Copyable + associatedtype BorrowingIterator: BorrowingIteratorProtocol & ~Copyable & ~Escapable + + var estimatedCount: EstimatedCount { get } + + @_lifetime(borrow self) + borrowing func makeBorrowingIterator() -> BorrowingIterator + + func _customContainsEquatableElement( + _ element: borrowing Element + ) -> Bool? +} + +@available(SwiftStdlib 5.0, *) +extension BorrowingSequence where Self: ~Copyable & ~Escapable { + @inlinable + public var underestimatedCount: Int { + switch estimatedCount { + case .infinite: + Int.max + case .exactly(let c): + c + case .unknown: + 0 + } + } + + @inlinable + public func _customContainsEquatableElement(_ element: borrowing Element) -> Bool? { + nil + } +} + +@available(SwiftStdlib 5.0, *) +extension BorrowingSequence where Self: Sequence { + @inlinable + public func _customContainsEquatableElement(_ element: borrowing Element) -> Bool? { + nil + } +} + +@available(SwiftStdlib 5.0, *) +extension BorrowingSequence where Element: Copyable { + // FIXME: How do we expect this to work for ~Copyable elements? + public var first: Element? { + var it = makeBorrowingIterator() + let span = it.nextSpan(maximumCount: 1) + guard !span.isEmpty else { return nil } + return span[0] + } +} + + + +@available(SwiftStdlib 5.0, *) +extension BorrowingSequence where Self: ~Copyable & ~Escapable { /// Implementation demo of what borrowing for-in loops would need to expand into. @inlinable public func _borrowingForEach( _ body: (borrowing Element) throws(E) -> Void ) throws(E) -> Void { - var it = startBorrowIteration() + var it = makeBorrowingIterator() while true { let span = it.nextSpan() if span.isEmpty { break } @@ -44,7 +108,7 @@ extension Container where Self: ~Copyable & ~Escapable { } @available(SwiftStdlib 5.0, *) -extension Container where Self: ~Copyable & ~Escapable { +extension BorrowingSequence where Self: ~Copyable & ~Escapable { @inlinable public func borrowingReduce( into initial: consuming Result, @@ -68,7 +132,7 @@ extension Container where Self: ~Copyable & ~Escapable { result = try next(result, item) } #else - var it = startBorrowIteration() + var it = makeBorrowingIterator() while true { let span = it.nextSpan() if span.isEmpty { break } diff --git a/Sources/ContainersPreview/Protocols/Container.swift b/Sources/ContainersPreview/Protocols/Container.swift new file mode 100644 index 00000000..6a380909 --- /dev/null +++ b/Sources/ContainersPreview/Protocols/Container.swift @@ -0,0 +1,461 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2024 - 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + +@available(SwiftStdlib 5.0, *) +public protocol Container: BorrowingSequence, ~Copyable, ~Escapable { + associatedtype Index: Comparable + + var count: Int { get } + + var startIndex: Index { get } + var endIndex: Index { get } + + /// Returns the position immediately after the given index. + /// + /// - Parameter index: A valid index of the container. `i` must be less + /// than `endIndex`. + /// - Returns: The index immediately following `i`. + func index(after index: Index) -> Index + + /// Replaces the given index with its successor. + /// + /// - Parameter index: A valid index of the container. `i` must be less + /// than `endIndex`. + func formIndex(after index: inout Index) + + /// Returns an index that is the specified distance from the given index. + /// + /// The value passed as `n` must not offset `index` beyond the bounds of the + /// container. + /// + /// - Parameter index: A valid index of the container. + /// - Parameter n: The distance by which to offset `index`. + /// - Returns: An index offset by distance from `index`. If `n` is positive, + /// this is the same value as the result of `n` calls to `index(after:)`. + /// If `n` is negative, this is the same value as the result of `abs(n)` + /// calls to `index(before:)`. + func index(_ index: Index, offsetBy n: Int) -> Index + + /// Offsets the given index by the specified distance, but no further than + /// the given limiting index. + /// + /// If the operation was able to offset `index` by exactly the requested + /// number of steps without hitting `limit`, then on return `n` is set to `0`, + /// and `index` is set to the adjusted index. + /// + /// If the operation hits the limit before it can take the requested number + /// of steps, then on return `index` is set to `limit`, and `n` is set + /// to the number of steps that couldn't be taken. + /// + /// The value passed as `n` must not offset `index` beyond the bounds of the + /// container, unless the index passed as `limit` prevents offsetting beyond + /// those bounds. + /// + /// - Parameter index: A valid index of the container. + /// - Parameter n: The distance to offset `index`. `n` must not be negative + /// unless the container conforms to the `BidirectionalContainer` protocol. + /// - Parameter limit: A valid index of the container to use as a limit. + /// If `n > 0`, a limit that is less than `index` has no effect. + /// Likewise, if `n < 0`, a limit that is greater than `index` has no + /// effect. + func formIndex( + _ index: inout Index, offsetBy n: inout Int, limitedBy limit: Index + ) + + /// Returns the distance between two indices. + /// + /// - Parameter start: A valid index of the collection. + /// - Parameter end: Another valid index of the collection. If end is equal + /// to start, the result is zero. + /// - Returns: The distance between `start` and `end`. + func distance(from start: Index, to end: Index) -> Int + + /// Return a span over the container's storage that begins with the element at + /// the given index, and extends to the end of the contiguous storage chunk + /// that contains it, but no more than `maximumCount` items. + /// + /// On return, the index is updated to address the next item following the + /// end of the returned span. + /// + /// This method can be used to efficiently process the items of a container in + /// bulk, by directly iterating over its piecewise contiguous pieces of + /// storage: + /// + /// var index = items.startIndex + /// while true { + /// let span = items.nextSpan(after: &index, maximumCount: 4) + /// if span.isEmpty { break } + /// // Process items in `span` + /// } + /// + /// The `maximumCount` argument gives the caller control over the number of + /// items it receives from the iterator. This lets the caller avoid getting + /// more elements than it would be able to immediately process, which would + /// significantly complicate container use. + /// + /// If the caller is able to process any number available items, it can signal + /// that by passing `Int.max` as the `maximumCount`, or simply by calling the + /// `nexSpan(after:)` method, which does precisely that. This is frequently + /// the case when the caller simply wants to iterate over the entire + /// container in a single loop. + /// + /// `maximumCount` sets an upper bound. To read a specific number of items, + /// the caller usually needs to invoke `nextSpan` in a loop: + /// + /// var items: some Container + /// var index = items.startIndex + /// var remainder = numberOfItemsToRead + /// while remainder > 0 { + /// let next = items.nextSpan(after: &index, maximumCount: remainder) + /// guard !next.isEmpty else { + /// // Container does not have enough items + /// break + /// } + /// remainder -= next.count + /// // Process items in `next` + /// } + /// + /// - Note: The spans returned by this method are not guaranteed to be + /// disjunct. Some containers may use the same storage chunk (or parts of a + /// storage chunk) multiple times, to repeat their contents. + /// + /// - Note: Repeated invocations of `nextSpan` on the same container and index + /// are not guaranteed to return identical results. (This is particularly + /// the case with containers that can store contents in their "inline" + /// representation. Such containers may not always have a unique address + /// in memory; the locations of the spans exposed by this method may vary + /// between different borrows of the same container.) + /// + /// - Parameter index: A valid index in the container, including the end + /// index. On return, this index is advanced by the count of the resulting + /// span, to simplify iteration. + /// - Parameter maximumCount: The maximum number of items the caller is able + /// to process immediately. `maximumCount` must be greater than zero. + /// If you are able to process an arbitrary number of items, set + /// `maximumCount` to `Int.max`, or call the `nextSpan(after:)` method. + /// - Returns: A span over contiguous storage that starts at the given index. + /// If the input index is the end index, then this returns an empty span. + /// Otherwise the result is non-empty, with its first element matching the + /// element at the input index. + @_lifetime(borrow self) + func nextSpan(after index: inout Index, maximumCount: Int) -> Span + + // subscript(index: Index) -> Element { borrow } + + // FIXME: Do we want these as standard requirements this time? + func index(alignedDown index: Index) -> Index + func index(alignedUp index: Index) -> Index +} + +@available(SwiftStdlib 5.0, *) +extension Container where Self: ~Copyable & ~Escapable { + /// Return a span over the container's storage that begins with the element at + /// the given index, and extends to the end of the contiguous storage chunk + /// that contains it. On return, the index is updated to address the next item + /// following the end of the returned span. + /// + /// This method can be used to efficiently process the items of a container in + /// bulk, by directly iterating over its piecewise contiguous pieces of + /// storage: + /// + /// var index = items.startIndex + /// while true { + /// let span = items.nextSpan(after: &index) + /// if span.isEmpty { break } + /// // Process items in `span` + /// } + /// + /// - Note: The spans returned by this method are not guaranteed to be + /// disjunct. Some containers may use the same storage chunk (or parts of a + /// storage chunk) multiple times, to repeat their contents. + /// + /// - Note: Repeated invocations of `nextSpan` on the same container and index + /// are not guaranteed to return identical results. (This is particularly + /// the case with containers that can store contents in their "inline" + /// representation. Such containers may not always have a unique address + /// in memory; the locations of the spans exposed by this method may vary + /// between different borrows of the same container.) + /// + /// - Parameter index: A valid index in the container, including the end + /// index. On return, this index is advanced by the count of the resulting + /// span, to simplify iteration. + /// - Returns: A span over contiguous storage that starts at the given index. + /// If the input index is the end index, then this returns an empty span. + /// Otherwise the result is non-empty, with its first element matching the + /// element at the input index. + @inlinable + @_lifetime(borrow self) + public func nextSpan(after index: inout Index) -> Span { + nextSpan(after: &index, maximumCount: Int.max) + } + +// @inlinable +// @_lifetime(borrow self) +// public func nextSpan(after index: inout Index, maximumCount: Int) -> Span { +// let original = index +// var span = nextSpan(after: &index) +// if span.count > maximumCount { +// span = span.extracting(first: maximumCount) +// // Index remains within the same span, so offseting it is expected to be quick +// index = self.index(original, offsetBy: maximumCount) +// } +// return span +// } +} + +@available(SwiftStdlib 5.0, *) +extension Container where Self: ~Copyable & ~Escapable { + @inlinable + public func formIndex(after index: inout Index) { + index = self.index(after: index) + } + + @inlinable + public func index(_ index: Index, offsetBy n: Int) -> Index { + _defaultIndex(index, advancedBy: n) + } + + @inlinable + public func formIndex( + _ index: inout Index, offsetBy n: inout Int, limitedBy limit: Index + ) { + _defaultFormIndex(&index, advancedBy: &n, limitedBy: limit) + } + + @inlinable + public func distance(from start: Index, to end: Index) -> Int { + _defaultDistance(from: start, to: end) + } + + @inlinable + public func index(alignedDown index: Index) -> Index { index } + + @inlinable + public func index(alignedUp index: Index) -> Index { index } +} + + +@available(SwiftStdlib 5.0, *) +extension Container where Self: ~Copyable & ~Escapable { + @inlinable + public func _defaultDistance(from start: Index, to end: Index) -> Int { + // FIXME: Use binary search here (with nextSpan(after:maximumCount:)) + var start = index(alignedDown: start) + let end = index(alignedDown: end) + if start > end { + return -_defaultDistance(from: end, to: start) + } + var count = 0 + while start != end { + count = count + 1 + formIndex(after: &start) + } + return count + } + + @inlinable + public func _defaultIndex(_ i: Index, advancedBy distance: Int) -> Index { + precondition( + distance >= 0, + "Only BidirectionalContainers can be advanced by a negative amount") + + var i = index(alignedDown: i) + var distance = distance + + #if true // with nextSpan(after:maximumCount:) + while distance > 0 { + let span = self.nextSpan(after: &i, maximumCount: distance) + precondition( + !span.isEmpty, + "Cannot advance index beyond the end of the container") + distance &-= span.count + } + return i + #else // without nextSpan(after:maximumCount:) + // FIXME: This implementation can be wasteful for contiguous containers, + // as iterating over spans will overshoot the target immediately. + // Reintroducing `nextSpan(after:maximumCount:)` would help avoid + // having to use a second loop to refine the result, but it would + // complicate conformances. + + // Skip forward until we find the span that contains our target. + while distance > 0 { + var j = i + let span = self.nextSpan(after: &j) + precondition( + !span.isEmpty, + "Cannot advance index beyond the end of the container") + guard span.count <= distance else { break } + i = j + distance &-= span.count + } + // Step through to find the precise target. + while distance > 0 { + self.formIndex(after: &i) + distance &-= 1 + } + return i + #endif + } + + @inlinable + public func _defaultFormIndex( + _ i: inout Index, + advancedBy distance: inout Int, + limitedBy limit: Index + ) { + precondition( + distance >= 0, + "Only BidirectionalContainers can be advanced by a negative amount") + + i = index(alignedDown: i) + let limit = index(alignedDown: limit) + if i > limit { + i = self.index(i, offsetBy: distance) + distance = 0 + return + } + +#if true // with nextSpan(after:maximumCount:) + // Skip forward until find our target or overshoot the limit. + while distance > 0, i < limit { + var j = i + let span = self.nextSpan(after: &j, maximumCount: distance) + precondition( + !span.isEmpty, + "Cannot advance index beyond the end of the container") + if j > limit { + break + } + i = j + distance &-= span.count + } + // Step through to find the precise target. + // FIXME: Use binary search here + while distance != 0 { + if i == limit { + return + } + formIndex(after: &i) + distance &-= 1 + } +#else // without nextSpan(after:maximumCount:) + // Skip forward until we find the span that contains our target. + while distance > 0 { + var j = i + let span = self.nextSpan(after: &j) + precondition( + !span.isEmpty, + "Cannot advance index beyond the end of the container") + guard span.count <= distance, j < limit else { + break + } + i = j + distance &-= span.count + } + // Step through to find the precise target. + while distance != 0 { + if i == limit { + return + } + formIndex(after: &i) + distance &-= 1 + } +#endif + } +} + +@available(SwiftStdlib 5.0, *) +extension Container where Self: ~Copyable & ~Escapable { + @_transparent + public var estimatedCount: EstimatedCount { .exactly(count) } +} + + +@available(SwiftStdlib 5.0, *) +public struct ContainerIterator< + Base: Container & ~Copyable /*FIXME: & ~Escapable*/ +>: ~Copyable, ~Escapable { + let _base: Borrow // FIXME: This doesn't support nonescapable Bases + var _position: Base.Index + + @_lifetime(borrow base) + init(_borrowing base: borrowing @_addressable Base, from position: Base.Index) { + self._base = Borrow(_borrowing: base) + self._position = position + } +} + +@available(SwiftStdlib 5.0, *) +extension ContainerIterator: BorrowingIteratorProtocol +where Base: ~Copyable /*FIXME: & ~Escapable*/ +{ + public typealias Element = Base.Element + + @_unsafeNonescapableResult // FIXME: we cannot convert from a borrow to an inout dependence! + @_lifetime(&self) + public mutating func nextSpan(maximumCount: Int) -> Span { + _base[].nextSpan(after: &self._position, maximumCount: maximumCount) + } +} + +@available(SwiftStdlib 5.0, *) +extension Container +where + Self: ~Copyable /*FIXME: & ~Escapable*/, + BorrowingIterator == ContainerIterator +{ + @_lifetime(borrow self) + public func makeBorrowingIterator() -> BorrowingIterator { + ContainerIterator(_borrowing: self, from: self.startIndex) + } +} + +#endif + +extension Strideable { + @inlinable + package mutating func _advance( + by distance: inout Stride, limitedBy limit: Self + ) { + if distance >= 0 { + guard limit >= self else { + self = self.advanced(by: distance) + distance = 0 + return + } + let d = Swift.min(distance, self.distance(to: limit)) + self = self.advanced(by: d) + distance -= d + } else { + guard limit <= self else { + self = self.advanced(by: distance) + distance = 0 + return + } + let d = Swift.max(distance, self.distance(to: limit)) + self = self.advanced(by: d) + distance -= d + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @inlinable + public mutating func advance( + by distance: inout Stride, limitedBy limit: Self + ) { + _advance(by: &distance, limitedBy: limit) + } +#endif +} + diff --git a/Sources/ContainersPreview/Protocols/ContainerAlgorithms.swift b/Sources/ContainersPreview/Protocols/ContainerAlgorithms.swift new file mode 100644 index 00000000..72fb0b41 --- /dev/null +++ b/Sources/ContainersPreview/Protocols/ContainerAlgorithms.swift @@ -0,0 +1,58 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2024 - 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + +@available(SwiftStdlib 6.2, *) +extension Container where Self: ~Copyable & ~Escapable { + @_alwaysEmitIntoClient + internal func _spanwiseZip( + with other: borrowing Other, + by process: (Span, Span) throws(E) -> Bool + ) throws(E) -> (Index, Other.Index) { + var i = self.startIndex // End index of the current span in `self` + var j = other.startIndex // End index of the current span in `other` + var a: Span = .init() + var b: Span = .init() + var pi = i // Start index of the original span we're currently processing in `self` + var pj = j // Start index of the original span we're currently processing in `other` + var ca = 0 // Count of the original span we're currently processing in `self` + var cb = 0 // Count of the original span we're currently processing in `other` + loop: + while true { + if a.isEmpty { + pi = i + a = self.nextSpan(after: &i) + ca = a.count + } + if b.isEmpty { + pj = j + b = other.nextSpan(after: &j) + cb = b.count + } + if a.isEmpty || b.isEmpty { + return ( + (a.isEmpty ? i : self.index(pi, offsetBy: ca - a.count)), + (b.isEmpty ? j : other.index(pj, offsetBy: cb - b.count))) + } + + let c = Swift.min(a.count, b.count) + + guard try process(a._trim(first: c), b._trim(first: c)) else { + return ( + (a.isEmpty ? i : self.index(pi, offsetBy: c)), + (b.isEmpty ? j : other.index(pj, offsetBy: c))) + } + } + } +} + +#endif diff --git a/Sources/ContainersPreview/Protocols/Drain.swift b/Sources/ContainersPreview/Protocols/Drain.swift new file mode 100644 index 00000000..938d0d74 --- /dev/null +++ b/Sources/ContainersPreview/Protocols/Drain.swift @@ -0,0 +1,215 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2024 - 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + +/// A type that supplies the values of an in-place consumable sequence through +/// a series of `InputSpan` instances. This iterator-like construct allows +/// directly consuming elements from some container's storage, in bulk, +/// without requiring them to be moved into any temporary buffer. +/// +/// Drains are inherently also producers -- they can produce items by simply +/// moving their consumable contents to the client-supplied series of +/// output spans. +@available(SwiftStdlib 5.0, *) +public protocol Drain: Producer, ~Copyable, ~Escapable +where ProducerError == Never +{ + /// Returns the next span of consumable items in the sequence underlying this + /// drain, of at most the specified maximum count. A `maximumCount` of nil + /// indicates no limit, meaning that the client is able to process an + /// arbitrarily large number of elements. + /// + /// Repeatedly calling this method returns, in order, all the elements of the + /// underlying consumable sequence. As soon as the sequence has run out of + /// elements, all subsequent calls return empty spans. + /// + /// While the returned input spans exist, they continue to mutate the drain, + /// extending the exclusive access initiated by the call to + /// `drainNext(maximumCount:)`. To call this (or any other) method again, the + /// returned input span needs to be consumed or otherwise destroyed. + /// + /// Once this method returns, the contents of the resulting input span are + /// already destined for consumption, either gradually by invoking explicit + /// methods such as `InputSpan.popFirst`, or all at once when + /// the input span is destroyed. There is no way to "put items back" into + /// the consumable sequence, other than by moving them into a + /// temporary location and later reinserting them into the underlying + /// construct through some type-specific operations. + /// + /// - Parameter maximumCount: The maximum number of items that the client + /// is prepared to consume, or nil if the client is able to process an + /// arbitrary number of elements. If this is non-nil, then it must be a + /// positive integer. + /// - Returns: An input span of at most the specified maximum count (if any), + /// containing the next elements of the underlying consumable sequence. + /// This method returns an empty span to indicate that it has reached + /// the end of the sequence. + @_lifetime(&self) + @_lifetime(self: copy self) + mutating func drainNext(maximumCount: Int) -> InputSpan + // TODO: The primary use case does not need this to throw; do we need to allow that? + // Note: making this failable is not entirely straightforward, as there is no + // easy way to signal partial success -- conforming implementations + // would likely need to store errors they encounter midway through a + // chunk and report them at the beginning of the next iteration. + // I take this as an indication that we don't need to do that. + // (Contrast with this `Producer.generate(into:)`; the shape of that method + // allows it to partially populate its client-supplied target and still + // report an error.) + // + // Note: We can also express this with a higher-order shape: + // + // mutating func drainNext( + // _ body: (inout InputSpan) throws(E) -> R + // ) throws(E) -> R + // + // This would allow partial consumption, eliminating the need for + // `maximumCount`, but at the cost of having to deal with closures -- + // it can be tricky to elegantly flow data/control in & out higher-order + // functions. Allowing the function argument to throw also precludes + // the drain itself from throwing, unless they are both required + // to use the same error type, which would be impractical. +} + +@available(SwiftStdlib 5.0, *) +extension Drain where Self: ~Copyable & ~Escapable { + /// Returns the next span of consumable items in the sequence underlying this + /// drain, of an arbitrarily large count. + /// + /// Repeatedly calling this method returns, in order, all the elements of the + /// underlying consumable sequence. As soon as the sequence has run out of + /// elements, all subsequent calls return empty spans. + /// + /// While the returned input spans exist, they continue to mutate the drain, + /// extending the exclusive access initiated by the call to + /// `drain(maximumCount:)`. To call this (or any other) method again, the + /// returned input span needs to be consumed or otherwise destroyed. + /// + /// Once this method returns, the contents of the resulting input span are + /// already destined for consumption, either gradually by invoking explicit + /// methods such as `InputSpan.popFirst`, or all at once when + /// the input span is destroyed. There is no way to "put items back" into + /// the consumable sequence, other than by moving them into a + /// temporary location and later reinserting them into the underlying + /// construct through some type-specific operations. + /// + /// - Returns: An input span containing the next elements of the underlying + /// consumable sequence. This method returns an empty span to indicate + /// that it has reached the end of the sequence. + @_lifetime(&self) + @_lifetime(self: copy self) + @_transparent + mutating func drainNext() -> InputSpan { + drainNext(maximumCount: Int.max) + } + + /// Generate the next batch of items into the supplied output span instance, + /// which must have room for at least one new element. + /// + /// Repeatedly calling this method produces, in order, all the elements of the + /// underlying generative sequence. As soon as the sequence has run out of + /// elements, all subsequent calls return false without appending any new + /// items to their target. This method is not guaranteed to fully populate the + /// given output span, but it always appends at least one item until the end + /// of the underlying generative sequence. + /// + /// The ownership of all generated elements is transferred to the caller of + /// this method -- it can arbitrarily store, mutate, consume or discard them + /// as needed, even across invocations of this method, or after the producer + /// is destroyed. + /// + /// The returned Boolean value can be used to easily determine if the + /// method was able to make progress towards filling `target` without hitting + /// the end of the underlying sequence. + /// + /// ### Error handling + /// + /// This method throws an error to indicate a failure while trying to generate + /// the upcoming next item in the sequence. Failure may happen midway through + /// populating `target`, in which case the output span will still gain + /// new items despite the error. (Those items are successfully + /// generated, and do not necessarilly need to be discarded.) + /// + /// This protocol does not specify the meaning of a failure, or the + /// precise state of the iterator after an error is thrown; however, the + /// error must not trigger runtime traps in subsequent attempts at iteration. + /// (After a failure, conforming types may choose to produce new items, or + /// signal the end of the iteration, or throw another error, which may or may + /// not match the first.) + /// + /// Absent of more specific information, generic code should stop + /// iterating, discard the producer and rethrow the error when it encounters + /// a failure. Generic code is encouraged to preserve the items that got + /// successfully produced before the throw (including ones appended by + /// the call that ultimately ended in failure); however, whether this is + /// possible (or desirable) ultimately depends on the specific problem that + /// the algorithm is solving. + /// + /// - Parameter target: An output span ready to take newly generated items. + /// - Returns: A boolean value indicating whether the operation was able to + /// append at least one item to the supplied output span without hitting + /// the end of the underlying sequence. + @inlinable + @_lifetime(target: copy target) + public mutating func generate( + into target: inout OutputSpan + ) throws(Never) -> Bool { + var source = self.drainNext(maximumCount: target.freeCapacity) + if source.isEmpty { return false } + target._append(moving: &source) + return true + } + + /// Skip at most the given number items in the underlying generative sequence, + /// decreasing it by the number of items successfully skipped. + /// + /// This is equivalent to generating the same number of items then immediately + /// discarding them, except it may avoid the overhead of actually + /// materializing them. + /// + /// As soon as the producer has run out of items, all subsequent calls to + /// this method stop decrementing `remainder` and return false. + /// + /// The default implementation of this method calls `generate(into:)` with + /// a small temporary buffer, immediately discarding all generated items. + /// Conforming types are encouraged to replace this default approach + /// with a more efficient implementation whenever it is possible to do so. + /// + /// ### Error handling + /// + /// This method throws an error to indicate a failure while trying to skip + /// the upcoming next item in the sequence. Failure may happen midway through + /// skipping a batch of items, in which case the `remainder` will still be + /// decremented by the number of elements that were successfully skipped + /// before encountering the problem. + /// + /// - Parameter remainder: The maximum number of items remaining to skip. + /// This method decrements this value by the number of items it + /// successfully skipped before returning. + /// - Returns: A boolean value indicating whether the operation was able to + /// satisfy the request at least partially without hitting the end of the + /// underlying consumable sequence. + @inlinable + @_lifetime(self: copy self) + public mutating func skip( + upTo n: inout Int + ) throws(ProducerError) -> Bool { + precondition(n >= 0, "Cannot skip a negative number of elements") + guard n > 0 else { return true } + let span = drainNext(maximumCount: n) + let success = span.count > 0 + n &-= span.count + return success + } +} + +#endif diff --git a/Sources/ContainersPreview/Protocols/Producer.swift b/Sources/ContainersPreview/Protocols/Producer.swift new file mode 100644 index 00000000..59f17608 --- /dev/null +++ b/Sources/ContainersPreview/Protocols/Producer.swift @@ -0,0 +1,271 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2024 - 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + +/// A type that supplies the values of a generative sequence by populating +/// a client-supplied series of `OutputSpan` instances. "Generative" sequences +/// transfer the ownership of items they produce to their clients, rather than +/// merely providing borrowing access to them. A `Producer` instance represents +/// an ongoing iteration over such a generative sequence. +@available(SwiftStdlib 5.0, *) +public protocol Producer: ~Copyable, ~Escapable { + /// The type of the items that this producer generates. + associatedtype Element: ~Copyable + + /// The error that this producer may throw, or `Never` if this producer + /// always succeeds. + associatedtype ProducerError: Error = Never + + /// A value less than or equal to the number of remaining items that this + /// producer is able to generate until it reaches its end. + /// + /// The default implementation returns 0. If you provide your own + /// implementation, make sure to compute the value nondestructively. + var underestimatedCount: Int { get } + + /// Generate the next batch of items into the supplied output span instance, + /// which must have room for at least one new element. + /// + /// Repeatedly calling this method produces, in order, all the elements of the + /// underlying generative sequence. As soon as the sequence has run out of + /// elements, all subsequent calls return false without appending any new + /// items to their target. This method is not guaranteed to fully populate the + /// given output span, but it always appends at least one item until the end + /// of the underlying generative sequence. + /// + /// The ownership of all generated elements is transferred to the caller of + /// this method -- it can arbitrarily store, mutate, consume or discard them + /// as needed, even across invocations of this method, or after the producer + /// is destroyed. + /// + /// The returned Boolean value can be used to easily determine if the + /// method was able to make progress towards filling `target` without hitting + /// the end of the underlying sequence. + /// + /// If `target` is a full span, this method is allowed to unconditionally + /// return true. Passing an empty span is not a reliable way to test if the + /// producer has reached its end. (Some producers may only be able to detect + /// that they are finished while trying to generate the next item.) + /// + /// ### Error handling + /// + /// This method throws an error to indicate a failure while trying to generate + /// the upcoming next item in the sequence. Failure may happen midway through + /// populating `target`, in which case the output span will still gain + /// new items despite the error. (Those items are successfully + /// generated, and do not necessarilly need to be discarded.) + /// + /// This protocol does not specify the meaning of a failure, or the + /// precise state of the iterator after an error is thrown; however, the + /// error must not trigger runtime traps in subsequent attempts at iteration. + /// (After a failure, conforming types may choose to produce new items, or + /// signal the end of the iteration, or throw another error, which may or may + /// not match the first.) + /// + /// Absent of more specific information, generic code should stop + /// iterating, discard the producer and rethrow the error when it encounters + /// a failure. Generic code is encouraged to preserve the items that got + /// successfully produced before the throw (including ones appended by + /// the call that ultimately ended in failure); however, whether this is + /// possible (or desirable) ultimately depends on the specific problem that + /// the algorithm is solving. + /// + /// - Parameter target: An output span ready to take newly generated items. + /// - Returns: A boolean value indicating whether the operation was able to + /// append at least one item to the supplied output span without hitting + /// the end of the underlying sequence. + @_lifetime(target: copy target) + @_lifetime(self: copy self) + @discardableResult + mutating func generate( + into target: inout OutputSpan + ) throws(ProducerError) -> Bool + + /// Skip at most the given number items in the underlying generative sequence, + /// decreasing it by the number of items successfully skipped. + /// + /// This is equivalent to generating the same number of items then immediately + /// discarding them, except it may avoid the overhead of actually + /// materializing them. + /// + /// As soon as the producer has run out of items, all subsequent calls to + /// this method stop decrementing `n` and return false. + /// + /// The default implementation of this method calls `generate(into:)` with + /// a small temporary buffer, immediately discarding all generated items. + /// Conforming types are encouraged to replace this default approach + /// with a more efficient implementation whenever it is possible to do so. + /// + /// ### Error handling + /// + /// This method throws an error to indicate a failure while trying to skip + /// the upcoming next item in the sequence. Failure may happen midway through + /// skipping a batch of items, in which case `n` will still be + /// decremented by the number of elements that were successfully skipped + /// before encountering the problem. + /// + /// - Parameter n: The maximum number of items remaining to skip. This + /// must be greater than zero. This method decrements this value by the + /// number of items it successfully skipped before returning. + /// - Returns: A boolean value indicating whether the operation was able to + /// skip at least one item without hitting the end of the underlying + /// sequence. + @_lifetime(self: copy self) + mutating func skip(upTo n: inout Int) throws(ProducerError) -> Bool + + /// Generate and return the next element in the underlying generative + /// sequence. + /// + /// Repeatedly calling this method produces, in order, all the elements of the + /// underlying generative sequence. As soon as the sequence has run out of + /// elements, all subsequent calls return `nil`. + /// + /// The ownership of all generated elements is transferred to the + /// caller of this method -- it can arbitrarily store, mutate, + /// consume or discard them as needed, even across invocations of this method, + /// or after the producer is destroyed. + /// + /// This method throws an error to indicate a failure. This protocol does not + /// specify the meaning of such errors, or the precise state of the + /// iterator after an error is thrown; however, the error must not trigger + /// runtime traps in subsequent attempts at iteration. + /// (Conforming types may choose to produce new items, or signal the end of + /// the iteration, or throw another error, which may or may not match the + /// first.) Absent of more specific information, generic code should stop + /// iterating, discard the producer and rethrow the error when it encounters + /// a failure. + /// + /// The default implementation of this method calls `generate(into:)` with + /// a temporary output span with room for a single item, and returns the + /// resulting contents. This often produces satisfactory results; but the + /// protocol allows conformances to customize this entry point if they believe + /// it to be necessary (for example, if they can take shortcuts that aren't + /// available in the bulk method). Custom implementations of `generateNext()` + /// must produce results that are indistinguishable from the default + /// implementation, but they may exhibit observably different performance + /// metrics. + @_lifetime(self: copy self) + mutating func generateNext() throws(ProducerError) -> Element? +} + +@available(SwiftStdlib 5.0, *) +extension Producer where Self: ~Copyable & ~Escapable { + /// A value less than or equal to the number of remaining items that this + /// producer is able to generate until it reaches its end. + /// + /// The default implementation returns 0. If you provide your own + /// implementation, make sure to compute the value nondestructively. + @inlinable + @inline(__always) + public var underestimatedCount: Int { 0 } + + /// Skip at most the given number items in the underlying generative sequence, + /// decreasing it by the number of items successfully skipped. + /// + /// This is equivalent to generating the same number of items then immediately + /// discarding them, except it may avoid the overhead of actually + /// materializing them. + /// + /// As soon as the producer has run out of items, all subsequent calls to + /// this method stop decrementing `n` and return false. + /// + /// The default implementation of this method calls `generate(into:)` with + /// a small temporary buffer, immediately discarding all generated items. + /// Conforming types are encouraged to replace this default approach + /// with a more efficient implementation whenever it is possible to do so. + /// + /// ### Error handling + /// + /// This method throws an error to indicate a failure while trying to skip + /// the upcoming next item in the sequence. Failure may happen midway through + /// skipping a batch of items, in which case `n` will still be + /// decremented by the number of elements that were successfully skipped + /// before encountering the problem. + /// + /// - Parameter n: The maximum number of items remaining to skip. This + /// must be greater than zero. This method decrements this value by the + /// number of items it successfully skipped before returning. + /// - Returns: A boolean value indicating whether the operation was able to + /// skip at least one item without hitting the end of the underlying + /// sequence. + @inlinable + @_lifetime(self: copy self) + public mutating func skip(upTo n: inout Int) throws(ProducerError) -> Bool { + precondition(n > 0, "Cannot skip fewer than one item") + let maxBufferSize = 8 + return try withTemporaryOutputSpan( + of: Element.self, capacity: Swift.min(maxBufferSize, n) + ) { span throws(ProducerError) in + defer { n &-= span.count } + return try self.generate(into: &span) + } + } + + /// Generate and return the next element in the underlying generative + /// sequence. + /// + /// Repeatedly calling this method produces, in order, all the elements of the + /// underlying generative sequence. As soon as the sequence has run out of + /// elements, all subsequent calls return `nil`. + /// + /// The ownership of all generated elements is transferred to the + /// caller of this method -- it can arbitrarily store, mutate, + /// consume or discard them as needed, even across invocations of this method, + /// or after the producer is destroyed. + /// + /// This method throws an error to indicate a failure. This protocol does not + /// specify the meaning of such errors, or the precise state of the + /// iterator after an error is thrown; however, the error must not trigger + /// runtime traps in subsequent attempts at iteration. + /// (Conforming types may choose to produce new items, or signal the end of + /// the iteration, or throw another error, which may or may not match the + /// first.) Absent of more specific information, generic code should stop + /// iterating, discard the producer and rethrow the error when it encounters + /// a failure. + /// + /// The default implementation of this method calls `generate(into:)` with + /// a temporary output span with room for a single item, and returns the + /// resulting contents. This often produces satisfactory results; but the + /// protocol allows conformances to customize this entry point if they believe + /// it to be necessary (for example, if they can take shortcuts that aren't + /// available in the bulk method). Custom implementations of `generateNext()` + /// must produce results that are indistinguishable from the default + /// implementation, but they may exhibit observably different performance + /// metrics. + @inlinable + @_lifetime(self: copy self) + public mutating func generateNext() throws(ProducerError) -> Element? { + try withUnsafeTemporaryAllocation( + of: Element.self, capacity: 1 + ) { buffer throws(ProducerError) in + var span = OutputSpan(buffer: buffer, initializedCount: 0) + guard try self.generate(into: &span) else { return nil } + return span.removeLast() + } + } +} + +@available(SwiftStdlib 5.0, *) +extension Producer where Self: ~Copyable & ~Escapable { + /// Returns true if the producer has no more elements, consuming it in + /// the process. This is implemented by checking if it is possible to + /// skip one item. + /// + /// This is useful in preconditions. + @inlinable + public consuming func _isAtEnd() throws(ProducerError) -> Bool { + var c = 1 + return try !skip(upTo: &c) + } +} + +#endif diff --git a/Sources/ContainersPreview/Ref.swift b/Sources/ContainersPreview/Types/Borrow.swift similarity index 53% rename from Sources/ContainersPreview/Ref.swift rename to Sources/ContainersPreview/Types/Borrow.swift index ab7edecc..f909262b 100644 --- a/Sources/ContainersPreview/Ref.swift +++ b/Sources/ContainersPreview/Types/Borrow.swift @@ -12,17 +12,25 @@ #if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW import Builtin +@available(SwiftStdlib 5.0, *) @frozen @safe -public struct Ref: Copyable, ~Escapable { +public struct Borrow: Copyable, ~Escapable { @usableFromInline - package let _pointer: UnsafePointer + package let _pointer: UnsafePointer -#if compiler(>=6.2) && FIXME @_lifetime(borrow value) @_alwaysEmitIntoClient @_transparent - public init(_ value: borrowing @_addressable T) { + internal init(_borrowing value: borrowing @_addressable Target) { + unsafe _pointer = UnsafePointer(Builtin.unprotectedAddressOfBorrow(value)) + } + +#if compiler(>=6.3) // rdar://161844406 (https://github.com/swiftlang/swift/pull/84748) + @_lifetime(borrow value) + @_alwaysEmitIntoClient + @_transparent + public init(_ value: borrowing @_addressable Target) { unsafe _pointer = UnsafePointer(Builtin.unprotectedAddressOfBorrow(value)) } #endif @@ -31,7 +39,7 @@ public struct Ref: Copyable, ~Escapable { @_alwaysEmitIntoClient @_transparent public init( - unsafeAddress: UnsafePointer, + unsafeAddress: UnsafePointer, borrowing owner: borrowing Owner ) { unsafe _pointer = unsafeAddress @@ -41,18 +49,35 @@ public struct Ref: Copyable, ~Escapable { @_alwaysEmitIntoClient @_transparent public init( - unsafeAddress: UnsafePointer, + unsafeAddress: UnsafePointer, copying owner: borrowing Owner ) { unsafe _pointer = unsafeAddress } @_alwaysEmitIntoClient - public subscript() -> T { + public subscript() -> Target { @_transparent unsafeAddress { unsafe _pointer } } } + +extension Optional where Wrapped: ~Copyable /* FIXME: ~Escapable */ { + @available(SwiftStdlib 5.0, *) + @_lifetime(borrow self) + @_addressableSelf + public func borrow() -> Borrow? { + if self == nil { + return nil + } + + let pointer = unsafe UnsafePointer( + Builtin.unprotectedAddressOfBorrow(self) + ) + + return unsafe Borrow(unsafeAddress: pointer, borrowing: self) + } +} #endif diff --git a/Sources/ContainersPreview/Box.swift b/Sources/ContainersPreview/Types/Box.swift similarity index 91% rename from Sources/ContainersPreview/Box.swift rename to Sources/ContainersPreview/Types/Box.swift index f486879b..a3099914 100644 --- a/Sources/ContainersPreview/Box.swift +++ b/Sources/ContainersPreview/Types/Box.swift @@ -94,8 +94,8 @@ extension Box where T: ~Copyable { @_alwaysEmitIntoClient @_transparent @_lifetime(immortal) - public consuming func leak() -> Mut { - let result = unsafe Mut(unsafeImmortalAddress: _pointer) + public consuming func leak() -> Inout { + let result = unsafe Inout(unsafeImmortalAddress: _pointer) discard self return result } @@ -103,11 +103,12 @@ extension Box where T: ~Copyable { #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW /// Return a borrowing reference to the contents of this box. + @available(SwiftStdlib 5.0, *) @_alwaysEmitIntoClient @_transparent @_lifetime(borrow self) - public func borrow() -> Ref { - unsafe Ref(unsafeAddress: UnsafePointer(_pointer), borrowing: self) + public func borrow() -> Borrow { + unsafe Borrow(unsafeAddress: UnsafePointer(_pointer), borrowing: self) } #endif @@ -116,8 +117,8 @@ extension Box where T: ~Copyable { @_alwaysEmitIntoClient @_transparent @_lifetime(&self) - public mutating func mutate() -> Mut { - unsafe Mut(unsafeAddress: _pointer, mutating: &self) + public mutating func mutate() -> Inout { + unsafe Inout(unsafeAddress: _pointer, mutating: &self) } #endif } diff --git a/Sources/ContainersPreview/Mut.swift b/Sources/ContainersPreview/Types/Inout.swift similarity index 56% rename from Sources/ContainersPreview/Mut.swift rename to Sources/ContainersPreview/Types/Inout.swift index 983b6314..a7526630 100644 --- a/Sources/ContainersPreview/Mut.swift +++ b/Sources/ContainersPreview/Types/Inout.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors +// Copyright (c) 2024 - 2026 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information @@ -12,17 +12,15 @@ #if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW import Builtin -// FIXME: A better name for the generic argument. - /// A safe mutable reference allowing in-place mutation to an exclusive value. /// -/// In order to get an instance of a `Mut`, one must have exclusive access -/// to the instance of `T`. This is achieved through the 'inout' operator, '&'. +/// In order to get an instance of a `Inout`, one must have exclusive access +/// to the instance of `Target`. This is achieved through the 'inout' operator, '&'. @frozen @safe -public struct Mut: ~Copyable, ~Escapable { +public struct Inout: ~Copyable, ~Escapable { @usableFromInline - package let _pointer: UnsafeMutablePointer + package let _pointer: UnsafeMutablePointer /// Initializes an instance of 'Mut' extending the exclusive access of the /// passed instance. @@ -30,8 +28,8 @@ public struct Mut: ~Copyable, ~Escapable { /// - Parameter instance: The desired instance to get a mutable reference to. @_alwaysEmitIntoClient @_transparent - public init(_ instance: inout T) { - unsafe _pointer = UnsafeMutablePointer(Builtin.unprotectedAddressOf(&instance)) + public init(_ instance: inout Target) { + unsafe _pointer = UnsafeMutablePointer(Builtin.unprotectedAddressOf(&instance)) } /// Unsafely initializes an instance of 'Mut' using the given 'unsafeAddress' @@ -39,7 +37,7 @@ public struct Mut: ~Copyable, ~Escapable { /// argument. /// /// - Parameter unsafeAddress: The address to use to mutably reference an - /// instance of type 'T'. + /// instance of type 'Target'. /// - Parameter owner: The owning instance that this 'Mut' instance's /// lifetime is based on. @unsafe @@ -47,7 +45,7 @@ public struct Mut: ~Copyable, ~Escapable { @_transparent @_lifetime(&owner) public init( - unsafeAddress: UnsafeMutablePointer, + unsafeAddress: UnsafeMutablePointer, mutating owner: inout Owner ) { unsafe _pointer = unsafeAddress @@ -58,33 +56,64 @@ public struct Mut: ~Copyable, ~Escapable { /// lifetime is immortal. /// /// - Parameter unsafeImmortalAddress: The address to use to mutably reference - /// an immortal instance of type 'T'. + /// an immortal instance of type 'Target'. @_lifetime(immortal) @unsafe @_alwaysEmitIntoClient @_transparent public init( - unsafeImmortalAddress: UnsafeMutablePointer + unsafeImmortalAddress: UnsafeMutablePointer ) { unsafe _pointer = unsafeImmortalAddress } } -extension Mut where T: ~Copyable { +extension Inout where Target: ~Copyable { /// Dereferences the mutable reference allowing for in-place reads and writes /// to the underlying instance. @_alwaysEmitIntoClient - public subscript() -> T { + public subscript() -> Target { @_transparent unsafeAddress { - unsafe UnsafePointer(_pointer) + unsafe UnsafePointer(_pointer) } - + @_transparent - @_lifetime(self: copy self) unsafeMutableAddress { unsafe _pointer } } } + + +extension Inout where Target: ~Copyable { + package func _withUnsafeTarget( + _ body: (inout Target) throws(E) -> R + ) throws(E) -> R { + try body(&_pointer.pointee) + } +} + + +extension Optional where Wrapped: ~Copyable /* FIXME: ~Escapable */ { + @_lifetime(&self) + @_alwaysEmitIntoClient + public mutating func mutate() -> Inout? { + if self == nil { + return nil + } + let pointer = unsafe UnsafeMutablePointer( + Builtin.unprotectedAddressOf(&self)) + return unsafe Inout(unsafeAddress: pointer, mutating: &self) + } + + @_lifetime(&self) + @_alwaysEmitIntoClient + @_transparent + public mutating func insert(_ value: consuming Wrapped) -> Inout { + self = .some(value) + return mutate()._consumingUnsafelyUnwrap() + } + +} #endif diff --git a/Sources/ContainersPreview/InputSpan.swift b/Sources/ContainersPreview/Types/InputSpan.swift similarity index 80% rename from Sources/ContainersPreview/InputSpan.swift rename to Sources/ContainersPreview/Types/InputSpan.swift index 7560041c..0d9b125f 100644 --- a/Sources/ContainersPreview/InputSpan.swift +++ b/Sources/ContainersPreview/Types/InputSpan.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors +// Copyright (c) 2024 - 2026 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information @@ -33,7 +33,9 @@ public struct InputSpan: ~Copyable, ~Escapable { deinit { if _count > 0 { let c = _count - unsafe _first().withMemoryRebound(to: Element.self, capacity: _count) { + unsafe _unsafeRawAddressOfSlot(uncheckedOffset: 0).withMemoryRebound( + to: Element.self, capacity: _count + ) { _ = unsafe $0.deinitialize(count: c) } } @@ -59,15 +61,6 @@ extension InputSpan where Element: ~Copyable { unsafe _pointer.unsafelyUnwrapped } - @_alwaysEmitIntoClient - @_transparent - @unsafe - internal func _first() -> UnsafeMutableRawPointer { - // NOTE: `_pointer` must be known to be not-nil. - let offset = (capacity &- _count) &* MemoryLayout.stride - return unsafe _start().advanced(by: offset) - } - @unsafe @_alwaysEmitIntoClient @_transparent @@ -82,10 +75,10 @@ extension InputSpan where Element: ~Copyable { @_alwaysEmitIntoClient @_transparent internal func _unsafeAddressOfElement( - unchecked index: Index + uncheckedOffset offset: Index ) -> UnsafeMutablePointer { _unsafeRawAddressOfSlot( - uncheckedOffset: index + uncheckedOffset: offset ).assumingMemoryBound(to: Element.self) } } @@ -251,13 +244,13 @@ extension InputSpan where Element: ~Copyable { public subscript(_ index: Index) -> Element { unsafeAddress { precondition(indices.contains(index), "Index out of bounds") - return unsafe UnsafePointer(_unsafeAddressOfElement(unchecked: index)) + return unsafe UnsafePointer(_unsafeAddressOfElement(uncheckedOffset: index)) } @_lifetime(self: copy self) unsafeMutableAddress { precondition(indices.contains(index), "Index out of bounds") - return unsafe _unsafeAddressOfElement(unchecked: index) + return unsafe _unsafeAddressOfElement(uncheckedOffset: index) } } @@ -272,11 +265,11 @@ extension InputSpan where Element: ~Copyable { @_alwaysEmitIntoClient public subscript(unchecked index: Index) -> Element { unsafeAddress { - unsafe UnsafePointer(_unsafeAddressOfElement(unchecked: index)) + unsafe UnsafePointer(_unsafeAddressOfElement(uncheckedOffset: index)) } @_lifetime(self: copy self) unsafeMutableAddress { - unsafe _unsafeAddressOfElement(unchecked: index) + unsafe _unsafeAddressOfElement(uncheckedOffset: index) } } @@ -303,8 +296,8 @@ extension InputSpan where Element: ~Copyable { @_lifetime(self: copy self) public mutating func swapAt(unchecked i: Index, unchecked j: Index) { guard i != j else { return } - let pi = unsafe _unsafeAddressOfElement(unchecked: i) - let pj = unsafe _unsafeAddressOfElement(unchecked: j) + let pi = unsafe _unsafeAddressOfElement(uncheckedOffset: i) + let pj = unsafe _unsafeAddressOfElement(uncheckedOffset: j) let temporary = unsafe pi.move() unsafe pi.initialize(to: pj.move()) unsafe pj.initialize(to: consume temporary) @@ -330,9 +323,9 @@ extension InputSpan where Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(self: copy self) public mutating func removeFirst() -> Element { - precondition(!isEmpty, "InputSpan underflow") + precondition(_count > 0, "InputSpan underflow") defer { _count &-= 1 } - return _unsafeAddressOfElement(unchecked: 0).move() + return _unsafeAddressOfElement(uncheckedOffset: 0).move() } /// Remove the last N elements of this span, returning the memory they occupy @@ -342,7 +335,7 @@ extension InputSpan where Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(self: copy self) public mutating func removeFirst(_ k: Int) { - precondition(k >= 0, "Can't remove a negative number of elements") + precondition(k >= 0, "Cannot remove a negative number of elements") precondition(k <= _count, "InputSpan underflow") unsafe _unsafeRawAddressOfSlot( uncheckedOffset: 0 @@ -351,6 +344,21 @@ extension InputSpan where Element: ~Copyable { } _count &-= k } + + /// Removes and returns the first element of this input span, if it exists. + /// + /// - Returns: The first element of the original span if it wasn't empty; + /// otherwise, `nil`. + /// + /// - Complexity: O(1) + @inlinable + public mutating func popFirst() -> Element? { + guard _count > 0 else { return nil } + let result = unsafe _unsafeAddressOfElement(uncheckedOffset: 0).move() + _count &-= 1 + return result + } + /// Remove all this span's elements and return its memory /// to the uninitialized state. @@ -364,10 +372,27 @@ extension InputSpan where Element: ~Copyable { } } -//MARK: Bulk append functions +//MARK: Bulk prepend functions @available(SwiftStdlib 5.0, *) -extension InputSpan { +extension InputSpan where Element: ~Copyable { + @_alwaysEmitIntoClient + @_lifetime(self: copy self) + public mutating func prepend(moving source: UnsafeMutableBufferPointer) { + self.withUnsafeMutableBufferPointer { dst, dstCount in + let dstEnd = dst.count &- dstCount + let dstStart = dstEnd - source.count + precondition(dstStart >= 0, "InputSpan capacity overflow") + dst + ._extracting(uncheckedFrom: dstStart, to: dstEnd) + .moveInitializeAll(fromContentsOf: source) + dstCount &+= source.count + } + } +} + +@available(SwiftStdlib 5.0, *) +extension InputSpan /* where Element: Copyable */ { /// Repeatedly append an element to this span. @_alwaysEmitIntoClient @_lifetime(self: copy self) @@ -380,6 +405,30 @@ extension InputSpan { } } +@available(SwiftStdlib 5.0, *) +extension InputSpan /* where Element: Copyable */ { + @inlinable + package mutating func prepend(copying source: UnsafeBufferPointer) { + self.withUnsafeMutableBufferPointer { dst, dstCount in + let dstEnd = dst.count &- dstCount + let dstStart = dstEnd - source.count + precondition(dstStart >= 0, "InputSpan capacity overflow") + dst + ._extracting(uncheckedFrom: dstStart, to: dstEnd) + .initializeAll(fromContentsOf: source) + dstCount &+= source.count + } + } + + @inlinable + package mutating func prepend(copying source: borrowing Span) { + source.withUnsafeBufferPointer { src in + self.prepend(copying: src) + } + } +} + + @available(SwiftStdlib 5.0, *) extension InputSpan where Element: ~Copyable { /// Borrow the underlying initialized memory for read-only access. @@ -473,4 +522,38 @@ extension InputSpan where Element: ~Copyable { } } +@available(SwiftStdlib 5.0, *) +extension InputSpan where Element: ~Copyable { + @_alwaysEmitIntoClient + @_lifetime(&self) + public mutating func consumePrefix(upTo n: Int) -> InputSpan { + precondition(n >= 0, "Cannot consume a negative number of elements") + let c = Swift.min(n, self.count) + + let buffer = unsafe _unsafeRawAddressOfSlot( + uncheckedOffset: 0 + ).withMemoryRebound(to: Element.self, capacity: c) { start in + UnsafeMutableBufferPointer(start: start, count: c) + } + _count -= c + return _overrideLifetime( + InputSpan(buffer: buffer, initializedCount: c), + mutating: &self) + } +} + +@available(SwiftStdlib 5.0, *) +internal func withTemporaryInputSpan( + of type: Element.Type, + capacity: Int, + _ body: (inout InputSpan) throws(E) -> R +) throws(E) -> R { + try _withUnsafeTemporaryAllocation( + of: Element.self, capacity: capacity + ) { buffer throws(E) in + var span = InputSpan(buffer: buffer, initializedCount: 0) + return try body(&span) + } +} + #endif diff --git a/Sources/ContainersPreview/Shared.swift b/Sources/ContainersPreview/Types/Shared.swift similarity index 100% rename from Sources/ContainersPreview/Shared.swift rename to Sources/ContainersPreview/Types/Shared.swift diff --git a/Sources/DequeModule/CMakeLists.txt b/Sources/DequeModule/CMakeLists.txt index f1c8cae8..8f687bcb 100644 --- a/Sources/DequeModule/CMakeLists.txt +++ b/Sources/DequeModule/CMakeLists.txt @@ -14,7 +14,8 @@ else() add_library(DequeModule ${COLLECTIONS_DEQUE_SOURCES}) target_link_libraries(DequeModule PRIVATE - InternalCollectionsUtilities) + InternalCollectionsUtilities + ContainersPreview) set_target_properties(DequeModule PROPERTIES INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY}) @@ -23,20 +24,48 @@ else() endif() target_sources(${module_name} PRIVATE - "Deque+Codable.swift" - "Deque+Collection.swift" - "Deque+CustomReflectable.swift" - "Deque+Descriptions.swift" - "Deque+Equatable.swift" - "Deque+ExpressibleByArrayLiteral.swift" - "Deque+Extras.swift" - "Deque+Hashable.swift" - "Deque+Testing.swift" - "Deque._Storage.swift" - "Deque._UnsafeHandle.swift" - "Deque.swift" - "_DequeBuffer.swift" - "_DequeBufferHeader.swift" + "_UnsafeDequeSegments.swift" + "_UnsafeDequeHandle.swift" "_DequeSlot.swift" - "_UnsafeWrappedBuffer.swift" + "RigidDeque/RigidDeque.swift" + "RigidDeque/RigidDeque+Append.swift" + "RigidDeque/RigidDeque+Consumption.swift" + "RigidDeque/RigidDeque+Container.swift" + "RigidDeque/RigidDeque+Descriptions.swift" + "RigidDeque/RigidDeque+Equatable.swift" + "RigidDeque/RigidDeque+Experimental.swift" + "RigidDeque/RigidDeque+Hashable.swift" + "RigidDeque/RigidDeque+Initializers.swift" + "RigidDeque/RigidDeque+Insertions.swift" + "RigidDeque/RigidDeque+Prepend.swift" + "RigidDeque/RigidDeque+Removals.swift" + "RigidDeque/RigidDeque+Replacements.swift" + "RigidDeque/RigidDeque+Testing.swift" + "UniqueDeque/UniqueDeque.swift" + "UniqueDeque/UniqueDeque+Append.swift" + "UniqueDeque/UniqueDeque+Consumption.swift" + "UniqueDeque/UniqueDeque+Container.swift" + "UniqueDeque/UniqueDeque+Descriptions.swift" + "UniqueDeque/UniqueDeque+Equatable.swift" + "UniqueDeque/UniqueDeque+Experimental.swift" + "UniqueDeque/UniqueDeque+Hashable.swift" + "UniqueDeque/UniqueDeque+Initializers.swift" + "UniqueDeque/UniqueDeque+Insertions.swift" + "UniqueDeque/UniqueDeque+Prepend.swift" + "UniqueDeque/UniqueDeque+Removals.swift" + "UniqueDeque/UniqueDeque+Replacements.swift" + "Deque/_DequeBuffer.swift" + "Deque/Deque+Collection.swift" + "Deque/Deque+CustomReflectable.swift" + "Deque/Deque.swift" + "Deque/Deque+Hashable.swift" + "Deque/_DequeBufferHeader.swift" + "Deque/Deque+Codable.swift" + "Deque/Deque+Testing.swift" + "Deque/Deque._UnsafeHandle.swift" + "Deque/Deque+Descriptions.swift" + "Deque/Deque+Extras.swift" + "Deque/Deque+ExpressibleByArrayLiteral.swift" + "Deque/Deque+Equatable.swift" + "Deque/Deque._Storage.swift" ) diff --git a/Sources/DequeModule/Deque+Codable.swift b/Sources/DequeModule/Deque/Deque+Codable.swift similarity index 100% rename from Sources/DequeModule/Deque+Codable.swift rename to Sources/DequeModule/Deque/Deque+Codable.swift diff --git a/Sources/DequeModule/Deque+Collection.swift b/Sources/DequeModule/Deque/Deque+Collection.swift similarity index 97% rename from Sources/DequeModule/Deque+Collection.swift rename to Sources/DequeModule/Deque/Deque+Collection.swift index 8f4fa8b6..1cbfcde5 100644 --- a/Sources/DequeModule/Deque+Collection.swift +++ b/Sources/DequeModule/Deque/Deque+Collection.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors +// Copyright (c) 2021 - 2026 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information @@ -701,7 +701,7 @@ extension Deque: RangeReplaceableCollection { _storage.update { target in target.uncheckedAppend(next) let gaps = target.availableSegments() - target.count += gaps.initialize(fromPrefixOf: &it) + target.count += gaps.initialize(copyingPrefixOf: &it) } } } @@ -735,7 +735,7 @@ extension Deque: RangeReplaceableCollection { _storage.ensureUnique(minimumCapacity: count + c) _storage.update { target in let gaps = target.availableSegments().prefix(c) - gaps.initialize(from: newElements) + gaps.initialize(copying: newElements) target.count += c } } @@ -757,8 +757,7 @@ extension Deque: RangeReplaceableCollection { /// this reduces the complexity to amortized O(1). @inlinable public mutating func insert(_ newElement: Element, at index: Int) { - precondition(index >= 0 && index <= count, - "Can't insert element at invalid index") + precondition(index >= 0 && index <= count, "Index out of bounds") _storage.ensureUnique(minimumCapacity: count + 1) _storage.update { target in if index == 0 { @@ -797,8 +796,7 @@ extension Deque: RangeReplaceableCollection { contentsOf newElements: __owned some Collection, at index: Int ) { - precondition(index >= 0 && index <= count, - "Can't insert elements at an invalid index") + precondition(index >= 0 && index <= count, "Index out of bounds") let newCount = newElements.count _storage.ensureUnique(minimumCapacity: count + newCount) _storage.update { target in @@ -865,8 +863,8 @@ extension Deque: RangeReplaceableCollection { @inlinable public mutating func _customRemoveLast(_ n: Int) -> Bool { - precondition(n >= 0, "Can't remove a negative number of elements") - precondition(n <= count, "Can't remove more elements than there are in the Collection") + precondition(n >= 0, "Cannot remove a negative number of elements") + precondition(n <= count, "Cannot remove more elements than there are in the Collection") _storage.ensureUnique() _storage.update { $0.uncheckedRemoveLast(n) } return true @@ -898,8 +896,8 @@ extension Deque: RangeReplaceableCollection { /// O(`count`). @inlinable public mutating func removeFirst(_ n: Int) { - precondition(n >= 0, "Can't remove a negative number of elements") - precondition(n <= count, "Can't remove more elements than there are in the Collection") + precondition(n >= 0, "Cannot remove a negative number of elements") + precondition(n <= count, "Cannot remove more elements than there are in the Collection") _storage.ensureUnique() return _storage.update { $0.uncheckedRemoveFirst(n) } } diff --git a/Sources/DequeModule/Deque+CustomReflectable.swift b/Sources/DequeModule/Deque/Deque+CustomReflectable.swift similarity index 100% rename from Sources/DequeModule/Deque+CustomReflectable.swift rename to Sources/DequeModule/Deque/Deque+CustomReflectable.swift diff --git a/Sources/DequeModule/Deque+Descriptions.swift b/Sources/DequeModule/Deque/Deque+Descriptions.swift similarity index 100% rename from Sources/DequeModule/Deque+Descriptions.swift rename to Sources/DequeModule/Deque/Deque+Descriptions.swift diff --git a/Sources/DequeModule/Deque+Equatable.swift b/Sources/DequeModule/Deque/Deque+Equatable.swift similarity index 100% rename from Sources/DequeModule/Deque+Equatable.swift rename to Sources/DequeModule/Deque/Deque+Equatable.swift diff --git a/Sources/DequeModule/Deque+ExpressibleByArrayLiteral.swift b/Sources/DequeModule/Deque/Deque+ExpressibleByArrayLiteral.swift similarity index 100% rename from Sources/DequeModule/Deque+ExpressibleByArrayLiteral.swift rename to Sources/DequeModule/Deque/Deque+ExpressibleByArrayLiteral.swift diff --git a/Sources/DequeModule/Deque+Extras.swift b/Sources/DequeModule/Deque/Deque+Extras.swift similarity index 98% rename from Sources/DequeModule/Deque+Extras.swift rename to Sources/DequeModule/Deque/Deque+Extras.swift index 850e493f..e4b36ba0 100644 --- a/Sources/DequeModule/Deque+Extras.swift +++ b/Sources/DequeModule/Deque/Deque+Extras.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors +// Copyright (c) 2021 - 2026 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information @@ -148,7 +148,7 @@ extension Deque { _storage.ensureUnique(minimumCapacity: count + c) _storage.update { target in let gaps = target.availableSegments().suffix(c) - gaps.initialize(from: newElements) + gaps.initialize(copying: newElements) target.count += c target.startSlot = target.slot(target.startSlot, offsetBy: -c) } diff --git a/Sources/DequeModule/Deque+Hashable.swift b/Sources/DequeModule/Deque/Deque+Hashable.swift similarity index 100% rename from Sources/DequeModule/Deque+Hashable.swift rename to Sources/DequeModule/Deque/Deque+Hashable.swift diff --git a/Sources/DequeModule/Deque+Testing.swift b/Sources/DequeModule/Deque/Deque+Testing.swift similarity index 93% rename from Sources/DequeModule/Deque+Testing.swift rename to Sources/DequeModule/Deque/Deque+Testing.swift index 0136886b..a101b001 100644 --- a/Sources/DequeModule/Deque+Testing.swift +++ b/Sources/DequeModule/Deque/Deque+Testing.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors +// Copyright (c) 2021 - 2026 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information @@ -36,8 +36,8 @@ extension Deque { /// /// This property isn't intended to be used outside of `Deque`'s own test /// target. - @_spi(Testing) - public var _capacity: Int { + @usableFromInline + package var _capacity: Int { _storage.capacity } @@ -47,16 +47,16 @@ extension Deque { /// /// This property isn't intended to be used outside of `Deque`'s own test /// target. - @_spi(Testing) - public var _startSlot: Int { + @usableFromInline + package var _startSlot: Int { _storage.startSlot.position } /// Constructs a deque instance of the specified contents and layout. Exposed /// as public to allow exhaustive input/output tests for `Deque`'s members. /// This isn't intended to be used outside of `Deque`'s own test target. - @_spi(Testing) - public init( + @usableFromInline + package init( _capacity capacity: Int, startSlot: Int, contents: some Sequence diff --git a/Sources/DequeModule/Deque._Storage.swift b/Sources/DequeModule/Deque/Deque._Storage.swift similarity index 100% rename from Sources/DequeModule/Deque._Storage.swift rename to Sources/DequeModule/Deque/Deque._Storage.swift diff --git a/Sources/DequeModule/Deque._UnsafeHandle.swift b/Sources/DequeModule/Deque/Deque._UnsafeHandle.swift similarity index 97% rename from Sources/DequeModule/Deque._UnsafeHandle.swift rename to Sources/DequeModule/Deque/Deque._UnsafeHandle.swift index 8302b635..263e5c40 100644 --- a/Sources/DequeModule/Deque._UnsafeHandle.swift +++ b/Sources/DequeModule/Deque/Deque._UnsafeHandle.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors +// Copyright (c) 2021 - 2026 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information @@ -172,7 +172,7 @@ extension Deque._UnsafeHandle { extension Deque._UnsafeHandle { @inlinable - internal func segments() -> _UnsafeWrappedBuffer { + internal func segments() -> _UnsafeDequeSegments { let wrap = capacity - startSlot.position if count <= wrap { return .init(start: ptr(at: startSlot), count: count) @@ -184,7 +184,7 @@ extension Deque._UnsafeHandle { @inlinable internal func segments( forOffsets offsets: Range - ) -> _UnsafeWrappedBuffer { + ) -> _UnsafeDequeSegments { assert(offsets.lowerBound >= 0 && offsets.upperBound <= count) let lower = slot(forOffset: offsets.lowerBound) let upper = slot(forOffset: offsets.upperBound) @@ -197,7 +197,7 @@ extension Deque._UnsafeHandle { @inlinable @inline(__always) - internal func mutableSegments() -> _UnsafeMutableWrappedBuffer { + internal func mutableSegments() -> _UnsafeMutableDequeSegments { assertMutable() return .init(mutating: segments()) } @@ -206,7 +206,7 @@ extension Deque._UnsafeHandle { @inline(__always) internal func mutableSegments( forOffsets range: Range - ) -> _UnsafeMutableWrappedBuffer { + ) -> _UnsafeMutableDequeSegments { assertMutable() return .init(mutating: segments(forOffsets: range)) } @@ -214,7 +214,7 @@ extension Deque._UnsafeHandle { extension Deque._UnsafeHandle { @inlinable - internal func availableSegments() -> _UnsafeMutableWrappedBuffer { + internal func availableSegments() -> _UnsafeMutableDequeSegments { assertMutable() let endSlot = self.endSlot guard count < capacity else { return .init(start: ptr(at: endSlot), count: 0) } @@ -224,8 +224,6 @@ extension Deque._UnsafeHandle { } } - - extension Deque._UnsafeHandle { @inlinable @discardableResult @@ -269,8 +267,6 @@ extension Deque._UnsafeHandle { } } - - extension Deque._UnsafeHandle { /// Copy elements into a new storage instance without changing capacity or /// layout. @@ -396,7 +392,7 @@ extension Deque._UnsafeHandle { assert(newElements.count == range.count) guard !range.isEmpty else { return } let target = mutableSegments(forOffsets: range) - target.assign(from: newElements) + target.reassign(copying: newElements) } } @@ -429,7 +425,7 @@ extension Deque._UnsafeHandle { let c = self.count count += source.count let gap = mutableSegments(forOffsets: c ..< count) - gap.initialize(from: source) + gap.initialize(copying: source) } } @@ -462,7 +458,7 @@ extension Deque._UnsafeHandle { count += source.count let gap = mutableWrappedBuffer(between: newStart, and: oldStart) - gap.initialize(from: source) + gap.initialize(copying: source) } } @@ -491,14 +487,14 @@ extension Deque._UnsafeHandle { assert(newElements.count == newCount) guard newCount > 0 else { return } let gap = openGap(ofSize: newCount, atOffset: offset) - gap.initialize(from: newElements) + gap.initialize(copying: newElements) } @inlinable internal func mutableWrappedBuffer( between start: Slot, and end: Slot - ) -> _UnsafeMutableWrappedBuffer { + ) -> _UnsafeMutableDequeSegments { assert(start.position <= capacity) assert(end.position <= capacity) if start < end { @@ -523,7 +519,7 @@ extension Deque._UnsafeHandle { internal func openGap( ofSize gapSize: Int, atOffset offset: Int - ) -> _UnsafeMutableWrappedBuffer { + ) -> _UnsafeMutableDequeSegments { assertMutable() assert(offset >= 0 && offset <= self.count) assert(self.count + gapSize <= capacity) diff --git a/Sources/DequeModule/Deque.swift b/Sources/DequeModule/Deque/Deque.swift similarity index 100% rename from Sources/DequeModule/Deque.swift rename to Sources/DequeModule/Deque/Deque.swift diff --git a/Sources/DequeModule/_DequeBuffer.swift b/Sources/DequeModule/Deque/_DequeBuffer.swift similarity index 100% rename from Sources/DequeModule/_DequeBuffer.swift rename to Sources/DequeModule/Deque/_DequeBuffer.swift diff --git a/Sources/DequeModule/_DequeBufferHeader.swift b/Sources/DequeModule/Deque/_DequeBufferHeader.swift similarity index 100% rename from Sources/DequeModule/_DequeBufferHeader.swift rename to Sources/DequeModule/Deque/_DequeBufferHeader.swift diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Append.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Append.swift new file mode 100644 index 00000000..0997dec7 --- /dev/null +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Append.swift @@ -0,0 +1,345 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2025 - 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: ~Copyable { + /// Adds an element to the end of the deque. + /// + /// If the deque does not have sufficient capacity to hold any more elements, + /// then this triggers a runtime error. + /// + /// - Parameter item: The element to append to the deque. + /// + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @inline(__always) + public mutating func append(_ newElement: consuming Element) { + precondition(!isFull, "RigidDeque capacity overflow") + _handle.uncheckedAppend(newElement) + } + + /// Adds an element to the end of the deque, if possible. + /// + /// If the deque does not have sufficient capacity to hold any more elements, + /// then this returns the given item without appending it; otherwise it + /// returns nil. + /// + /// - Parameter item: The element to append to the deque. + /// - Returns: `item` if the deque is full; otherwise nil. + /// + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @inline(__always) + public mutating func pushLast(_ item: consuming Element) -> Element? { + // FIXME: Remove this in favor of a standard algorithm. + if isFull { return item } + append(item) + return nil + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: ~Copyable { + /// Efficiently append a given number of items to the back of this deque by + /// populating a series of storage regions through repeated calls of the + /// specified callback function. + /// + /// If the capacity of the deque isn't sufficient to accommodate the specified + /// number of new elements, then this method triggers a runtime error. + /// + /// var buffer = RigidDeque(capacity: 20) + /// buffer.append(999) + /// var i = 0 + /// buffer.append(maximumCount: 6) { target in + /// while !target.isFull { + /// target.append(i) + /// i += 1 + /// } + /// } + /// // `buffer` now contains [999, 0, 1, 2, 3, 4, 5, 6] + /// + /// The newly appended items are not guaranteed to form a single contiguous + /// storage region. Therefore, the supplied callback may be invoked multiple + /// times to initialize each successive chunk of storage. However, invocations + /// cease when the callback fails to fully populate its output span or if + /// it throws an error. In such cases, the deque keeps all items that were + /// successfully initialized before the callback terminated the append. + /// + /// var buffer = RigidDeque(capacity: 20) + /// buffer.append(999) + /// var i = 0 + /// buffer.append(maximumCount: 6) { target in + /// while !target.isFull, i <= 3 { + /// target.append(i) + /// i += 1 + /// } + /// } + /// // `buffer` now contains [999, 0, 1, 2, 3] + /// + /// - Parameters: + /// - maximumCount: The maximum number of items to append to the deque. + /// - body: A callback that gets called at most twice to directly + /// populate newly reserved storage within the deque. + /// + /// - Complexity: O(`maximumCount`) in addition to the complexity of the callback + /// invocations. + @_alwaysEmitIntoClient + @inline(__always) + public mutating func append( + maximumCount: Int, + initializingWith body: (inout OutputSpan) throws(E) -> Void + ) throws(E) -> Void { + precondition(maximumCount >= 0, "Cannot append a negative number of items") + guard maximumCount > 0 else { return } + precondition(freeCapacity >= maximumCount, "RigidDeque capacity overflow") + try _handle.uncheckedAppend(maximumCount: maximumCount, initializingWith: body) + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: ~Copyable { + /// Moves the elements of a buffer to the end of this deque, leaving the + /// buffer uninitialized. + /// + /// If the deque does not have sufficient capacity to hold all items in the + /// buffer, then this triggers a runtime error. + /// + /// - Parameters: + /// - items: A fully initialized buffer whose contents to move into + /// the deque. + /// + /// - Complexity: O(`items.count`) + @_alwaysEmitIntoClient + public mutating func append( + moving items: UnsafeMutableBufferPointer + ) { + precondition(items.count <= freeCapacity, "RigidDeque capacity overflow") + _handle.uncheckedAppend(moving: items) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Moves the elements of an input span by appending them to the end of + /// this deque, leaving the span empty. + /// + /// If the deque does not have sufficient capacity to hold all items in its + /// storage, then this triggers a runtime error. + /// + /// - Parameters: + /// - items: An input span whose contents need to be appended to this deque. + /// + /// - Complexity: O(`items.count`) + @_alwaysEmitIntoClient + public mutating func append( + moving items: inout InputSpan + ) { + items.withUnsafeMutableBufferPointer { buffer, count in + let source = buffer._extracting(last: count) + unsafe self.append(moving: source) + count = 0 + } + } +#endif + + /// Moves the elements of an output span by appending them to the end of + /// this deque, leaving the span empty. + /// + /// If the deque does not have sufficient capacity to hold all items in its + /// storage, then this triggers a runtime error. + /// + /// - Parameters: + /// - items: An output span whose contents need to be appended to this deque. + /// + /// - Complexity: O(`items.count`) + @_alwaysEmitIntoClient + public mutating func append( + moving items: inout OutputSpan + ) { + items.withUnsafeMutableBufferPointer { buffer, count in + let source = buffer._extracting(first: count) + unsafe self.append(moving: source) + count = 0 + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Appends at most `maximumCount` items generated by a producer to the end of + /// this deque. + /// + /// If the target deque does not have sufficient capacity to hold the + /// specified number of new items, then this triggers a runtime error. + /// + /// This operation appends as many items as the producer can generate before + /// either reaching its end (or throwing an error), or filling the specified + /// capacity. This operation only consumes the first `maximumCount` items in the + /// producer; if the producer has more, then they remain available after this + /// method returns. + /// + /// - Parameters: + /// - maximumCount: The maximum number of items to append to the deque, or + /// nil to use all available capacity. + /// - producer: A producer that generates the items to append. + /// + /// - Complexity: O(*n*), where *n* is the number of items + @_alwaysEmitIntoClient + public mutating func append< + P: Producer & ~Copyable & ~Escapable + >( + maximumCount: Int? = nil, + from producer: inout P + ) throws(P.ProducerError) { + try self.append( + maximumCount: maximumCount ?? self.freeCapacity + ) { target throws(P.ProducerError) in + try producer.generate(into: &target) + } + } +#endif +} + +@available(SwiftStdlib 5.0, *) +extension RigidDeque /*where Element: Copyable*/ { + /// Copies the elements of a buffer and append them to the end of this + /// deque. + /// + /// If the deque does not have sufficient capacity to hold all items in the + /// buffer, then this triggers a runtime error. + /// + /// - Parameters: + /// - items: A fully initialized buffer whose contents to copy into + /// the deque. + /// + /// - Complexity: O(`items.count`) + @_alwaysEmitIntoClient + public mutating func append( + copying items: UnsafeBufferPointer + ) { + precondition( + items.count <= freeCapacity, + "RigidDeque capacity overflow") + _handle.uncheckedAppend(copying: items) + } + + /// Copies the elements of a buffer and append them to the end of this + /// deque. + /// + /// If the deque does not have sufficient capacity to hold all items in the + /// buffer, then this triggers a runtime error. + /// + /// - Parameters: + /// - items: A fully initialized buffer whose contents to copy into + /// the deque. + /// + /// - Complexity: O(`items.count`) + @_alwaysEmitIntoClient + public mutating func append( + copying items: UnsafeMutableBufferPointer + ) { + unsafe self.append(copying: UnsafeBufferPointer(items)) + } + + /// Copies the elements of a span and append them to the end of this deque. + /// + /// If the deque does not have sufficient capacity to hold all items in the + /// span, then this triggers a runtime error. + /// + /// - Parameters: + /// - items: A span whose contents to copy into the deque. + /// + /// - Complexity: O(`items.count`) + @_alwaysEmitIntoClient + public mutating func append(copying items: Span) { + unsafe items.withUnsafeBufferPointer { source in + unsafe self.append(copying: source) + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @_alwaysEmitIntoClient + internal mutating func _append< + S: BorrowingSequence & ~Copyable & ~Escapable + >(copying items: borrowing S) { + var it = items.makeBorrowingIterator() + while true { + let span = it.nextSpan() + if span.isEmpty { break } + self.append(copying: span) + } + } + + /// Copies the elements of a borrowing sequence and append them to the end of + /// this deque. + /// + /// If the deque does not have sufficient capacity to hold all items in the + /// sequence, then this triggers a runtime error. + /// + /// - Parameters: + /// - newElements: The new elements to copy into the deque. + /// + /// - Complexity: O(*m*), where *m* is the length of `newElements`. + @_alwaysEmitIntoClient + public mutating func append & ~Copyable & ~Escapable>( + copying newElements: borrowing S + ) { + self._append(copying: newElements) + } +#endif + + /// Append the elements of a sequence to the end of this deque by copying + /// them. + /// + /// If the deque does not have sufficient capacity to hold all items in the + /// sequence, then this triggers a runtime error. + /// + /// - Parameters: + /// - newElements: The new elements to copy into the deque. + /// + /// - Complexity: O(*m*), where *m* is the length of `newElements`. + @_alwaysEmitIntoClient + public mutating func append(copying newElements: some Sequence) { + let done: Void? = newElements.withContiguousStorageIfAvailable { buffer in + unsafe self.append(copying: buffer) + return + } + if done != nil { return } + + var it = _handle.uncheckedAppend(copyingPrefixOf: newElements) + precondition(it.next() == nil, "RigidDeque capacity overflow") + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Copies the elements of a borrowing sequence to the end of this deque. + /// + /// If the deque does not have sufficient capacity to hold all items in the + /// sequence, then this triggers a runtime error. + /// + /// - Parameters: + /// - items: The new elements to copy into the deque. + /// + /// - Complexity: O(*m*), where *m* is the length of `items`. + @_alwaysEmitIntoClient + public mutating func append< + S: BorrowingSequence & Sequence + >( + copying items: S + ) { + self._append(copying: items) + } +#endif +} + +#endif diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Consumption.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Consumption.swift new file mode 100644 index 00000000..0a19a35f --- /dev/null +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Consumption.swift @@ -0,0 +1,275 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: ~Copyable { +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Remove the specified subrange of items from this deque, + /// passing a series of input spans to a given callback function to consume + /// them in place. + /// + /// The callback is not required to fully consume the contents of its + /// argument; any items it leaves in the input span get automatically + /// consumed. The underlying storage isn't necessarily contiguous, so + /// the callback may be called more than once, whether or not it fully + /// consumes its input. If the specified range is empty, the callback + /// may not be called at all. + /// + /// - Parameter subrange: The subrange of items to consume from this deque. + /// - Parameter consumer: A function taking an input span of the removed items, + /// allowing them to be consumed straight out of the deque's storage. + /// The function is called at most once. + /// + /// - Complexity: O(`self.count`) + @_alwaysEmitIntoClient + @inline(__always) + public mutating func consume( + _ subrange: Range, + consumingWith consumer: (inout InputSpan) -> Void + ) { + _checkValidBounds(subrange) + let segments = self._handle.mutableSegments(forOffsets: subrange) + + var span = InputSpan(buffer: segments.first, initializedCount: segments.first.count) + consumer(&span) + _ = consume span + + if let second = segments.second { + var span = InputSpan(buffer: second, initializedCount: second.count) + consumer(&span) + } + } + + /// Remove the specified subrange of items from this deque, + /// passing a series of input spans to a given callback function to consume + /// them in place. + /// + /// The callback is not required to fully consume the contents of its + /// argument; any items it leaves in the input span get automatically + /// consumed. The underlying storage isn't necessarily contiguous, so + /// the callback may be called more than once, whether or not it fully + /// consumes its input. If the specified range is empty, the callback + /// may not be called at all. + /// + /// - Parameter subrange: The subrange of items to consume from this deque. + /// - Parameter consumer: A function taking an input span of the removed items, + /// allowing them to be consumed straight out of the deque's storage. + /// The function is called at most once. + /// + /// - Complexity: O(`self.count`) + @_alwaysEmitIntoClient + @inline(__always) + public mutating func consume>( + _ subrange: R, + consumingWith consumer: (inout InputSpan) -> Void + ) { + consume(subrange.relative(to: indices), consumingWith: consumer) + } + + /// Remove all items currently in this deque, passing a series of input + /// spans to a given callback function to consume them in place. + /// + /// The callback is not required to fully consume the contents of its + /// argument; any items it leaves in the input span get automatically + /// consumed. The underlying storage isn't necessarily contiguous, so + /// the callback may be called more than once, whether or not it fully + /// consumes its input. If the specified range is empty, the callback + /// may not be called at all. + /// + /// - Parameter consumer: A function taking an input span of the removed items, + /// allowing them to be consumed straight out of the deque's storage. + /// The function is called at most once. + /// - Complexity: O(`self.count`) + @_alwaysEmitIntoClient + @inline(__always) + public mutating func consumeAll( + consumingWith consumer: (inout InputSpan) -> Void + ) { + consume(indices, consumingWith: consumer) + } + + /// Remove the specified number of items from the end of this deque, + /// passing an input span to a given callback function to consume them in + /// place. + /// + /// The callback is not required to fully consume the contents of its + /// argument; any items it leaves in the input span get automatically + /// consumed. The underlying storage isn't necessarily contiguous, so + /// the callback may be called more than once, whether or not it fully + /// consumes its input. If the specified range is empty, the callback + /// may not be called at all. + /// + /// - Parameter n: The number of items to consume from the end of the deque. + /// `n` must be greater than or equal to zero and must not exceed + /// the count of the deque. + /// - Parameter consumer: A function taking an input span of the removed items, + /// allowing them to be consumed straight out of the deque's storage. + /// - Complexity: O(`n`) + @_alwaysEmitIntoClient + @inline(__always) + public mutating func consumeLast( + _ n: Int, + consumingWith consumer: (inout InputSpan) -> Void + ) { + precondition( + n >= 0 && n <= self.count, + "Count of elements to consume is out of bounds") + consume(self.count &- n ..< self.count, consumingWith: consumer) + } + + /// Remove the specified number of items from the front of this deque, + /// passing an input span to a given callback function to consume them in + /// place. + /// + /// The callback is not required to fully consume the contents of its + /// argument; any items it leaves in the input span get automatically + /// consumed. The underlying storage isn't necessarily contiguous, so + /// the callback may be called more than once, whether or not it fully + /// consumes its input. If the specified range is empty, the callback + /// may not be called at all. + /// + /// - Parameter n: The number of items to consume from the front of the deque. + /// `n` must be greater than or equal to zero and must not exceed + /// the count of the deque. + /// - Parameter consumer: A function taking an input span of the removed items, + /// allowing them to be consumed straight out of the deque's storage. + /// - Complexity: O(`n`) + @_alwaysEmitIntoClient + @inline(__always) + public mutating func consumeFirst( + _ n: Int, + consumingWith consumer: (inout InputSpan) -> Void + ) { + precondition( + n >= 0 && n <= self.count, + "Count of elements to consume is out of bounds") + consume(0 ..< n, consumingWith: consumer) + } +#endif +} + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: ~Copyable { + @_alwaysEmitIntoClient + @inline(__always) + @_lifetime(&self) + public mutating func consume(_ subrange: Range) -> SubrangeConsumer { + SubrangeConsumer(_base: &self, offsetRange: subrange) + } + + @_alwaysEmitIntoClient + @inline(__always) + @_lifetime(&self) + public mutating func consume>( + _ subrange: R + ) -> SubrangeConsumer { + consume(subrange.relative(to: indices)) + } + + @_alwaysEmitIntoClient + @inline(__always) + @_lifetime(&self) + public mutating func consumeAll() -> SubrangeConsumer { + consume(indices) + } + + @_alwaysEmitIntoClient + @inline(__always) + @_lifetime(&self) + public mutating func consumeLast(_ n: Int) -> SubrangeConsumer { + precondition( + n >= 0 && n <= self.count, + "Count of elements to consume is out of bounds") + return consume(self.count - n ..< self.count) + } + + @_alwaysEmitIntoClient + @inline(__always) + @_lifetime(&self) + public mutating func consumeFirst(_ n: Int) -> SubrangeConsumer { + precondition( + n >= 0 && n <= self.count, + "Count of elements to consume is out of bounds") + return consume(0 ..< n) + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: ~Copyable { + @frozen + public struct SubrangeConsumer: ~Copyable, ~Escapable { + @usableFromInline + internal var _base: Inout + + @usableFromInline + internal var _offsetRange: Range + + @usableFromInline + internal var _buffer1: UnsafeMutableBufferPointer + + @usableFromInline + internal var _buffer2: UnsafeMutableBufferPointer + + @_alwaysEmitIntoClient + @inline(__always) + @_lifetime(&_base) + internal init(_base: inout RigidDeque, offsetRange: Range) { + _base._checkValidBounds(subrange) + let segments = _base._handle.mutableSegments(forOffsets: offsetRange) + self._buffer1 = segments.first + self._buffer2 = segments.second ?? .init(start: nil, count: 0) + self._base = Inout(&_base) + self._offsetRange = offsetRange + } + + @inlinable + deinit { + self._buffer1.deinitialize() + self._buffer2.deinitialize() + // FIXME: This needs to be written as + // self._base[]._handle.closeGap(offsets: self._offsetRange) + // but unfortunately we cannot mutate self in deinit yet. + // Inout's dereferencing operation is necessarily declared mutating + // to avoid exclusivity violations. + self._base._pointer.pointee._handle.closeGap(offsets: self._offsetRange) + } + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidDeque.SubrangeConsumer: Drain { + @inlinable + @_lifetime(&self) + @_lifetime(self: copy self) + public mutating func drainNext(maximumCount: Int) -> InputSpan { + if _buffer1.isEmpty { + if _buffer2.isEmpty { + return .init() + } + swap(&_buffer1, &_buffer2) + } + let buffer = _buffer1._trim(first: maximumCount) + return _overrideLifetime( + InputSpan(buffer: buffer, initializedCount: buffer.count), + mutating: &self) + } +} +#endif + +#endif diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift new file mode 100644 index 00000000..16ed1ee5 --- /dev/null +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift @@ -0,0 +1,106 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2025 - 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + + +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: ~Copyable { +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @frozen + public struct BorrowingIterator: ~Escapable, BorrowingIteratorProtocol { + @usableFromInline + internal var _currentSegment: Span + + @usableFromInline + internal var _nextSegment: Span + + @_alwaysEmitIntoClient + @_lifetime(borrow _deque) + internal init(_deque: borrowing RigidDeque) { + let segments = _deque._handle.segments() + self._currentSegment = _overrideLifetime( + Span(_unsafeElements: segments.first), + borrowing: _deque) + self._nextSegment = _overrideLifetime( + Span( + _unsafeElements: segments.second ?? UnsafeBufferPointer._empty), + borrowing: _deque) + } + + @_alwaysEmitIntoClient + @_lifetime(copy self) + @_lifetime(self: copy self) + public mutating func nextSpan(maximumCount: Int) -> Span { + let result = _currentSegment._trim(first: maximumCount) + if _currentSegment.isEmpty { + _currentSegment = _nextSegment + _nextSegment = Span() + } + return result + } + } + + @_alwaysEmitIntoClient + @_lifetime(borrow self) + public borrowing func makeBorrowingIterator() -> BorrowingIterator { + BorrowingIterator(_deque: self) + } +#endif +} + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +@available(SwiftStdlib 5.0, *) +extension RigidDeque: Container where Element: ~Copyable {} +#endif + +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: ~Copyable { + @_alwaysEmitIntoClient + @inline(__always) + public func index(after index: Int) -> Int { index + 1 } + + @_alwaysEmitIntoClient + @inline(__always) + public func formIndex(after index: inout Int) { index += 1 } + + @_alwaysEmitIntoClient + @inline(__always) + public func index(_ index: Int, offsetBy n: Int) -> Int { + index + n + } + + @_alwaysEmitIntoClient + public func formIndex( + _ index: inout Index, offsetBy n: inout Int, limitedBy limit: Index + ) { + index._advance(by: &n, limitedBy: limit) + } + + @_alwaysEmitIntoClient + @_lifetime(borrow self) + public func nextSpan(after index: inout Int, maximumCount: Int) -> Span { + _checkValidIndex(index) + precondition(maximumCount > 0, "maximumCount must be positive") + let segment = self._handle + .nextSegment(from: index) + ._extracting(first: maximumCount) + index &+= segment.count + return _overrideLifetime(Span(_unsafeElements: segment), borrowing: self) + } +} + +#endif diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Descriptions.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Descriptions.swift new file mode 100644 index 00000000..5d7e53de --- /dev/null +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Descriptions.swift @@ -0,0 +1,30 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension RigidDeque /*: CustomStringConvertible */ where Element: ~Copyable { + public var description: String { + /// FIXME: Print the item descriptions when available. + "<\(count) items>" + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidDeque /*: CustomDebugStringConvertible */ where Element: ~Copyable { + public var debugDescription: String { + /// FIXME: Print the item descriptions when available. + "<\(count) items>" + } +} + +#endif diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Equatable.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Equatable.swift new file mode 100644 index 00000000..747dcef1 --- /dev/null +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Equatable.swift @@ -0,0 +1,46 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.2) + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +#endif + +@available(SwiftStdlib 5.0, *) +extension RigidDeque /*: Equatable */ where Element: Equatable /* & ~Copyable */ { + public func isTriviallyIdentical(to other: borrowing Self) -> Bool { + self._handle.isIdentical(to: other._handle) + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidDeque /*: Equatable */ where Element: Equatable /* & ~Copyable */ { + @inlinable + public static func ==( + left: borrowing Self, + right: borrowing Self + ) -> Bool { + guard left.count == right.count else { return false } + guard !left.isTriviallyIdentical(to: right) else { return true } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + return left.elementsEqual(right) +#else + for i in 0 ..< left.count { + guard left[i] == right[i] else { return false } + } + return true +#endif + } +} + +#endif diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Experimental.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Experimental.swift new file mode 100644 index 00000000..250ab5d3 --- /dev/null +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Experimental.swift @@ -0,0 +1,42 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + +#if false // FIXME +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: ~Copyable { + @_alwaysEmitIntoClient + @_transparent + @_lifetime(borrow self) + public func borrowElement(at index: Int) -> Borrow { + _checkItemIndex(index) + let slot = _handle.slot(forOffset: index) + return Borrow(unsafeAddress: _handle.ptr(at: slot), borrowing: self) + } + + @_alwaysEmitIntoClient + @_transparent + @_lifetime(&self) + public mutating func mutateElement(at index: Int) -> Inout { + _checkItemIndex(index) + let slot = _handle.slot(forOffset: index) + return Inout(unsafeAddress: _handle.mutablePtr(at: slot), mutating: &self) + } +} +#endif + +#endif diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Hashable.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Hashable.swift new file mode 100644 index 00000000..5600a2b7 --- /dev/null +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Hashable.swift @@ -0,0 +1,31 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.2) + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +#endif + +@available(SwiftStdlib 5.0, *) +extension RigidDeque /*: Hashable */ where Element: Hashable /* & ~Copyable */ { + @inlinable + public func hash(into hasher: inout Hasher) { + hasher.combine(self.count) + let segments = self._handle.segments() + segments.first.span._hashContents(into: &hasher) + if let second = segments.second { + second.span._hashContents(into: &hasher) + } + } +} + +#endif diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Initializers.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Initializers.swift new file mode 100644 index 00000000..ec8d79c1 --- /dev/null +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Initializers.swift @@ -0,0 +1,214 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2025 - 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: ~Copyable { + /// Initializes a new rigid deque with zero capacity and no elements. + /// + /// - Complexity: O(1) + @inlinable + public init() { + self.init(_handle: .allocate(capacity: 0)) + } + + /// Creates an empty rigid deque with the specified capacity. + @_alwaysEmitIntoClient + public init(capacity: Int) { + self.init(_handle: .allocate(capacity: capacity)) + } + + /// Creates a rigid deque with the specified capacity, then calls the given + /// closure with an output span covering the deque's uninitialized memory. + /// + /// - Parameters: + /// - capacity: The number of elements to allocate space for in the new + /// rigid deque. + /// - initializer: A closure that initializes the elements of the new deque. + /// - Parameter outputSpan: An `OutputSpan` allowing initialization of the + /// deque's initial elements. + @inlinable @inline(__always) + public init( + capacity: Int, + initializingWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) { + self.init(_handle: .allocate(capacity: capacity)) + try self.append(maximumCount: capacity, initializingWith: initializer) + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: ~Copyable { + /// Creates a new rigid deque taking over the storage of the specified + /// unique deque instance, consuming it in the process. + /// + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @inline(__always) + public init(consuming deque: consuming UniqueDeque) { + self = deque._storage + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: ~Copyable { +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Creates a new rigid deque of the specified capacity, populating it with + /// items generated by a given producer. + /// + /// The deque is appended as many items as possible before the producer + /// reaches its end. No more than `capacity` elements are retrieved from the + /// producer. + /// + /// If the producer throws an error during this initializer, then all + /// previously produced items are discarded and the initializer rethrows the + /// error. + /// + /// - Parameters: + /// - producer: A producer that generates the items to append to the new + /// deque. + /// + /// - Complexity: O(`capacity`) + public init & ~Copyable & ~Escapable>( + capacity: Int, from producer: inout P + ) throws(P.ProducerError) { + self.init(capacity: capacity) + try self.append(from: &producer) + } +#endif +} + +@available(SwiftStdlib 5.0, *) +extension RigidDeque /*where Element: Copyable*/ { + /// Creates a new deque containing the specified number of a single, + /// repeated value. + /// + /// - Parameters: + /// - repeatedValue: The element to repeat. + /// - count: The number of times to repeat the value passed in the + /// `repeating` parameter. `count` must be zero or greater. + /// + /// - Complexity: O(`count`) + @inlinable + public init(repeating repeatedValue: Element, count: Int) { + self.init(capacity: count) + _handle.mutableBuffer.initialize(repeating: repeatedValue) + _handle.count = count + } +} + + +@available(SwiftStdlib 5.0, *) +extension RigidDeque /*where Element: Copyable*/ { +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Creates a new deque with the specified capacity, holding a copy + /// of the contents of a given borrowing sequence. + /// + /// - Parameters: + /// - capacity: The storage capacity of the new deque. + /// - contents: A sequence whose contents to copy into the new deque. + /// The sequence must not contain more than `capacity` elements. + @_alwaysEmitIntoClient + @inline(__always) + public init< + S: BorrowingSequence & ~Copyable & ~Escapable + >( + capacity: Int, + copying contents: borrowing S + ) { + self.init(capacity: capacity) + self._append(copying: contents) + } +#endif + + /// Creates a new deque with the specified capacity, holding a copy + /// of the contents of a given sequence. + /// + /// - Parameters: + /// - capacity: The storage capacity of the new deque. + /// - contents: The sequence whose contents to copy into the new deque. + /// The sequence must not contain more than `capacity` elements. + @_alwaysEmitIntoClient + @inline(__always) + public init( + capacity: Int, + copying contents: some Sequence + ) { + self.init(capacity: capacity) + self.append(copying: contents) + } + + /// Creates a new rigid deque from the given collection, with the capacity + /// derived from the collection's count. + /// + /// - Parameters: + /// - contents: The contents whose contents to copy into the new deque. + @_alwaysEmitIntoClient + @inline(__always) + public init( + capacity: Int? = nil, + copying contents: some Collection + ) { + self.init(capacity: capacity ?? contents.count) + self.append(copying: contents) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Creates a new deque with the specified capacity, holding a copy + /// of the contents of a given sequence. + /// + /// - Parameters: + /// - capacity: The storage capacity of the new deque. + /// - contents: A sequence whose contents to copy into the new deque. + /// The sequence must not contain more than `capacity` elements. + @_alwaysEmitIntoClient + @inline(__always) + public init< + S: BorrowingSequence & Sequence + >( + capacity: Int, + copying contents: borrowing S + ) { + self.init(capacity: capacity) + self._append(copying: contents) + } + + /// Creates a new deque with the specified capacity, holding a copy + /// of the contents of a given collection. + /// + /// - Parameters: + /// - capacity: The storage capacity of the new deque, or nil to copy all + /// items. If specified, the capacity must be greater + /// than or equal to the count of the collection. + /// - contents: A collection whose contents to copy into the new deque. + /// The sequence must not contain more than `capacity` elements. + @_alwaysEmitIntoClient + @inline(__always) + public init< + S: BorrowingSequence & Collection + >( + capacity: Int? = nil, + copying contents: S + ) { + self.init(capacity: capacity ?? contents.count) + self._append(copying: contents) + } +#endif + +} + +#endif diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift new file mode 100644 index 00000000..0f26ccb4 --- /dev/null +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift @@ -0,0 +1,490 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2025 - 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: ~Copyable { + /// Inserts a new element into the deque at the specified position. + /// + /// If the deque does not have sufficient capacity to hold any more elements, + /// then this triggers a runtime error. + /// + /// The new element is inserted before the element currently at the specified + /// index. If you pass the deque's `endIndex` as the `index` parameter, then + /// the new element is appended to the container. + /// + /// Existing elements in the deque's storage are moved as needed to make room + /// for the new item. (The direction of the move depends on the location of + /// the insertion, minimizing the cost.) + /// + /// - Parameter item: The new element to insert into the deque. + /// - Parameter index: The position at which to insert the new element. + /// `index` must be a valid index in the deque. + /// + /// - Complexity: O(`self.count`) + @_alwaysEmitIntoClient + @inline(__always) + public mutating func insert(_ item: consuming Element, at index: Int) { + precondition(!isFull, "RigidDeque capacity overflow") + _checkValidIndex(index) + _handle.uncheckedInsert(item, at: index) + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: ~Copyable { + /// Inserts a given number of new items into this deque at the specified + /// position, using a callback to directly initialize deque storage by + /// populating a series of output spans. + /// + /// Existing elements in the deque's storage are moved as needed to make room + /// for the new items. (The direction of the move depends on the location of + /// the insertion, minimizing the cost.) + /// + /// If the capacity of the deque isn't sufficient to accommodate the specified + /// number of new elements, then this method triggers a runtime error. + /// + /// var buffer = RigidDeque(capacity: 20) + /// buffer.append([-999, 999]) + /// var i = 0 + /// buffer.insert(addingCount: 3, at: 1) { target in + /// while !target.isFull { + /// target.append(i) + /// i += 1 + /// } + /// } + /// // `buffer` now contains [-999, 0, 1, 2, 999] + /// + /// The newly inserted items are not guaranteed to form a single contiguous + /// storage region. Therefore, the supplied callback may be invoked multiple + /// times to initialize each successive chunk of storage. However, invocations + /// cease if the callback fails to fully populate its output span or if + /// it throws an error. In such cases, the deque keeps all items that were + /// successfully initialized before the callback terminated the insertion. + /// + /// Partial insertions create a gap in ring buffer storage that needs to be + /// closed by moving already inserted items to their correct positions given + /// the adjusted count. This adds some overhead compared to adding exactly as + /// many items as promised. + /// + /// - Parameters: + /// - newItemCount: The maximum number of items to insert into the deque. + /// - index: The position at which to insert the new items. + /// `index` must be a valid index in the deque. + /// - initializer: A callback that gets called at most twice to directly + /// populate newly reserved storage within the deque. The function + /// is always called with an empty output span. + /// + /// - Complexity: O(`self.count` + `newItemCount`) in addition to the complexity + /// of the callback invocations. + @_alwaysEmitIntoClient + @inline(__always) + public mutating func insert( + addingCount newItemCount: Int, + at index: Int, + initializingWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) { + _checkValidIndex(index) + precondition(newItemCount >= 0, "Cannot add a negative number of items") + precondition(newItemCount <= freeCapacity, "RigidDeque capacity overflow") + try _handle.uncheckedInsert( + addingCount: newItemCount, at: index, initializingWith: initializer) + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: ~Copyable { + /// Inserts the elements of a fully initialized buffer by moving them into + /// this deque, starting at the specified position. After this operation, + /// the supplied buffer becomes uninitialized. + /// + /// Existing elements in the deque's storage are moved as needed to make room + /// for the new items. (The direction of the move depends on the location of + /// the insertion, minimizing the cost.) + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// - Parameters: + /// - items: A fully initialized buffer whose contents to move into + /// the deque. + /// - index: The position at which to insert the new items. + /// `index` must be a valid index in the array. + /// + /// - Complexity: O(`self.count` + `items.count`) + @_alwaysEmitIntoClient + public mutating func insert( + moving items: UnsafeMutableBufferPointer, + at index: Int + ) { + guard !items.isEmpty else { return } + var remainder = items + insert(addingCount: items.count, at: index) { target in + target.withUnsafeMutableBufferPointer { buffer, count in + buffer.moveInitializeAll( + fromContentsOf: remainder._trim(first: buffer.count)) + count = buffer.count + } + } + assert(remainder.isEmpty) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Moves the elements of an input span into this deque, + /// starting at the specified position, and leaving the span empty. + /// + /// Existing elements in the deque's storage are moved as needed to make room + /// for the new items. (The direction of the move depends on the location of + /// the insertion, minimizing the cost.) + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// - Parameters: + /// - items: An input span whose contents to move into + /// the deque. + /// - index: The position at which to insert the new items. + /// `index` must be a valid index in the deque. + /// + /// - Complexity: O(`self.count` + `items.count`) + @_alwaysEmitIntoClient + public mutating func insert( + moving items: inout InputSpan, + at index: Int + ) { + items.withUnsafeMutableBufferPointer { buffer, count in + let source = buffer._extracting(last: count) + unsafe self.insert(moving: source, at: index) + count = 0 + } + } +#endif + + /// Moves the elements of an output span into this deque, + /// starting at the specified position, and leaving the span empty. + /// + /// Existing elements in the deque's storage are moved as needed to make room + /// for the new items. (The direction of the move depends on the location of + /// the insertion, minimizing the cost.) + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// - Parameters: + /// - items: An output span whose contents to move into + /// the deque. + /// - index: The position at which to insert the new items. + /// `index` must be a valid index in the deque. + /// + /// - Complexity: O(`self.count` + `items.count`) + @_alwaysEmitIntoClient + public mutating func insert( + moving items: inout OutputSpan, + at index: Int + ) { + items.withUnsafeMutableBufferPointer { buffer, count in + let source = buffer._extracting(first: count) + unsafe self.insert(moving: source, at: index) + count = 0 + } + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: ~Copyable { +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Inserts at most `newItemCount` items generated by a producer into this + /// deque, starting at the given index. + /// + /// Existing elements in the deque's storage are moved as needed to make room + /// for the new items. (The direction of the move depends on the location of + /// the insertion, minimizing the cost.) + /// + /// If the target deque does not have sufficient capacity to hold the + /// specified number of new items, then this triggers a runtime error. + /// + /// This operation inserts as many items as the producer can generate before + /// either reaching `newItemCount`, or the producer hitting its end, or + /// throwing an error. If the producer has more than `newItemCount` items + /// left in its underlying sequence, then extra items remain available after + /// this method returns. + /// + /// If the operation inserts fewer than `newItemCount` items, then it results + /// in a gap in ring buffer storage that needs to be closed by moving some + /// items to their correct positions given the adjusted count. This adds some + /// overhead compared to adding exactly as many items as promised. + /// + /// - Parameters: + /// - newItemCount: The maximum number of items to insert into the deque. + /// - index: The position at which to insert the new items. + /// `index` must be a valid index in the deque. + /// - producer: A producer that generates the items to append. + /// + /// - Complexity: O(`self.count` + `newItemCount`) + @_alwaysEmitIntoClient + public mutating func insert< + P: Producer & ~Copyable & ~Escapable + >( + addingCount newItemCount: Int, + from producer: inout P, + at index: Int + ) throws(P.ProducerError) { + try insert(addingCount: newItemCount, at: index) { target throws(P.ProducerError) in + while !target.isFull, try producer.generate(into: &target) { + // Do nothing + } + } + } + #endif +} + +@available(SwiftStdlib 5.0, *) +extension RigidDeque /* where Element: Copyable */ { + /// Copies the elements of a fully initialized buffer pointer into this + /// deque at the specified position. + /// + /// The new elements are inserted before the element currently at the + /// specified index. If you pass the deque’s `endIndex` as the `index` + /// parameter, then the new elements are appended to the end of the array. + /// + /// Existing elements in the deque's storage are moved as needed to make room + /// for the new items. (The direction of the move depends on the location of + /// the insertion, minimizing the cost.) + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// - Parameters: + /// - items: The new elements to insert into the deque. The buffer + /// must be fully initialized. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of `self`. + /// + /// - Complexity: O(`count` + `items.count`) + @inlinable + public mutating func insert( + copying items: UnsafeBufferPointer, at index: Int + ) { + guard items.count > 0 else { return } + var remainder = items + insert(addingCount: remainder.count, at: index) { target in + target.withUnsafeMutableBufferPointer { buffer, count in + buffer.initializeAll( + fromContentsOf: remainder._extracting(first: buffer.count)) + remainder = remainder._extracting(droppingFirst: buffer.count) + count = buffer.count + } + } + assert(remainder.isEmpty) + } + + /// Copies the elements of a fully initialized buffer pointer into this + /// deque at the specified position. + /// + /// The new elements are inserted before the element currently at the + /// specified index. If you pass the deque’s `endIndex` as the `index` + /// parameter, then the new elements are appended to the end of the deque. + /// + /// Existing elements in the deque's storage are moved as needed to make room + /// for the new items. (The direction of the move depends on the location of + /// the insertion, minimizing the cost.) + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// - Parameters: + /// - items: The new elements to insert into the deque. The buffer + /// must be fully initialized. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of `self`. + /// + /// - Complexity: O(`count` + `items.count`) + @inlinable + public mutating func insert( + copying items: UnsafeMutableBufferPointer, + at index: Int + ) { + unsafe self.insert(copying: UnsafeBufferPointer(items), at: index) + } + + /// Copies the elements of a span into this deque at the specified position. + /// + /// The new elements are inserted before the element currently at the + /// specified index. If you pass the deque’s `endIndex` as the `index` + /// parameter, then the new elements are appended to the end of the deque. + /// + /// Existing elements in the deque's storage are moved as needed to make room + /// for the new items. (The direction of the move depends on the location of + /// the insertion, minimizing the cost.) + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// - Parameters: + /// - items: The new elements to insert into the deque. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of the deque. + /// + /// - Complexity: O(`count` + `items.count`) + @inlinable + public mutating func insert( + copying items: Span, at index: Int + ) { + unsafe items.withUnsafeBufferPointer { + unsafe self.insert(copying: $0, at: index) + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @inlinable + internal mutating func _insertContainer< + C: Container & ~Copyable & ~Escapable + >( + at index: Int, + copying items: borrowing C, + newCount: Int + ) { + let expectedCount = self.count + newCount + var it = items.makeBorrowingIterator() + insert(addingCount: newCount, at: index) { target in + it.copyContents(into: &target) + } + precondition( + it.nextSpan().isEmpty && self.count == expectedCount, + "Broken Container: count doesn't match contents") + } +#endif + + @inlinable + internal mutating func _insertCollection( + at index: Int, + copying items: some Collection, + newCount: Int + ) { + let done: Void? = items.withContiguousStorageIfAvailable { src in + self.insert(copying: src, at: index) + } + if done != nil { return } + + var i = items.startIndex + self.insert(addingCount: newCount, at: index) { target in + while !target.isFull { + target.append(items[i]) + items.formIndex(after: &i) + } + } + precondition(i == items.endIndex, + "Broken Collection: count doesn't match contents") + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Copies the elements of a container into this deque at the specified + /// position. + /// + /// The new elements are inserted before the element currently at the + /// specified index. If you pass the deque’s `endIndex` as the `index` + /// parameter, then the new elements are appended to the end of the deque. + /// + /// Existing elements in the deque's storage are moved as needed to make room + /// for the new items. (The direction of the move depends on the location of + /// the insertion, minimizing the cost.) + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// - Parameters: + /// - newElements: The new elements to insert into the deque. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of the deque. + /// + /// - Complexity: O(`self.count` + `items.count`). + @_alwaysEmitIntoClient + @inline(__always) + public mutating func insert< + C: Container & ~Copyable & ~Escapable + >( + copying items: borrowing C, at index: Int + ) { + _insertContainer( + at: index, copying: items, newCount: items.count) + } +#endif + + /// Copies the elements of a collection into this deque at the specified + /// position. + /// + /// The new elements are inserted before the element currently at the + /// specified index. If you pass the deque’s `endIndex` as the `index` + /// parameter, then the new elements are appended to the end of the deque. + /// + /// Existing elements in the deque's storage are moved as needed to make room + /// for the new items. (The direction of the move depends on the location of + /// the insertion, minimizing the cost.) + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// - Parameters: + /// - items: The new elements to insert into the deque. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of the deque. + /// + /// - Complexity: O(`count` + `newElements.count`) + @inlinable + @inline(__always) + public mutating func insert( + copying items: some Collection, at index: Int + ) { + _insertCollection( + at: index, copying: items, newCount: items.count) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Copies the elements of a container into this deque at the specified + /// position. + /// + /// The new elements are inserted before the element currently at the + /// specified index. If you pass the deque's `endIndex` as the `index` + /// parameter, then the new elements are appended to the end of the deque. + /// + /// Existing elements in the deque's storage are moved as needed to make room + /// for the new items. (The direction of the move depends on the location of + /// the insertion, minimizing the cost.) + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// - Parameters: + /// - items: The new elements to insert into the deque. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of the deque. + /// + /// - Complexity: O(`self.count` + `items.count`) + @_alwaysEmitIntoClient + @inline(__always) + public mutating func insert< + C: Container & Collection + >( + copying items: borrowing C, at index: Int + ) { + _insertContainer( + at: index, copying: items, newCount: items.count) + } +#endif +} + +#endif diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift new file mode 100644 index 00000000..7ace8d56 --- /dev/null +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift @@ -0,0 +1,490 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2025 - 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: ~Copyable { + /// Adds an element to the front of the deque. + /// + /// If the deque does not have sufficient capacity to hold any more elements, + /// then this triggers a runtime error. + /// + /// - Parameter item: The element to prepend to the deque. + /// + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @_transparent + public mutating func prepend(_ newElement: consuming Element) { + precondition(!isFull, "RigidDeque capacity overflow") + _handle.uncheckedPrepend(newElement) + } + + /// Adds an element to the front of the deque, if possible. + /// + /// If the deque does not have sufficient capacity to hold any more elements, + /// then this returns the given item without prepending it; otherwise it + /// returns nil. + /// + /// - Parameter item: The element to prepend to the deque. + /// - Returns: `item` if the deque is full; otherwise nil. + /// + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @_transparent + public mutating func pushFirst(_ item: consuming Element) -> Element? { + // FIXME: Remove this in favor of a standard algorithm. (Or not -- prependable containers may not be worth a protocol) + if isFull { return item } + prepend(item) + return nil + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: ~Copyable { + /// Efficiently prepend a given number of items to the front of this deque by + /// populating a series of storage regions through repeated calls of the + /// specified callback function. + /// + /// If the capacity of the deque isn't sufficient to accommodate the specified + /// number of new elements, then this method triggers a runtime error. + /// + /// var buffer = RigidDeque(capacity: 20) + /// buffer.append(999) + /// var i = 0 + /// buffer.prepend(count: 6) { target in + /// while !target.isFull { + /// target.append(i) + /// i += 1 + /// } + /// } + /// // `buffer` now contains [0, 1, 2, 3, 4, 5, 6, 999] + /// + /// The newly prepended items are not guaranteed to form a single contiguous + /// storage region. Therefore, the supplied callback may be invoked multiple + /// times to initialize each successive chunk of storage. However, invocations + /// cease if the callback fails to fully populate its output span or if + /// it throws an error. In such cases, the deque keeps all items that were + /// successfully initialized before the callback terminated the prepend. + /// + /// Note: Partial prepends create a gap in ring buffer storage that needs to + /// be closed by moving newly prepended items to their correct positions given + /// the adjusted count. This adds some overhead compared to adding exactly as + /// many items as promised. + /// + /// var buffer = RigidDeque(capacity: 20) + /// buffer.append(999) + /// var i = 0 + /// buffer.prepend(count: 6) { target in + /// while !target.isFull, i <= 3 { + /// target.append(i) + /// i += 1 + /// } + /// } + /// // `buffer` now contains [0, 1, 2, 3, 999] + /// + /// - Parameters: + /// - newItemCount: The maximum number of items to prepend to the deque. + /// - body: A callback that gets called at most twice to directly + /// populate newly reserved storage within the deque. + /// + /// - Complexity: O(`newItemCount`) in addition to the complexity of the callback + /// invocations. + @_alwaysEmitIntoClient + public mutating func prepend( + addingCount newItemCount: Int, + initializingWith body: (inout OutputSpan) throws(E) -> Void + ) throws(E) -> Void { + precondition(newItemCount >= 0, "Cannot prepend a negative number of items") + precondition(freeCapacity >= newItemCount, "RigidDeque capacity overflow") + try _handle.uncheckedPrepend(addingCount: newItemCount, initializingWith: body) + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: ~Copyable { + /// Moves the elements of a buffer to the front of this deque, leaving the + /// buffer uninitialized. + /// + /// If the deque does not have sufficient capacity to hold all items in the + /// buffer, then this triggers a runtime error. + /// + /// - Parameters: + /// - items: A fully initialized buffer whose contents to move into + /// the deque. + /// + /// - Complexity: O(`items.count`) + @_alwaysEmitIntoClient + @inline(__always) + public mutating func prepend( + moving items: UnsafeMutableBufferPointer + ) { + precondition(items.count <= freeCapacity, "RigidDeque capacity overflow") + _handle.uncheckedPrepend(moving: items) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Moves the elements of an input span by prepending them to the front of + /// this deque, leaving the span empty. + /// + /// If the deque does not have sufficient capacity to hold all items in its + /// storage, then this triggers a runtime error. + /// + /// - Parameters: + /// - items: An input span whose contents need to be prepended to this deque. + /// + /// - Complexity: O(`items.count`) + @_alwaysEmitIntoClient + public mutating func prepend( + moving items: inout InputSpan + ) { + items.withUnsafeMutableBufferPointer { buffer, count in + let source = buffer._extracting(last: count) + unsafe self.prepend(moving: source) + count = 0 + } + } +#endif + + /// Moves the elements of an output span by prepending them to the front of + /// this deque, leaving the span empty. + /// + /// If the deque does not have sufficient capacity to hold all items in its + /// storage, then this triggers a runtime error. + /// + /// - Parameters: + /// - items: An output span whose contents need to be prepended to this deque. + /// + /// - Complexity: O(`items.count`) + @_alwaysEmitIntoClient + public mutating func prepend( + moving items: inout OutputSpan + ) { + items.withUnsafeMutableBufferPointer { buffer, count in + let source = buffer._extracting(first: count) + unsafe self.prepend(moving: source) + count = 0 + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Prepends at most `maximumCount` items generated by a producer to the front of + /// this deque. + /// + /// If the target deque does not have sufficient capacity to hold the + /// specified number of new items, then this triggers a runtime error. + /// + /// This operation prepends as many items as the producer can generate before + /// either reaching its end (or throwing an error), or filling the specified + /// capacity. This operation only consumes the first `maximumCount` items in the + /// producer; if the producer has more, then they remain available after this + /// method returns. + /// + /// Note: Partial prepends create a gap in ring buffer storage that needs to + /// be closed by moving newly prepended items to their correct positions given + /// the adjusted count. This adds some overhead compared to adding exactly as + /// many items as promised. + /// + /// - Parameters: + /// - maximumCount: The maximum number of items to prepend to the deque, or + /// nil to use all available capacity. + + /// - producer: A producer that generates the items to prepend. + /// + /// - Complexity: O(`maximumCount ?? self.freeCapacity`) + @_alwaysEmitIntoClient + @inline(__always) + public mutating func prepend< + P: Producer & ~Copyable & ~Escapable + >( + maximumCount: Int? = nil, + from producer: inout P + ) throws(P.ProducerError) { + try self.prepend( + addingCount: maximumCount ?? freeCapacity + ) { target throws(P.ProducerError) in + try producer.generate(into: &target) + } + } +#endif +} + +@available(SwiftStdlib 5.0, *) +extension RigidDeque /*where Element: Copyable*/ { + /// Copies the elements of a buffer and prepend them to the front of this + /// rigid deque. + /// + /// If the deque does not have sufficient capacity to hold all items in the + /// buffer, then this triggers a runtime error. + /// + /// - Parameters: + /// - items: A fully initialized buffer whose contents to copy into + /// the deque. + /// + /// - Complexity: O(`items.count`) + @inlinable + @_alwaysEmitIntoClient + public mutating func prepend( + copying items: UnsafeBufferPointer + ) { + precondition( + items.count <= freeCapacity, + "RigidDeque capacity overflow") + _handle.uncheckedPrepend(copying: items) + } + + /// Copies the elements of a buffer and prepend them to the front of this + /// deque. + /// + /// If the deque does not have sufficient capacity to hold all items in the + /// buffer, then this triggers a runtime error. + /// + /// - Parameters: + /// - items: A fully initialized buffer whose contents to copy into + /// the deque. + /// + /// - Complexity: O(`items.count`) + @inlinable + @_alwaysEmitIntoClient + public mutating func prepend( + copying items: UnsafeMutableBufferPointer + ) { + unsafe self.prepend(copying: UnsafeBufferPointer(items)) + } + + /// Copy the elements of a span and prepend them to the front of this deque. + /// + /// If the deque does not have sufficient capacity to hold all items in the + /// span, then this triggers a runtime error. + /// + /// - Parameters: + /// - items: A span whose contents to copy into the deque. + /// + /// - Complexity: O(`items.count`) + @inlinable + @_alwaysEmitIntoClient + public mutating func prepend(copying items: Span) { + unsafe items.withUnsafeBufferPointer { source in + unsafe self.prepend(copying: source) + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @inlinable + internal mutating func _prepend< + S: BorrowingSequence & ~Copyable & ~Escapable + >(copying items: borrowing S) { + // We don't know the exact count of new elements, so we cannot initialize + // them in place. Append them to the end of the deque first, then rotate + // them to their correct location. + // + // FIXME: If we get a BorrowingSequence.estimatedCount with an exact case, + // then we should use that when possible to copy items to their final + // location in a single pass. + let oldCount = self.count + self._append(copying: items) // Not a typo! + _handle.rotate(toStartAtOffset: oldCount) + } + + @inlinable + internal mutating func _prepend< + S: BorrowingSequence & ~Copyable & ~Escapable + >( + copying items: borrowing S, + exactCount: Int + ) { + var it = items.makeBorrowingIterator() + self.prepend(addingCount: exactCount) { target in + let span = it.nextSpan(maximumCount: target.freeCapacity) + target._append(copying: span) + } + } + + /// Copies the elements of a borrowing sequence and prepend them to the front + /// of this deque. + /// + /// If the deque does not have sufficient capacity to hold all items in the + /// sequence, then this triggers a runtime error. + /// + /// As borrowing sequences do not necessarily provide an exact count, this + /// operation works by first appending the items, then finalizing the + /// prepend by rotating them in place as a postprocessing step. + /// + /// - Parameters: + /// - items: The new elements to copy into the deque. + /// + /// - Complexity: O(*m*), where *m* is the length of `items`. + @_alwaysEmitIntoClient + public mutating func prepend & ~Copyable & ~Escapable>( + copying items: borrowing S + ) { + self._prepend(copying: items) + } + + /// Copies the elements of a container and prepends them to the front + /// of this deque. + /// + /// If the deque does not have sufficient capacity to hold all items in the + /// container, then this triggers a runtime error. + /// + /// - Parameters: + /// - items: The new elements to copy into the deque. + /// + /// - Complexity: O(`items.count`) + @_alwaysEmitIntoClient + public mutating func prepend & ~Copyable & ~Escapable>( + copying items: borrowing C + ) { + self._prepend(copying: items, exactCount: items.count) + } +#endif + + /// Prepend the elements of a sequence to the front of this deque by copying + /// them. + /// + /// If the deque does not have sufficient capacity to hold all items in the + /// sequence, then this triggers a runtime error. + /// + /// This example prepends the elements of a `Range` instance + /// to a rigid deque of integers. + /// + /// var numbers = RigidDeque(capacity: 10) + /// numbers.append(copying: [1, 2, 3, 4, 5]) + /// numbers.prepend(copying: 10...15) + /// // `numbers` now contains [10, 11, 12, 13, 14, 15, 1, 2, 3, 4, 5] + /// + /// As borrowing sequences do not necessarily provide an exact count, this + /// operation works by first appending the items, then finalizing the + /// prepend by rotating them in place as a postprocessing step. + /// + /// - Parameter items: The elements to prepend to the deque. + /// + /// - Complexity: O(`items.count`) + @inlinable + @_alwaysEmitIntoClient + public mutating func prepend( + copying items: some Sequence + ) { + let done: Void? = items.withContiguousStorageIfAvailable { source in + unsafe self.prepend(copying: source) + return + } + guard done == nil else { return } + let oldCount = self.count + self.append(copying: items) // Not a typo! + _handle.rotate(toStartAtOffset: oldCount) + } + + /// Prepend the elements of a collection to the front of this deque by copying + /// them. + /// + /// If the deque does not have sufficient capacity to hold all items in the + /// sequence, then this triggers a runtime error. + /// + /// This example prepends the elements of a `Range` instance + /// to a rigid deque of integers. + /// + /// var numbers = RigidDeque(capacity: 10) + /// numbers.append(copying: [1, 2, 3, 4, 5]) + /// numbers.prepend(copying: 10...15) + /// // `numbers` now contains [10, 11, 12, 13, 14, 15, 1, 2, 3, 4, 5] + /// + /// - Parameter items: The elements to prepend to the deque. + /// + /// - Complexity: O(`items.count`) + @inlinable + @_alwaysEmitIntoClient + public mutating func prepend( + copying items: some Collection + ) { + let done: Void? = items.withContiguousStorageIfAvailable { source in + unsafe self.prepend(copying: source) + return + } + guard done == nil else { return } + let c = items.count + guard c > 0 else { return } + precondition(c <= freeCapacity, "RigidDeque capacity overflow") + _handle.uncheckedPrepend(copying: items, exactCount: c) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Copies the elements of a borrowing sequence to the end of this deque. + /// + /// If the deque does not have sufficient capacity to hold all items in the + /// sequence, then this triggers a runtime error. + /// + /// - Parameters: + /// - items: The new elements to copy into the deque. + /// + /// - Complexity: O(*m*), where *m* is the length of `items`. + @_alwaysEmitIntoClient + public mutating func prepend & Sequence>( + copying items: borrowing S + ) { + self._prepend(copying: items) + } + + /// Copies the elements of a borrowing sequence to the end of this deque. + /// + /// If the deque does not have sufficient capacity to hold all items in the + /// sequence, then this triggers a runtime error. + /// + /// - Parameters: + /// - items: The new elements to copy into the deque. + /// + /// - Complexity: O(*m*), where *m* is the length of `items`. + @_alwaysEmitIntoClient + public mutating func prepend & Collection>( + copying items: borrowing S + ) { + self._prepend(copying: items, exactCount: items.count) + } + + /// Copies the elements of a container to the end of this deque. + /// + /// If the deque does not have sufficient capacity to hold all items in the + /// sequence, then this triggers a runtime error. + /// + /// - Parameters: + /// - items: The new elements to copy into the deque. + /// + /// - Complexity: O(*m*), where *m* is the length of `items`. + @_alwaysEmitIntoClient + public mutating func prepend & Sequence>( + copying items: borrowing C + ) { + self._prepend(copying: items, exactCount: items.count) + } + + /// Copies the elements of a container to the end of this deque. + /// + /// If the deque does not have sufficient capacity to hold all items in the + /// sequence, then this triggers a runtime error. + /// + /// - Parameters: + /// - items: The new elements to copy into the deque. + /// + /// - Complexity: O(*m*), where *m* is the length of `items`. + @_alwaysEmitIntoClient + public mutating func prepend & Collection>( + copying items: borrowing C + ) { + self._prepend(copying: items, exactCount: items.count) + } +#endif +} +#endif diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Removals.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Removals.swift new file mode 100644 index 00000000..38f3048b --- /dev/null +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Removals.swift @@ -0,0 +1,153 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2025 - 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: ~Copyable { + /// Removes and returns the element at the specified position. + /// + /// Existing elements in the deque's storage are moved as needed to close the + /// gap left by the removed item. (The direction of the move depends on the + /// location of the removal, minimizing the cost.) + /// + /// - Parameter i: The position of the element to remove. `index` must be + /// a valid index of the deque that is not equal to the end index. + /// - Returns: The removed element. + /// + /// - Complexity: O(`count`) + @discardableResult + @_alwaysEmitIntoClient + public mutating func remove(at index: Int) -> Element { + _checkItemIndex(index) + return _handle.uncheckedRemove(at: index) + } + + /// Removes all elements from the deque, preserving its allocated capacity. + /// + /// - Complexity: O(`count`) + @_alwaysEmitIntoClient + public mutating func removeAll() { + _handle.uncheckedRemoveAll() + } + + /// Removes and returns the first element of the deque. + /// + /// The deque must not be empty. + /// + /// - Returns: The first element of the original deque. + /// + /// - Complexity: O(1) + @discardableResult + @_alwaysEmitIntoClient + public mutating func removeFirst() -> Element { + precondition(!isEmpty, "Cannot remove first element of an empty RigidDeque") + return _handle.uncheckedRemoveFirst() + } + + /// Removes and returns the last element of the deque. + /// + /// The deque must not be empty. + /// + /// - Returns: The last element of the original deque. + /// + /// - Complexity: O(1) + @discardableResult + @_alwaysEmitIntoClient + public mutating func removeLast() -> Element { + precondition(!isEmpty, "Cannot remove last element of an empty RigidDeque") + return _handle.uncheckedRemoveLast() + } + + /// Removes and discards the specified number of elements from the start of + /// the deque. + /// + /// Attempting to remove more elements than exist in the deque + /// triggers a runtime error. + /// + /// - Parameter k: The number of elements to remove from the deque. + /// `k` must be greater than or equal to zero and must not exceed + /// the count of the deque. + /// + /// - Complexity: O(`k`) + @_alwaysEmitIntoClient + public mutating func removeFirst(_ k: Int) { + precondition(k >= 0, "Cannot remove a negative number of elements") + precondition(k <= count, "Cannot remove more elements than there are in the container") + _handle.uncheckedRemoveFirst(k) + } + + /// Removes and discards the specified number of elements from the end of the + /// deque. + /// + /// Attempting to remove more elements than exist in the deque + /// triggers a runtime error. + /// + /// - Parameter k: The number of elements to remove from the deque. + /// `k` must be greater than or equal to zero and must not exceed + /// the count of the deque. + /// + /// - Complexity: O(`k`) + @_alwaysEmitIntoClient + public mutating func removeLast(_ n: Int) { + precondition(n >= 0, "Cannot remove a negative number of elements") + precondition(n <= count, "Cannot remove more elements than there are in the container") + _handle.uncheckedRemoveLast(n) + } + + /// Removes the specified subrange of elements from the deque. + /// + /// - Parameter bounds: The subrange to remove. The bounds of the + /// range must be valid indices of the deque. + /// + /// - Complexity: O(`count`) + @_alwaysEmitIntoClient + public mutating func removeSubrange(_ bounds: Range) { + precondition( + bounds.lowerBound >= 0 && bounds.upperBound <= count, + "Subrange out of bounds") + _handle.uncheckedRemove(offsets: bounds) + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: ~Copyable { + /// Removes and returns the first element of the deque, if there is one. + /// + /// - Returns: The first element of the original deque if it was not empty; + /// otherwise, `nil`. + /// + /// - Complexity: O(1) + @_alwaysEmitIntoClient + public mutating func popFirst() -> Element? { + guard !isEmpty else { return nil } + return _handle.uncheckedRemoveFirst() + } + + /// Removes and returns the last element of the deque, if there is one. + /// + /// - Returns: The last element of the original deque if it was not empty; + /// otherwise, `nil`. + /// + /// - Complexity: O(1) + @_alwaysEmitIntoClient + public mutating func popLast() -> Element? { + guard !isEmpty else { return nil } + return _handle.uncheckedRemoveLast() + } +} + +#endif diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift new file mode 100644 index 00000000..9cb87b7f --- /dev/null +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift @@ -0,0 +1,613 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: ~Copyable { + /// Replaces the specified range of elements by a given count of new items, + /// using a callback to directly initialize deque storage by populating + /// a series of output spans. + /// + /// This method has the same overall effect as calling + /// + /// try deque.removeSubrange(subrange) + /// try deque.insert( + /// addingCount: newItemCount, + /// at: subrange.lowerBound, + /// initializingWith: initializer) + /// + /// Except it performs faster (by a constant factor), by avoiding moving + /// some items in the deque twice. + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// The newly inserted items are not guaranteed to form a single contiguous + /// storage region. Therefore, the supplied callback may be invoked multiple + /// times to initialize each successive chunk of storage. However, invocations + /// cease if the callback fails to fully populate its output span or if + /// it throws an error. In such cases, the deque keeps all items that were + /// successfully initialized before the callback terminated the prepend. + /// + /// Partial insertions create a gap in ring buffer storage that needs to be + /// closed by moving newly inserted items to their correct positions given + /// the adjusted count. This adds some overhead compared to adding exactly as + /// many items as promised. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - newItemCount: the maximum number of items to replace the old subrange. + /// - initializer: A callback that gets called at most twice to directly + /// populate newly reserved storage within the deque. The function + /// is always called with an empty output span. + /// + /// - Complexity: O(`self.count` + `newItemCount`) in addition to the complexity + /// of the callback invocations. + @inlinable + public mutating func replace( + removing subrange: Range, + addingCount newItemCount: Int, + initializingWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) -> Void { + _checkValidBounds(subrange) + precondition(newItemCount >= 0, "Cannot add a negative number of items") + precondition( + count - subrange.count + newItemCount <= capacity, + "RigidDeque capacity overflow") + try _handle.uncheckedReplace( + removing: subrange, + addingCount: newItemCount, + initializingWith: initializer) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Replaces the specified range of elements by a given count of new items, + /// using callbacks to consume old items, and to then insert new ones. + /// + /// The number of new elements need not match the number of elements being + /// removed. + /// + /// This method has the same overall effect as calling + /// + /// try deque.consume(subrange, consumingWith: consumer) + /// try deque.insert( + /// addingCount: newItemCount, + /// at: subrange.lowerBound, + /// initializingWith: initializer) + /// + /// Except it performs faster (by a constant factor), by avoiding moving + /// some items in the deque twice. + /// + /// If the deque doesn't have sufficient capacity to accommodate the specified + /// number of new elements, then this method triggers a runtime error. + /// + /// Neither the removed nor the newly inserted items are guaranteed to form a + /// single contiguous storage region. Therefore, the supplied callbacks may be + /// invoked multiple times to consume, then initialize successive chunks of + /// storage. Calls to `consumer` do not get interleaved with calls to + /// `initializer`: no new item is inserted until every replaced item has been + /// fully consumed. + /// + /// The `consumer` callback is not required to fully depopulate its input + /// span. Any items the callback leaves in the span still get removed and + /// discarded from the deque before insertions begin. If there are more + /// spans to consume, the callback will get called again after such a partial + /// consumption. + /// + /// The `initializer` callback is not required to fully populate its + /// output span, and it is allowed to throw an error. In such cases, the + /// replacement operation ends, and the deque keeps all items that were + /// successfully initialized before the callback terminated. + /// + /// Partial insertions create a gap in ring buffer storage that needs to be + /// closed by moving newly inserted items to their correct positions given + /// the adjusted count. This adds some overhead compared to adding exactly as + /// many items as promised. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - newItemCount: the maximum number of items to replace the old subrange. + /// - consumer: A callback that gets called at most twice to consume + /// the elements to be removed directly from the deque's storage. The + /// function is always called with a non-empty input span. + /// - initializer: A callback that gets called at most twice to directly + /// populate newly reserved storage within the deque. The function + /// is always called with an empty output span. + /// + /// - Complexity: O(`self.count` + `newItemCount`) in addition to the + /// complexity of the callback invocations. + @inlinable + public mutating func replace( + removing subrange: Range, + consumingWith consumer: (inout InputSpan) -> Void, + addingCount newItemCount: Int, + initializingWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) -> Void { + _checkValidBounds(subrange) + precondition(newItemCount >= 0, "Cannot add a negative number of items") + precondition( + count - subrange.count + newItemCount <= capacity, + "RigidDeque capacity overflow") + try _handle.uncheckedReplace( + removing: subrange, + consumingWith: consumer, + addingCount: newItemCount, + initializingWith: initializer) + } +#endif +} + +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: ~Copyable { + /// Replaces the specified range of elements by moving the elements of a + /// fully initialized buffer into their place. On return, the buffer is left + /// in an uninitialized state. + /// + /// This method has the effect of removing the specified range of elements + /// from the deque and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `items` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(moving:at:)`. + /// + /// Likewise, if you pass a zero-length buffer as the `items` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - items: A fully initialized buffer whose contents to move into + /// the deque. + /// + /// - Complexity: O(`self.count` + `items.count`) + @_alwaysEmitIntoClient + public mutating func replace( + removing subrange: Range, + moving items: UnsafeMutableBufferPointer, + ) { + var remainder = items + replace(removing: subrange, addingCount: remainder.count) { target in + target.withUnsafeMutableBufferPointer { buffer, count in + buffer.moveInitializeAll( + fromContentsOf: remainder._trim(first: buffer.count)) + count = buffer.count + } + } + assert(remainder.isEmpty) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Replaces the specified range of elements by moving the contents of an + /// input span into their place. On return, the span is left empty. + /// + /// This method has the effect of removing the specified range of elements + /// from the deque and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `items` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(moving:at:)`. + /// + /// Likewise, if you pass a zero-length buffer as the `items` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - items: An input span whose contents are to be moved into the deque. + /// + /// - Complexity: O(`self.count` + `items.count`) + @_alwaysEmitIntoClient + public mutating func replace( + removing subrange: Range, + moving items: inout InputSpan + ) { + items.withUnsafeMutableBufferPointer { buffer, count in + let source = buffer._extracting(last: count) + unsafe self.replace(removing: subrange, moving: source) + count = 0 + } + } +#endif + + /// Replaces the specified range of elements by moving the contents of an + /// output span into their place. On return, the span is left empty. + /// + /// This method has the effect of removing the specified range of elements + /// from the deque and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `items` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(moving:at:)`. + /// + /// Likewise, if you pass a zero-length buffer as the `items` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the deque. + /// - items: An output span whose contents are to be moved into the deque. + /// + /// - Complexity: O(`self.count` + `items.count`) + @_alwaysEmitIntoClient + public mutating func replace( + removing subrange: Range, + moving items: inout OutputSpan + ) { + items.withUnsafeMutableBufferPointer { buffer, count in + let source = buffer._extracting(first: count) + unsafe self.replace(removing: subrange, moving: source) + count = 0 + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Replaces the specified range of elements by at most `newItemCount` items + /// generated by a producer. + /// + /// This method has the effect of removing the specified range of elements + /// from the deque and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the items generated by `producer` at `subrange.lowerBound`. This + /// case is more directly expressed by calling `insert(moving:at:)`. + /// + /// Likewise, if the given producer is empty, then this method removes the + /// elements in the given subrange without replacement. This case is more + /// directly expressed by calling `removeSubrange`. + /// + /// This operation inserts as many items as the producer can generate before + /// either reaching `newItemCount`, or the producer hitting its end, or + /// throwing an error. If the producer has more than `newItemCount` items left in + /// its underlying sequence, then extra items remain available after this + /// method returns. + /// + /// If the operation inserts fewer than `newItemCount` items, then it results in + /// a gap in ring buffer storage that needs to be closed by moving some + /// items to their correct positions given the adjusted count. This adds some + /// overhead compared to adding exactly as many items as promised. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - newItemCount: The maximum number of items to insert into the deque. + /// - producer: A producer that generates the items to append. + /// + /// - Complexity: O(`self.count` + `maximumCount`) + @_alwaysEmitIntoClient + public mutating func replace< + P: Producer & ~Copyable & ~Escapable + >( + removing subrange: Range, + addingCount newItemCount: Int, + from producer: inout P + ) throws(P.ProducerError) { + try replace( + removing: subrange, + addingCount: newItemCount + ) { target throws(P.ProducerError) in + try producer.generate(into: &target) + } + } +#endif +} + +@available(SwiftStdlib 5.0, *) +extension RigidDeque /* where Element: Copyable */ { + /// Replaces the specified subrange of elements by copying the elements of + /// the given buffer pointer, which must be fully initialized. + /// + /// This method has the effect of removing the specified range of elements + /// from the deque and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `items` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(copying:at:)`. + /// + /// Likewise, if you pass a zero-length buffer as the `items` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - items: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `items.count`) + @inlinable + public mutating func replace( + removing subrange: Range, + copying items: UnsafeBufferPointer + ) { + var remainder = items + replace(removing: subrange, addingCount: remainder.count) { target in + target.withUnsafeMutableBufferPointer { dst, dstCount in + dst.initializeAll(fromContentsOf: remainder._trim(first: dst.count)) + dstCount += dst.count + } + } + assert(remainder.isEmpty) + } + + /// Replaces the specified subrange of elements by copying the elements of + /// the given buffer pointer, which must be fully initialized. + /// + /// This method has the effect of removing the specified range of elements + /// from the deque and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `items` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(copying:at:)`. + /// + /// Likewise, if you pass a zero-length buffer as the `items` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - items: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `items.count`) + @inlinable + public mutating func replace( + removing subrange: Range, + copying items: UnsafeMutableBufferPointer + ) { + unsafe self.replace( + removing: subrange, + copying: UnsafeBufferPointer(items)) + } + + /// Replaces the specified subrange of elements by copying the elements of + /// the given span. + /// + /// This method has the effect of removing the specified range of elements + /// from the deque and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `items` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(copying:at:)`. + /// + /// Likewise, if you pass a zero-length span as the `items` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - items: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `items.count`) + @inlinable + public mutating func replace( + removing subrange: Range, + copying items: Span + ) { + unsafe items.withUnsafeBufferPointer { buffer in + unsafe self.replace(removing: subrange, copying: buffer) + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @inlinable + internal mutating func _replace< + C: Container & ~Copyable & ~Escapable + >( + removing subrange: Range, + copyingContainer items: borrowing C, + newCount: Int + ) { + + let expectedCount = self.count - subrange.count + newCount + var it = items.makeBorrowingIterator() + self.replace(removing: subrange, addingCount: newCount) { target in + it.copyContents(into: &target) + } + precondition( + it.nextSpan().isEmpty && count == expectedCount, + "Broken Container: count doesn't match contents") + } +#endif + + @inlinable + internal mutating func _replace( + removing subrange: Range, + copyingCollection items: __owned some Collection, + newCount: Int + ) { + let done: Void? = items.withContiguousStorageIfAvailable { src in + precondition( + src.count == newCount, + "Broken Collection: count doesn't match contents") + self.replace(removing: subrange, copying: src) + } + if done != nil { return } + + var i = items.startIndex + self.replace(removing: subrange, addingCount: newCount) { target in + while !target.isFull { + target.append(items[i]) + items.formIndex(after: &i) + } + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Replaces the specified subrange of elements by copying the elements of + /// the given container. + /// + /// This method has the effect of removing the specified range of elements + /// from the deque and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `items` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(copying:at:)`. + /// + /// Likewise, if you pass a zero-length container as the `items` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the array. + /// - items: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `items.count`) + @inlinable + @inline(__always) + public mutating func replace< + C: Container & ~Copyable & ~Escapable + >( + removing subrange: Range, + copying items: borrowing C + ) { + _replace( + removing: subrange, copyingContainer: items, newCount: items.count) + } +#endif + + /// Replaces the specified subrange of elements by copying the elements of + /// the given collection. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `items` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(copying:at:)`. + /// + /// Likewise, if you pass a zero-length collection as the `items` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - items: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `items.count`) + @inlinable + @inline(__always) + public mutating func replace( + removing subrange: Range, + copying items: __owned some Collection + ) { + _replace( + removing: subrange, copyingCollection: items, newCount: items.count) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Replaces the specified subrange of elements by copying the elements of + /// the given container. + /// + /// This method has the effect of removing the specified range of elements + /// from the deque and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `items` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(copying:at:)`. + /// + /// Likewise, if you pass a zero-length container as the `items` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the array. + /// - items: The new elements to copy into the collection. + /// + /// - Complexity: O(*n* + *m*), where *n* is count of this deque and + /// *m* is the count of `items`. + @inlinable + @inline(__always) + public mutating func replace< + C: Container & Collection + >( + removing subrange: Range, + copying items: C + ) { + _replace( + removing: subrange, copyingContainer: items, newCount: items.count) + } +#endif +} + +#endif diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Testing.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Testing.swift new file mode 100644 index 00000000..cd6a0d12 --- /dev/null +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Testing.swift @@ -0,0 +1,60 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2025 - 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +// This file contains exported but non-public entry points to support clear box +// testing. + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: ~Copyable { + /// The number of the storage slot in this deque that holds the first element. + /// (Or would hold it after an insertion in case the deque is currently + /// empty.) + /// + /// This property isn't intended to be used outside of `DequeModule`'s own test + /// target. + @usableFromInline + package var _startSlot: Int { + _handle.startSlot.position + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidDeque { + /// Constructs a deque instance of the specified contents and layout. Exposed + /// as public to allow exhaustive input/output tests for `RigidDeque` members. + /// + /// This initializer isn't intended to be used outside of `DequeModule`'s + /// own test target. + @usableFromInline + package init( + _capacity capacity: Int, + startSlot: Int, + copying contents: some Sequence + ) { + let contents = Array(contents) + + self.init(capacity: capacity) + _handle.startSlot = _handle.slot(_handle.startSlot, offsetBy: startSlot) + self.append(copying: contents) + assert(self.capacity == capacity) + assert(self._startSlot == startSlot) + assert(self.count == contents.count) + } +} + +#endif diff --git a/Sources/DequeModule/RigidDeque/RigidDeque.swift b/Sources/DequeModule/RigidDeque/RigidDeque.swift new file mode 100644 index 00000000..d92efbb3 --- /dev/null +++ b/Sources/DequeModule/RigidDeque/RigidDeque.swift @@ -0,0 +1,361 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2025 - 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(<6.2) + +/// A fixed capacity, heap allocated, noncopyable double-ended queue of +/// potentially noncopyable elements. +@frozen +@available(*, unavailable, message: "RigidDeque requires a Swift 6.2 toolchain") +public struct RigidDeque: ~Copyable { + public init() { + fatalError() + } +} + +#else + +/// A fixed capacity, heap allocated, noncopyable double-ended queue of +/// potentially noncopyable elements. A deque (pronounced "deck") +/// is an ordered random-access container that supports efficient +/// insertions and removals from both ends. +/// +/// Deques implement the same indexing semantics as arrays: they use integer +/// indices, and the first element of a nonempty deque is always at logical +/// index zero. +/// +/// var colors = RigidDeque(capacity: 5) +/// colors.append("red") +/// colors.prepend("yellow") +/// colors.append("blue") +/// // `colors` now contains "yellow", "red", "blue" +/// +/// print(colors[0]) // prints "yellow" +/// print(colors[1]) // prints "red" +/// +/// print(colors.removeFirst()) // prints "yellow" +/// print(colors.removeLast()) // prints "blue" +/// // `colors` now contains "red" +/// +/// This double-ended nature makes deques particularly well-suited for +/// representing first-in-first-out (FIFO) buffers, where new items are +/// inserted at one end, and old items are retrieved from the other. +/// For example, they are ideal for modeling buffered data streams, such as +/// networking channels, or other producer/consumer scenarios. +/// +/// ### Implementation Notes +/// +/// `RigidDeque` implements a ring buffer. It stores its elements in a +/// single heap-allocated buffer, and to allow fast insertions and removals +/// from both ends, the buffer behaves as if its ends were glued together into +/// a ring shape. This comes at the cost of potentially discontiguous storage, as +/// the contents of the ring buffer sometimes wrap around the edges. +/// +/// While the first item in the deque is always addressed by the logical index +/// zero, its physical location can be anywhere in the underlying ring buffer. +/// Compare this with `RigidArray`'s contiguous storage, where the first item +/// is always stored at the start of the buffer, so new data can always be +/// efficiently appended to the end, but inserting at the front is relatively +/// slow, as existing elements need to be shifted to make room. +/// +/// ### Fixed Storage Capacity +/// +/// `RigidDeque` instances are created with a specific maximum capacity. +/// Elements can be added to the deque up to that capacity, but no more: trying +/// to add an item to a full deque results in a runtime trap. +/// +/// var items = RigidDeque(capacity: 2) +/// items.prepend(1) +/// items.prepend(2) +/// items.prepend(3) // Runtime error: RigidDeque capacity overflow +/// +/// Rigid deques provide convenience properties to help verify that it has +/// enough available capacity: `isFull` and `freeCapacity`. +/// +/// guard items.freeCapacity >= 4 else { throw CapacityOverflow() } +/// items.append(copying: newItems) +/// +/// It is possible to extend or shrink the capacity of a rigid deque instance, +/// but this needs to be done explicitly, with operations dedicated to this +/// purpose (such as ``reserveCapacity`` and ``reallocate(capacity:)``). +/// The deque never resizes itself automatically. +/// +/// Therefore, it is necessary to perform careful manual analysis (or up front +/// runtime capacity checks) to prevent the deque from overflowing its storage. +/// This makes this type more difficult to use than a dynamically resizing +/// container. However, it allows this construct to provide predictably stable +/// performance. +/// +/// This trading of usability in favor of stable performance limits `RigidDeque` +/// to the most resource-constrained of use cases, such as space-constrained +/// environments that require carefully accounting of every heap allocation, or +/// time-constrained applications that cannot accommodate unexpected latency +/// spikes due to a reallocation getting triggered at an inopportune moment. +/// +/// For use cases outside of these narrow domains, we generally recommmend +/// to use the dynamically resizing ``UniqueDeque`` type rather than +/// `RigidDeque`. For copyable elements, the copy-on-write `Deque` type is an +/// even more convenient and expressive choice. +@available(SwiftStdlib 5.0, *) +@frozen +@safe +public struct RigidDeque: ~Copyable { + @usableFromInline + internal typealias _Slot = _DequeSlot + + @usableFromInline + package typealias _UnsafeHandle = _UnsafeDequeHandle + + @usableFromInline + package var _handle: _UnsafeHandle + + @_alwaysEmitIntoClient + @inline(__always) + package init(_handle: consuming _UnsafeHandle) { + self._handle = _handle + } + + @inlinable + @inline(__always) + deinit { + _handle.dispose() + } + + @inlinable @inline(__always) + package mutating func _takeHandle() -> _UnsafeHandle { + exchange(&_handle, with: .allocate(capacity: 0)) + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidDeque: @unchecked Sendable where Element: Sendable & ~Copyable {} + +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: ~Copyable { +#if COLLECTIONS_INTERNAL_CHECKS + @usableFromInline @inline(never) @_effects(releasenone) + package func _checkInvariants() { + _handle._checkInvariants() + } +#else + @_transparent + package func _checkInvariants() {} +#endif // COLLECTIONS_INTERNAL_CHECKS +} + + +//MARK: - Basics + +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: ~Copyable { + /// The maximum number of elements this rigid deque can hold. + /// + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @_transparent + public var capacity: Int { _assumeNonNegative(_handle.capacity) } + + /// The number of additional elements that can be added to this deque without + /// exceeding its storage capacity. + /// + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @_transparent + public var freeCapacity: Int { _assumeNonNegative(capacity &- count) } + + /// A Boolean value indicating whether this rigid deque is fully populated. + /// If this property returns true, then the array's storage is at capacity, + /// and it cannot accommodate any additional elements. + /// + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @_transparent + public var isFull: Bool { count == capacity } +} + +//MARK: - Container primitives + +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: ~Copyable { + /// A type that represents a position in the deque: an integer offset from its + /// logical start position. + /// + /// Valid indices consist of the position of every element and a "past the + /// end" position that’s not valid for use as a subscript argument. + public typealias Index = Int + + /// A Boolean value indicating whether this deque contains no elements. + /// + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @_transparent + public var isEmpty: Bool { _handle.count == 0 } + + /// The number of elements in this deque. + /// + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @_transparent + public var count: Int { _handle.count } + + /// The position of the first element in a nonempty deque. This is always zero. + /// + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @_transparent + public var startIndex: Int { 0 } + + /// The deque’s "past the end” position—that is, the position one greater than + /// the last valid subscript argument. This is always equal to the deque's + /// count. + /// + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @_transparent + public var endIndex: Int { _handle.count } + + /// The range of indices that are valid for subscripting this deque. + /// + /// - Complexity: O(1) + @inlinable + @inline(__always) + public var indices: Range { unsafe Range(uncheckedBounds: (0, count)) } + + @_alwaysEmitIntoClient + @_transparent + package func _checkItemIndex(_ index: Int) { + precondition( + UInt(bitPattern: index) < UInt(bitPattern: _handle.count), + "Index out of bounds") + } + + @_alwaysEmitIntoClient + @_transparent + package func _checkValidIndex(_ index: Int) { + precondition( + UInt(bitPattern: index) <= UInt(bitPattern: _handle.count), + "Index out of bounds") + } + + @_alwaysEmitIntoClient + @_transparent + package func _checkValidBounds(_ subrange: Range) { + precondition( + subrange.lowerBound >= 0 && subrange.upperBound <= _handle.count, + "Index range out of bounds") + } + + @_alwaysEmitIntoClient + public subscript(position: Int) -> Element { + // FIXME: Replace with borrow/mutate accessors + @inline(__always) + @_transparent + unsafeAddress { + _checkItemIndex(position) + let slot = _handle.slot(forOffset: position) + return _handle.ptr(at: slot) + } + @inline(__always) + @_transparent + unsafeMutableAddress { + _checkItemIndex(position) + let slot = _handle.slot(forOffset: position) + return _handle.mutablePtr(at: slot) + } + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: ~Copyable { + /// Exchanges the values at the specified indices of the deque. + /// + /// Both parameters must be valid indices of the deque and not equal to + /// `endIndex`. Passing the same index as both `i` and `j` has no effect. + /// + /// - Parameter i: The index of the first value to swap. + /// - Parameter j: The index of the second valud to swap. + /// + /// - Complexity: O(1) + @inlinable + public mutating func swapAt(_ i: Int, _ j: Int) { + _checkItemIndex(i) + _checkItemIndex(j) + _handle.uncheckedSwapAt(i, j) + } +} + +//MARK: - Resizing + +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: ~Copyable { + /// Grow or shrink the capacity of a rigid deque instance without discarding + /// its contents. + /// + /// This operation replaces the deque's storage buffer with a newly allocated + /// buffer of the specified capacity, moving all existing elements + /// to its new storage. The old storage is then deallocated. + /// + /// - Parameter newCapacity: The desired new capacity. `newCapacity` must be + /// greater than or equal to the current count. + /// + /// - Complexity: O(`count`) + @_alwaysEmitIntoClient + public mutating func reallocate(capacity newCapacity: Int) { + _handle.reallocate(capacity: newCapacity) + } + + /// Ensure that the deque has capacity to store the specified number of + /// elements, by growing its storage buffer if necessary. + /// + /// If `capacity < n`, then this operation reallocates the rigid deque's + /// storage to grow it; on return, the deque's capacity becomes `n`. + /// Otherwise the deque is left as is. + /// + /// - Complexity: O(`count`) + @inlinable + public mutating func reserveCapacity(_ n: Int) { + guard capacity < n else { return } + reallocate(capacity: n) + } +} + +//MARK: - Copying helpers + +@available(SwiftStdlib 5.0, *) +extension RigidDeque { + /// Copy the contents of this deque into a newly allocated rigid deque + /// instance with just enough capacity to hold all its elements. + /// + /// - Complexity: O(`count`) + @_alwaysEmitIntoClient + public func clone() -> Self { + RigidDeque(_handle: _handle.allocateCopy(capacity: count)) + } + + /// Copy the contents of this deque into a newly allocated rigid deque + /// instance with the specified capacity. + /// + /// - Parameter capacity: The desired capacity of the resulting rigid deque. + /// `capacity` must be greater than or equal to `count`. + /// + /// - Complexity: O(`count`) + @_alwaysEmitIntoClient + public func clone(capacity: Int) -> Self { + RigidDeque(_handle: _handle.allocateCopy(capacity: capacity)) + } +} + +#endif // compiler(<6.2) diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Append.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Append.swift new file mode 100644 index 00000000..7302dde2 --- /dev/null +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Append.swift @@ -0,0 +1,371 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2025 - 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque where Element: ~Copyable { + /// Adds an element to the end of the deque. + /// + /// If the deque does not have sufficient capacity to hold any more elements, + /// then this reallocates the deque's storage to grow its capacity, using a + /// geometric growth rate. + /// + /// - Parameter item: The element to append to the collection. + /// + /// - Complexity: O(1) as amortized over many invocations on the same deque. + @_alwaysEmitIntoClient + @_transparent + public mutating func append(_ newElement: consuming Element) { + _ensureFreeCapacity(1) + _storage._handle.uncheckedAppend(newElement) + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque where Element: ~Copyable { + /// Efficiently append a given number of items to the back of this deque by + /// populating a series of storage regions through repeated calls of the + /// specified callback function. + /// + /// If the deque doesn't have sufficient capacity to accommodate the specified + /// number of new elements, then this method reallocates the deque's storage + /// to grow it, using a geometric growth rate. + /// + /// var buffer = UniqueDeque() + /// buffer.append(999) + /// var i = 0 + /// buffer.append(maximumCount: 6) { target in + /// while !target.isFull { + /// target.append(i) + /// i += 1 + /// } + /// } + /// // `buffer` now contains [999, 0, 1, 2, 3, 4, 5, 6] + /// + /// The newly appended items are not guaranteed to form a single contiguous + /// storage region. Therefore, the supplied callback may be invoked multiple + /// times to initialize each successive chunk of storage. However, invocations + /// cease when the callback fails to fully populate its output span or if + /// it throws an error. In such cases, the deque keeps all items that were + /// successfully initialized before the callback terminated the append. + /// + /// var buffer = UniqueDeque() + /// buffer.append(999) + /// var i = 0 + /// buffer.append(maximumCount: 6) { target in + /// while !target.isFull, i <= 3 { + /// target.append(i) + /// i += 1 + /// } + /// } + /// // `buffer` now contains [999, 0, 1, 2, 3] + /// + /// - Parameters: + /// - maximumCount: The maximum number of items to append to the deque. + /// - body: A callback that gets called at most twice to directly + /// populate newly reserved storage within the deque. + /// + /// - Complexity: O(`maximumCount`) in addition to the complexity of the callback + /// invocations, when amortized over many similar invocations on the same + /// deque. + @_alwaysEmitIntoClient + @inline(__always) + public mutating func append( + maximumCount: Int, + initializingWith body: (inout OutputSpan) throws(E) -> Void + ) throws(E) -> Void { + guard maximumCount > 0 else { return } + _ensureFreeCapacity(maximumCount) + try _storage._handle.uncheckedAppend( + maximumCount: maximumCount, initializingWith: body) + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque where Element: ~Copyable { + /// Moves the elements of a buffer to the end of this deque, leaving the + /// buffer uninitialized. + /// + /// If the deque doesn't have sufficient capacity to accommodate the new + /// elements, then this method reallocates the deque's storage to grow it, + /// using a geometric growth rate. + /// + /// - Parameters: + /// - items: A fully initialized buffer whose contents to move into + /// the deque. + /// + /// - Complexity: O(`items.count`) when amortized over many similar + /// invocations on the same deque. + @_alwaysEmitIntoClient + public mutating func append( + moving items: UnsafeMutableBufferPointer + ) { + _ensureFreeCapacity(items.count) + _storage._handle.uncheckedAppend(moving: items) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Moves the elements of an input span by appending them to the end of + /// this deque, leaving the span empty. + /// + /// If the deque doesn't have sufficient capacity to accommodate the new + /// elements, then this method reallocates the deque's storage to grow it, + /// using a geometric growth rate. + /// + /// - Parameters: + /// - items: An input span whose contents need to be appended to this deque. + /// + /// - Complexity: O(`items.count`) when amortized over many similar + /// invocations on the same deque. + @_alwaysEmitIntoClient + public mutating func append( + moving items: inout InputSpan + ) { + items.withUnsafeMutableBufferPointer { buffer, count in + let source = buffer._extracting(last: count) + unsafe self.append(moving: source) + count = 0 + } + } +#endif + + /// Moves the elements of an output span by appending them to the end of + /// this deque, leaving the span empty. + /// + /// If the deque doesn't have sufficient capacity to accommodate the new + /// elements, then this method reallocates the deque's storage to grow it, + /// using a geometric growth rate. + /// + /// - Parameters: + /// - items: An output span whose contents need to be appended to this deque. + /// + /// - Complexity: O(`items.count`) when amortized over many similar + /// invocations on the same deque. + @_alwaysEmitIntoClient + public mutating func append( + moving items: inout OutputSpan + ) { + items.withUnsafeMutableBufferPointer { buffer, count in + let source = buffer._extracting(first: count) + unsafe self.append(moving: source) + count = 0 + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Appends at most `maximumCount` items generated by a producer to the end of + /// this deque. If `maximumCount` is nil, this appends every item the producer + /// can generate. + /// + /// If the deque doesn't have sufficient capacity to accommodate the specified + /// number of new elements, then this method reallocates the deque's storage + /// to grow it, using a geometric growth rate. + /// + /// This operation appends as many items as the producer can generate before + /// either reaching its end (or throwing an error), or filling the specified + /// capacity. This operation only consumes the first `maximumCount` items in the + /// producer; if the producer has more, then they remain available after this + /// method returns. + /// + /// - Parameters: + /// - maximumCount: The maximum number of items to append to the deque, or + /// nil to append every item the producer generates. + /// - producer: A producer that generates the items to append. + /// + /// - Complexity: O(*n*) where *n* is the number of new items, when + /// amortized over many similar invocations on the same deque. + @_alwaysEmitIntoClient + public mutating func append< + P: Producer & ~Copyable & ~Escapable + >( + maximumCount: Int? = nil, + from producer: inout P + ) throws(P.ProducerError) { + if let maximumCount { + _ensureFreeCapacity(maximumCount) + try _storage._handle.uncheckedAppend( + maximumCount: maximumCount + ) { target throws(P.ProducerError) in + while !target.isFull, try producer.generate(into: &target) { + // Do nothing + } + } + return + } + + while true { + _ensureFreeCapacity(1) + try _storage._handle.uncheckedAppend( + maximumCount: freeCapacity + ) { target throws(P.ProducerError) in + while !target.isFull, try producer.generate(into: &target) { + // Do nothing + } + } + } + } +#endif +} + + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque /*where Element: Copyable*/ { + /// Copies the elements of a buffer and append them to the end of this + /// deque. + /// + /// If the deque doesn't have sufficient capacity to accommodate the specified + /// number of new elements, then this method reallocates the deque's storage + /// to grow it, using a geometric growth rate. + /// + /// - Parameters: + /// - items: A fully initialized buffer whose contents to copy into + /// the deque. + /// + /// - Complexity: O(`items.count`) when amortized over many similar + /// invocations on the same deque. + @_alwaysEmitIntoClient + public mutating func append( + copying items: UnsafeBufferPointer + ) { + _ensureFreeCapacity(items.count) + unsafe _storage.append(copying: items) + } + + /// Copies the elements of a buffer to the end of this deque. + /// + /// If the deque doesn't have sufficient capacity to accommodate the specified + /// number of new elements, then this method reallocates the deque's storage + /// to grow it, using a geometric growth rate. + /// + /// - Parameters: + /// - items: A fully initialized buffer whose contents to copy into + /// the deque. + /// + /// - Complexity: O(`items.count`) when amortized over many similar + /// invocations on the same deque. + @_alwaysEmitIntoClient + public mutating func append( + copying items: UnsafeMutableBufferPointer + ) { + unsafe self.append(copying: UnsafeBufferPointer(items)) + } + + /// Copies the elements of a span to the end of this deque. + /// + /// If the deque doesn't have sufficient capacity to accommodate the specified + /// number of new elements, then this method reallocates the deque's storage + /// to grow it, using a geometric growth rate. + /// + /// - Parameters: + /// - items: A span whose contents to copy into the deque. + /// + /// - Complexity: O(`items.count`) when amortized over many similar + /// invocations on the same deque. + @_alwaysEmitIntoClient + public mutating func append(copying items: Span) { + _ensureFreeCapacity(items.count) + _storage.append(copying: items) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @_alwaysEmitIntoClient + internal mutating func _append< + S: BorrowingSequence & ~Copyable & ~Escapable + >(copying items: borrowing S) { + var it = items.makeBorrowingIterator() + while true { + let span = it.nextSpan() + if span.isEmpty { break } + self.append(copying: span) + } + } + + /// Copies the elements of a borrowing sequence and append them to the end of + /// this deque. + /// + /// If the deque doesn't have sufficient capacity to accommodate the new + /// elements, then this method reallocates the deque's storage to grow it, + /// using a geometric growth rate. + /// + /// - Parameters: + /// - items: The new elements to copy into the deque. + /// + /// - Complexity: O(*m*), where *m* is the length of `items`, when amortized + /// over many similar invocations on the same deque + @_alwaysEmitIntoClient + public mutating func append & ~Copyable & ~Escapable>( + copying items: borrowing S + ) { + self._append(copying: items) + } +#endif + + /// Copies the elements of a sequence to the end of this deque. + /// + /// If the deque does not have sufficient capacity to hold enough elements, + /// then this reallocates the deque's storage to extend its capacity, using + /// a geometric growth rate. If the input sequence does not provide a correct + /// estimate of its count, then the deque's storage may need to be resized + /// more than once. + /// + /// - Parameters: + /// - items: The new elements to copy into the deque. + /// + /// - Complexity: O(*m*), where *m* is the length of `items`, when + /// amortized over many similar invocations over the same deque. + @_alwaysEmitIntoClient + public mutating func append(copying items: some Sequence) { + let done: Void? = items.withContiguousStorageIfAvailable { buffer in + _ensureFreeCapacity(buffer.count) + unsafe _storage.append(copying: buffer) + return + } + if done != nil { return } + + _ensureFreeCapacity(items.underestimatedCount) + var it = _storage._handle.uncheckedAppend(copyingPrefixOf: items) + while let item = it.next() { + _ensureFreeCapacity(1) + _storage.append(item) + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Copies the elements of a borrowing sequence to the end of this deque. + /// + /// If the deque doesn't have sufficient capacity to accommodate the new + /// elements, then this method reallocates the deque's storage to grow it, + /// using a geometric growth rate. + /// + /// - Parameters: + /// - items: The new elements to copy into the deque. + /// + /// - Complexity: O(*m*), where *m* is the length of `items`, when + /// amortized over many similar invocations over the same deque. + @_alwaysEmitIntoClient + public mutating func append< + S: BorrowingSequence & Sequence + >( + copying items: S + ) { + self._append(copying: items) + } +#endif + +} + +#endif diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Consumption.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Consumption.swift new file mode 100644 index 00000000..e0cae681 --- /dev/null +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Consumption.swift @@ -0,0 +1,203 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque where Element: ~Copyable { +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Remove the specified subrange of items from this deque, + /// passing a series of input spans to a given callback function to consume + /// them in place. + /// + /// The callback is not required to fully consume the contents of its + /// argument; any items it leaves in the input span get automatically + /// consumed. The underlying storage isn't necessarily contiguous, so + /// the callback may be called more than once, whether or not it fully + /// consumes its input. If the specified range is empty, the callback + /// may not be called at all. + /// + /// - Parameter subrange: The subrange of items to consume from this deque. + /// - Parameter consumer: A function taking an input span of the removed items, + /// allowing them to be consumed straight out of the deque's storage. + /// The function is called at most once. + /// + /// - Complexity: O(`self.count`) + @_alwaysEmitIntoClient + @inline(__always) + public mutating func consume( + _ subrange: Range, + consumingWith consumer: (inout InputSpan) -> Void + ) { + _storage.consume(subrange, consumingWith: consumer) + } + + /// Remove the specified subrange of items from this deque, + /// passing a series of input spans to a given callback function to consume + /// them in place. + /// + /// The callback is not required to fully consume the contents of its + /// argument; any items it leaves in the input span get automatically + /// consumed. The underlying storage isn't necessarily contiguous, so + /// the callback may be called more than once, whether or not it fully + /// consumes its input. If the specified range is empty, the callback + /// may not be called at all. + /// + /// - Parameter subrange: The subrange of items to consume from this deque. + /// - Parameter consumer: A function taking an input span of the removed items, + /// allowing them to be consumed straight out of the deque's storage. + /// The function is called at most once. + /// + /// - Complexity: O(`self.count`) + @_alwaysEmitIntoClient + @inline(__always) + public mutating func consume>( + _ subrange: R, + consumingWith consumer: (inout InputSpan) -> Void + ) { + consume(subrange.relative(to: indices), consumingWith: consumer) + } + + /// Remove all items currently in this deque, passing a series of input + /// spans to a given callback function to consume them in place. + /// + /// The callback is not required to fully consume the contents of its + /// argument; any items it leaves in the input span get automatically + /// consumed. The underlying storage isn't necessarily contiguous, so + /// the callback may be called more than once, whether or not it fully + /// consumes its input. If the specified range is empty, the callback + /// may not be called at all. + /// + /// - Parameter consumer: A function taking an input span of the removed items, + /// allowing them to be consumed straight out of the deque's storage. + /// The function is called at most once. + /// - Complexity: O(`self.count`) + @_alwaysEmitIntoClient + @inline(__always) + public mutating func consumeAll( + consumingWith consumer: (inout InputSpan) -> Void + ) { + consume(indices, consumingWith: consumer) + } + + /// Remove the specified number of items from the end of this deque, + /// passing an input span to a given callback function to consume them in + /// place. + /// + /// The callback is not required to fully consume the contents of its + /// argument; any items it leaves in the input span get automatically + /// consumed. The underlying storage isn't necessarily contiguous, so + /// the callback may be called more than once, whether or not it fully + /// consumes its input. If the specified range is empty, the callback + /// may not be called at all. + /// + /// - Parameter n: The number of items to consume from the end of the deque. + /// `n` must be greater than or equal to zero and must not exceed + /// the count of the deque. + /// - Parameter consumer: A function taking an input span of the removed items, + /// allowing them to be consumed straight out of the deque's storage. + /// - Complexity: O(`n`) + @_alwaysEmitIntoClient + @inline(__always) + public mutating func consumeLast( + _ n: Int, + consumingWith consumer: (inout InputSpan) -> Void + ) { + _storage.consumeLast(n, consumingWith: consumer) + } + + /// Remove the specified number of items from the front of this deque, + /// passing an input span to a given callback function to consume them in + /// place. + /// + /// The callback is not required to fully consume the contents of its + /// argument; any items it leaves in the input span get automatically + /// consumed. The underlying storage isn't necessarily contiguous, so + /// the callback may be called more than once, whether or not it fully + /// consumes its input. If the specified range is empty, the callback + /// may not be called at all. + /// + /// - Parameter n: The number of items to consume from the front of the deque. + /// `n` must be greater than or equal to zero and must not exceed + /// the count of the deque. + /// - Parameter consumer: A function taking an input span of the removed items, + /// allowing them to be consumed straight out of the deque's storage. + /// - Complexity: O(`n`) + @_alwaysEmitIntoClient + @inline(__always) + public mutating func consumeFirst( + _ n: Int, + consumingWith consumer: (inout InputSpan) -> Void + ) { + _storage.consumeFirst(n, consumingWith: consumer) + } + +#endif +} + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +@available(SwiftStdlib 5.0, *) +extension UniqueDeque where Element: ~Copyable { + public typealias SubrangeConsumer = RigidDeque.SubrangeConsumer + + @_alwaysEmitIntoClient + @inline(__always) + @_lifetime(&self) + public mutating func consume( + _ subrange: Range + ) -> SubrangeConsumer { + _storage.consume(subrange) + } + + @_alwaysEmitIntoClient + @inline(__always) + @_lifetime(&self) + public mutating func consume>( + _ subrange: R + ) -> SubrangeConsumer { + consume(subrange.relative(to: indices)) + } + + @_alwaysEmitIntoClient + @inline(__always) + @_lifetime(&self) + public mutating func consumeAll() -> SubrangeConsumer { + consume(indices) + } + + @_alwaysEmitIntoClient + @inline(__always) + @_lifetime(&self) + public mutating func consumeLast(_ n: Int) -> SubrangeConsumer { + precondition( + n >= 0 && n <= self.count, + "Count of elements to consume is out of bounds") + return consume(self.count - n ..< self.count) + } + + @_alwaysEmitIntoClient + @inline(__always) + @_lifetime(&self) + public mutating func consumeFirst(_ n: Int) -> SubrangeConsumer { + precondition( + n >= 0 && n <= self.count, + "Count of elements to consume is out of bounds") + return consume(0 ..< n) + } +} +#endif + +#endif diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift new file mode 100644 index 00000000..09f39802 --- /dev/null +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift @@ -0,0 +1,68 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque where Element: ~Copyable { +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + public typealias BorrowingIterator = RigidDeque.BorrowingIterator + + @_alwaysEmitIntoClient + @_lifetime(borrow self) + public borrowing func makeBorrowingIterator() -> BorrowingIterator { + BorrowingIterator(_deque: self._storage) + } +#endif +} + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +@available(SwiftStdlib 5.0, *) +extension UniqueDeque: Container where Element: ~Copyable {} +#endif + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque where Element: ~Copyable { + @_alwaysEmitIntoClient + @inline(__always) + public func index(after index: Int) -> Int { index + 1 } + + @_alwaysEmitIntoClient + @inline(__always) + public func formIndex(after index: inout Int) { index += 1 } + + @_alwaysEmitIntoClient + @inline(__always) + public func index(_ index: Int, offsetBy n: Int) -> Int { + index + n + } + + @_alwaysEmitIntoClient + public func formIndex( + _ index: inout Index, offsetBy n: inout Int, limitedBy limit: Index + ) { + index._advance(by: &n, limitedBy: limit) + } + + @_alwaysEmitIntoClient + @_lifetime(borrow self) + public func nextSpan(after index: inout Int, maximumCount: Int) -> Span { + _storage.nextSpan(after: &index, maximumCount: maximumCount) + } +} + +#endif diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Descriptions.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Descriptions.swift new file mode 100644 index 00000000..5378d5ec --- /dev/null +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Descriptions.swift @@ -0,0 +1,30 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque /*: CustomStringConvertible */ where Element: ~Copyable { + public var description: String { + /// FIXME: Print the item descriptions when available. + "<\(count) items>" + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque /*: CustomDebugStringConvertible */ where Element: ~Copyable { + public var debugDescription: String { + /// FIXME: Print the item descriptions when available. + "<\(count) items>" + } +} + +#endif diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Equatable.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Equatable.swift new file mode 100644 index 00000000..7ee9fc88 --- /dev/null +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Equatable.swift @@ -0,0 +1,29 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.2) + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +#endif + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque /*: Equatable */ where Element: Equatable /* & ~Copyable */ { + @inlinable + public static func ==( + left: borrowing Self, + right: borrowing Self + ) -> Bool { + left._storage == right._storage + } +} + +#endif diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Experimental.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Experimental.swift new file mode 100644 index 00000000..e150c28c --- /dev/null +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Experimental.swift @@ -0,0 +1,36 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + +#if false // FIXME + +@_alwaysEmitIntoClient +@_transparent +@_lifetime(borrow self) +public func borrowElement(at index: Int) -> Borrow { + _storage.borrowElement(at: index) +} + +@_alwaysEmitIntoClient +@_transparent +@_lifetime(&self) +public mutating func mutateElement(at index: Int) -> Inout { + _storage.mutateElement(at: index) +} + +#endif +#endif diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Hashable.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Hashable.swift new file mode 100644 index 00000000..25e0fccd --- /dev/null +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Hashable.swift @@ -0,0 +1,22 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque /*: Hashable */ where Element: Hashable /* & ~Copyable */ { + @inlinable + public func hash(into hasher: inout Hasher) { + self._storage.hash(into: &hasher) + } +} + +#endif diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Initializers.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Initializers.swift new file mode 100644 index 00000000..3d7d50bf --- /dev/null +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Initializers.swift @@ -0,0 +1,188 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2025 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque where Element: ~Copyable { + /// Initializes a new unique deque with no elements. + /// + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @_transparent + public init() { + _storage = .init(capacity: 0) + } + + /// Creates an empty unique deque with the specified capacity. + @_alwaysEmitIntoClient + @_transparent + public init(capacity: Int) { + _storage = .init(capacity: capacity) + } + + /// Creates a unique deque with the specified capacity, then calls the given + /// closure with an output span covering the deque's uninitialized memory. + /// + /// - Parameters: + /// - capacity: The number of elements to allocate space for in the new + /// rigid deque. + /// - initializer: A closure that initializes the elements of the new deque. + /// - Parameter outputSpan: An `OutputSpan` allowing initialization of the + /// deque's initial elements. + @inlinable @inline(__always) + public init( + capacity: Int, + initializingWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) { + _storage = try .init(capacity: capacity, initializingWith: initializer) + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque where Element: ~Copyable { + /// Creates a new unique deque taking over the storage of the specified + /// rigid deque instance, consuming it in the process. + /// + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @inline(__always) + public init(consuming deque: consuming RigidDeque) { + self._storage = deque + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque where Element: ~Copyable { +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Creates a new unique deque of the specified capacity, populating it with + /// all items generated by a given producer. + /// + /// - Parameters: + /// - producer: A producer that generates the items to append to the new + /// deque. + /// + /// - Complexity: O(`capacity`) + public init & ~Copyable & ~Escapable>( + capacity: Int, from producer: inout P + ) throws(P.ProducerError) { + self.init(capacity: capacity) + try self.append(from: &producer) + } +#endif +} + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque /*where Element: Copyable*/ { + /// Creates a new deque containing the specified number of a single, + /// repeated value. + /// + /// - Parameters: + /// - repeatedValue: The element to repeat. + /// - count: The number of times to repeat the value passed in the + /// `repeating` parameter. `count` must be zero or greater. + /// + /// - Complexity: O(`count`) + @inlinable + public init(repeating repeatedValue: Element, count: Int) { + self._storage = .init(repeating: repeatedValue, count: count) + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque /*where Element: Copyable*/ { +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Creates a new deque with the specified capacity, holding a copy + /// of the contents of a given borrowing sequence. + /// + /// - Parameters: + /// - capacity: The storage capacity of the new deque, or nil to let the + /// deque grow itself as needed to accomodate all items in `contents`. + /// - contents: A sequence whose contents to copy into the new deque. + @_alwaysEmitIntoClient + @inline(__always) + public init< + S: BorrowingSequence & ~Copyable & ~Escapable + >( + capacity: Int? = nil, + copying contents: borrowing S + ) { + self.init(capacity: capacity ?? 0) + self._append(copying: contents) + } +#endif + + /// Creates a new deque with the specified initial capacity, holding a copy + /// of the contents of a given sequence. + /// + /// - Parameters: + /// - capacity: The storage capacity of the new deque, or nil to let the + /// deque grow itself as needed to accomodate all items in `contents`. + /// - contents: The sequence whose contents to copy into the new deque. + @_alwaysEmitIntoClient + @inline(__always) + public init( + capacity: Int? = nil, + copying contents: some Sequence + ) { + self.init(capacity: capacity ?? contents.underestimatedCount) + self.append(copying: contents) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Creates a new deque with the specified capacity, holding a copy + /// of the contents of a given sequence. + /// + /// - Parameters: + /// - capacity: The storage capacity of the new deque, or nil to let the + /// deque grow itself as needed to accomodate all items in `contents`. + /// - contents: A sequence whose contents to copy into the new deque. + /// The sequence must not contain more than `capacity` elements. + @_alwaysEmitIntoClient + @inline(__always) + public init< + S: BorrowingSequence & Sequence + >( + capacity: Int? = nil, + copying contents: S + ) { + self.init(capacity: capacity ?? contents.underestimatedCount) + self._append(copying: contents) + } + + /// Creates a new deque with the specified capacity, holding a copy + /// of the contents of a given sequence. + /// + /// - Parameters: + /// - capacity: The storage capacity of the new deque. + /// - contents: A sequence whose contents to copy into the new deque. + /// The sequence must not contain more than `capacity` elements. + @_alwaysEmitIntoClient + @inline(__always) + public init< + S: BorrowingSequence & Collection + >( + capacity: Int? = nil, + copying contents: S + ) { + self.init(capacity: capacity ?? contents.count) + self._append(copying: contents) + } +#endif + +} + +#endif diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Insertions.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Insertions.swift new file mode 100644 index 00000000..899b27fa --- /dev/null +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Insertions.swift @@ -0,0 +1,515 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2025 - 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque where Element: ~Copyable { + /// Inserts a new element into the deque at the specified position. + /// + /// If the deque does not have sufficient capacity to hold any more elements, + /// then this reallocates the deque's storage to grow its capacity, using a + /// geometric growth rate. + /// + /// The new element is inserted before the element currently at the specified + /// index. If you pass the deque's `endIndex` as the `index` parameter, then + /// the new element is appended to the container. + /// + /// Existing elements in the deque's storage are moved as needed to make room + /// for the new item. (The direction of the move depends on the location of + /// the insertion, minimizing the cost.) + /// + /// - Parameter item: The new element to insert into the deque. + /// - Parameter index: The position at which to insert the new element. + /// `index` must be a valid index in the deque. + /// + /// - Complexity: O(`self.count`) when amortized over many similar + /// invocations on the same deque. + @_alwaysEmitIntoClient + @_transparent + public mutating func insert(_ item: consuming Element, at index: Int) { + _storage._checkValidIndex(index) + _ensureFreeCapacity(1) + _storage._handle.uncheckedInsert(item, at: index) + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque where Element: ~Copyable { + /// Inserts a given number of new items into this deque at the specified + /// position, using a callback to directly initialize deque storage by + /// populating a series of output spans. + /// + /// Existing elements in the deque's storage are moved as needed to make room + /// for the new items. (The direction of the move depends on the location of + /// the insertion, minimizing the cost.) + /// + /// If the deque does not have sufficient capacity to hold enough elements, + /// then this reallocates the deque's storage to grow its capacity, using a + /// geometric growth rate. + /// + /// var buffer = UniqueDeque(capacity: 20) + /// buffer.append([-999, 999]) + /// var i = 0 + /// buffer.insert(addingCount: 3, at: 1) { target in + /// while !target.isFull { + /// target.append(i) + /// i += 1 + /// } + /// } + /// // `buffer` now contains [-999, 0, 1, 2, 999] + /// + /// The newly inserted items are not guaranteed to form a single contiguous + /// storage region. Therefore, the supplied callback may be invoked multiple + /// times to initialize each successive chunk of storage. However, invocations + /// cease if the callback fails to fully populate its output span or if + /// it throws an error. In such cases, the deque keeps all items that were + /// successfully initialized before the callback terminated the prepend. + /// + /// Partial insertions create a gap in ring buffer storage that needs to be + /// closed by moving already inserted items to their correct positions given + /// the adjusted count. This adds some overhead compared to adding exactly as + /// many items as promised. + /// + /// - Parameters: + /// - newItemCount: The maximum number of items to insert into the deque. + /// - index: The position at which to insert the new items. + /// `index` must be a valid index in the deque. + /// - initializer: A callback that gets called at most twice to directly + /// populate newly reserved storage within the deque. The function + /// is always called with an empty output span. + /// + /// - Complexity: O(`self.count` + `newItemCount`) in addition to the complexity + /// of the callback invocations when amortized over many similar + /// invocations on the same deque. + @_alwaysEmitIntoClient + @inline(__always) + public mutating func insert( + addingCount newItemCount: Int, + at index: Int, + initializingWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) { + _storage._checkValidIndex(index) + precondition(newItemCount >= 0, "Cannot add a negative number of items") + _ensureFreeCapacity(newItemCount) + try _storage._handle.uncheckedInsert( + addingCount: newItemCount, at: index, initializingWith: initializer) + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque where Element: ~Copyable { + /// Inserts the elements of a fully initialized buffer by moving them into + /// this deque, starting at the specified position. After this operation, + /// the supplied buffer becomes uninitialized. + /// + /// Existing elements in the deque's storage are moved as needed to make room + /// for the new items. (The direction of the move depends on the location of + /// the insertion, minimizing the cost.) + /// + /// If the deque does not have sufficient capacity to hold enough elements, + /// then this reallocates the deque's storage to grow its capacity, using a + /// geometric growth rate. + /// + /// - Parameters: + /// - items: A fully initialized buffer whose contents to move into + /// the deque. + /// - index: The position at which to insert the new items. + /// `index` must be a valid index in the array. + /// + /// - Complexity: O(`self.count` + `items.count`) when amortized over many + /// similar invocations on the same deque. + @_alwaysEmitIntoClient + public mutating func insert( + moving items: UnsafeMutableBufferPointer, + at index: Int + ) { + guard !items.isEmpty else { return } + var remainder = items + insert(addingCount: items.count, at: index) { target in + target.withUnsafeMutableBufferPointer { buffer, count in + buffer.moveInitializeAll( + fromContentsOf: remainder._trim(first: buffer.count)) + count = buffer.count + } + } + assert(remainder.isEmpty) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Moves the elements of an input span into this deque, + /// starting at the specified position, and leaving the span empty. + /// + /// Existing elements in the deque's storage are moved as needed to make room + /// for the new items. (The direction of the move depends on the location of + /// the insertion, minimizing the cost.) + /// + /// If the deque does not have sufficient capacity to hold enough elements, + /// then this reallocates the deque's storage to grow its capacity, using a + /// geometric growth rate. + /// + /// - Parameters: + /// - items: An input span whose contents to move into + /// the deque. + /// - index: The position at which to insert the new items. + /// `index` must be a valid index in the deque. + /// + /// - Complexity: O(`self.count` + `items.count`) when amortized over many + /// similar invocations on the same deque. + @_alwaysEmitIntoClient + public mutating func insert( + moving items: inout InputSpan, + at index: Int + ) { + items.withUnsafeMutableBufferPointer { buffer, count in + let source = buffer._extracting(last: count) + unsafe self.insert(moving: source, at: index) + count = 0 + } + } +#endif + + /// Moves the elements of an output span into this deque, + /// starting at the specified position, and leaving the span empty. + /// + /// Existing elements in the deque's storage are moved as needed to make room + /// for the new items. (The direction of the move depends on the location of + /// the insertion, minimizing the cost.) + /// + /// If the deque does not have sufficient capacity to hold enough elements, + /// then this reallocates the deque's storage to grow its capacity, using a + /// geometric growth rate. + /// + /// - Parameters: + /// - items: An output span whose contents to move into + /// the deque. + /// - index: The position at which to insert the new items. + /// `index` must be a valid index in the deque. + /// + /// - Complexity: O(`self.count` + `items.count`) when amortized over many + /// similar invocations on the same deque. + @_alwaysEmitIntoClient + public mutating func insert( + moving items: inout OutputSpan, + at index: Int + ) { + items.withUnsafeMutableBufferPointer { buffer, count in + let source = buffer._extracting(first: count) + unsafe self.insert(moving: source, at: index) + count = 0 + } + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque where Element: ~Copyable { +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Inserts at most `newItemCount` items generated by a producer into this + /// deque, starting at the given index. + /// + /// Existing elements in the deque's storage are moved as needed to make room + /// for the new items. (The direction of the move depends on the location of + /// the insertion, minimizing the cost.) + /// + /// If the deque does not have sufficient capacity to hold enough items, + /// then this reallocates the deque's storage to grow its capacity, using a + /// geometric growth rate. + /// + /// This operation inserts as many items as the producer can generate before + /// either reaching `newItemCount`, or the producer hitting its end, or + /// throwing an error. If the producer has more than `newItemCount` items + /// left in its underlying sequence, then extra items remain available after + /// this method returns. + /// + /// If the operation inserts fewer than `newItemCount` items, then it results + /// in a gap in ring buffer storage that needs to be closed by moving some + /// items to their correct positions given the adjusted count. This adds some + /// overhead compared to adding exactly as many items as promised. + /// + /// - Parameters: + /// - newItemCount: The maximum number of items to insert into the deque. + /// - index: The position at which to insert the new items. + /// `index` must be a valid index in the deque. + /// - producer: A producer that generates the items to append. + /// + /// - Complexity: O(`self.count` + `newItemCount`) when amortized over many + /// similar invocations on the same deque. + @_alwaysEmitIntoClient + public mutating func insert< + P: Producer & ~Copyable & ~Escapable + >( + addingCount newItemCount: Int, + from producer: inout P, + at index: Int + ) throws(P.ProducerError) { + try insert(addingCount: newItemCount, at: index) { target throws(P.ProducerError) in + while !target.isFull, try producer.generate(into: &target) { + // Do nothing + } + } + } + #endif +} + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque /* where Element: Copyable */ { + /// Copies the elements of a fully initialized buffer pointer into this + /// deque at the specified position. + /// + /// The new elements are inserted before the element currently at the + /// specified index. If you pass the deque’s `endIndex` as the `index` + /// parameter, then the new elements are appended to the end of the array. + /// + /// Existing elements in the deque's storage are moved as needed to make room + /// for the new items. (The direction of the move depends on the location of + /// the insertion, minimizing the cost.) + /// + /// If the deque does not have sufficient capacity to hold enough items, + /// then this reallocates the deque's storage to grow its capacity, using a + /// geometric growth rate. + /// + /// - Parameters: + /// - items: The new elements to insert into the deque. The buffer + /// must be fully initialized. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of `self`. + /// + /// - Complexity: O(`count` + `newElements.count`) when amortized over many + /// similar invocations on the same deque. + @inlinable + public mutating func insert( + copying items: UnsafeBufferPointer, at index: Int + ) { + guard items.count > 0 else { return } + var remainder = items + insert(addingCount: remainder.count, at: index) { target in + target.withUnsafeMutableBufferPointer { buffer, count in + buffer.initializeAll( + fromContentsOf: remainder._extracting(first: buffer.count)) + remainder = remainder._extracting(droppingFirst: buffer.count) + count = buffer.count + } + } + assert(remainder.isEmpty) + } + + /// Copies the elements of a fully initialized buffer pointer into this + /// deque at the specified position. + /// + /// The new elements are inserted before the element currently at the + /// specified index. If you pass the deque’s `endIndex` as the `index` + /// parameter, then the new elements are appended to the end of the deque. + /// + /// Existing elements in the deque's storage are moved as needed to make room + /// for the new items. (The direction of the move depends on the location of + /// the insertion, minimizing the cost.) + /// + /// If the deque does not have sufficient capacity to hold enough items, + /// then this reallocates the deque's storage to grow its capacity, using a + /// geometric growth rate. + /// + /// - Parameters: + /// - items: The new elements to insert into the deque. The buffer + /// must be fully initialized. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of `self`. + /// + /// - Complexity: O(`count` + `newElements.count`) when amortized over many + /// similar invocations on the same deque. + @inlinable + public mutating func insert( + copying items: UnsafeMutableBufferPointer, + at index: Int + ) { + unsafe self.insert(copying: UnsafeBufferPointer(items), at: index) + } + + /// Copies the elements of a span into this deque at the specified position. + /// + /// The new elements are inserted before the element currently at the + /// specified index. If you pass the deque’s `endIndex` as the `index` + /// parameter, then the new elements are appended to the end of the deque. + /// + /// Existing elements in the deque's storage are moved as needed to make room + /// for the new items. (The direction of the move depends on the location of + /// the insertion, minimizing the cost.) + /// + /// If the deque does not have sufficient capacity to hold enough items, + /// then this reallocates the deque's storage to grow its capacity, using a + /// geometric growth rate. + /// + /// - Parameters: + /// - items: The new elements to insert into the deque. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of the deque. + /// + /// - Complexity: O(`count` + `items.count`) when amortized over many similar + /// invocations on the same deque. + @inlinable + public mutating func insert( + copying items: Span, at index: Int + ) { + unsafe items.withUnsafeBufferPointer { + unsafe self.insert(copying: $0, at: index) + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @inlinable + internal mutating func _insertContainer< + C: Container & ~Copyable & ~Escapable + >( + at index: Int, + copying items: borrowing C, + newCount: Int + ) { + let expectedCount = self.count + newCount + var it = items.makeBorrowingIterator() + insert(addingCount: newCount, at: index) { target in + it.copyContents(into: &target) + } + precondition( + it.nextSpan().isEmpty && count == expectedCount, + "Broken Container: count doesn't match contents") + } +#endif + + @inlinable + internal mutating func _insertCollection( + at index: Int, + copying items: some Collection, + newCount: Int + ) { + let done: Void? = items.withContiguousStorageIfAvailable { src in + self.insert(copying: src, at: index) + } + if done != nil { return } + + var i = items.startIndex + self.insert(addingCount: newCount, at: index) { target in + while !target.isFull { + target.append(items[i]) + items.formIndex(after: &i) + } + } + precondition( + i == items.endIndex, + "Broken Collection: count doesn't match contents") + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Copies the elements of a container into this deque at the specified + /// position. + /// + /// The new elements are inserted before the element currently at the + /// specified index. If you pass the deque’s `endIndex` as the `index` + /// parameter, then the new elements are appended to the end of the deque. + /// + /// Existing elements in the deque's storage are moved as needed to make room + /// for the new items. (The direction of the move depends on the location of + /// the insertion, minimizing the cost.) + /// + /// If the deque does not have sufficient capacity to hold enough items, + /// then this reallocates the deque's storage to grow its capacity, using a + /// geometric growth rate. + /// + /// - Parameters: + /// - newElements: The new elements to insert into the deque. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of the deque. + /// + /// - Complexity: O(`self.count` + `items.count`) when amortized over many + /// similar invocations on the same deque. + @_alwaysEmitIntoClient + @inline(__always) + public mutating func insert< + C: Container & ~Copyable & ~Escapable + >( + copying items: borrowing C, at index: Int + ) { + _insertContainer( + at: index, copying: items, newCount: items.count) + } +#endif + + /// Copies the elements of a collection into this deque at the specified + /// position. + /// + /// The new elements are inserted before the element currently at the + /// specified index. If you pass the deque’s `endIndex` as the `index` + /// parameter, then the new elements are appended to the end of the deque. + /// + /// Existing elements in the deque's storage are moved as needed to make room + /// for the new items. (The direction of the move depends on the location of + /// the insertion, minimizing the cost.) + /// + /// If the deque does not have sufficient capacity to hold enough items, + /// then this reallocates the deque's storage to grow its capacity, using a + /// geometric growth rate. + /// + /// - Parameters: + /// - items: The new elements to insert into the deque. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of the deque. + /// + /// - Complexity: O(`count` + `newElements.count`) when amortized over many + /// similar invocations on the same deque. + @inlinable + @inline(__always) + public mutating func insert( + copying items: some Collection, at index: Int + ) { + _insertCollection( + at: index, copying: items, newCount: items.count) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Copies the elements of a container into this deque at the specified + /// position. + /// + /// The new elements are inserted before the element currently at the + /// specified index. If you pass the deque's `endIndex` as the `index` + /// parameter, then the new elements are appended to the end of the deque. + /// + /// Existing elements in the deque's storage are moved as needed to make room + /// for the new items. (The direction of the move depends on the location of + /// the insertion, minimizing the cost.) + /// + /// If the deque does not have sufficient capacity to hold enough items, + /// then this reallocates the deque's storage to grow its capacity, using a + /// geometric growth rate. + /// + /// - Parameters: + /// - items: The new elements to insert into the deque. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of the deque. + /// + /// - Complexity: O(`self.count` + `items.count`) when amortized over many + /// similar invocations on the same deque. + @_alwaysEmitIntoClient + @inline(__always) + public mutating func insert< + C: Container & Collection + >( + copying items: borrowing C, at index: Int + ) { + _insertContainer( + at: index, copying: items, newCount: items.count) + } +#endif +} + +#endif diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift new file mode 100644 index 00000000..de4408fb --- /dev/null +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift @@ -0,0 +1,511 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2025 - 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque where Element: ~Copyable { + /// Adds an element to the front of the deque. + /// + /// If the deque does not have sufficient capacity to hold any more elements, + /// then this reallocates the deque's storage to grow its capacity, using a + /// geometric growth rate. + /// + /// - Parameter item: The element to prepend to the deque. + /// + /// - Complexity: O(1) when amortized over many invocations on the same deque. + @_alwaysEmitIntoClient + @_transparent + public mutating func prepend(_ newElement: consuming Element) { + _ensureFreeCapacity(1) + _storage._handle.uncheckedPrepend(newElement) + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque where Element: ~Copyable { + /// Efficiently prepend a given number of items to the front of this deque by + /// populating a series of storage regions through repeated calls of the + /// specified callback function. + /// + /// If the deque doesn't have sufficient capacity to accommodate the specified + /// number of new elements, then this method reallocates the deque's storage + /// to grow it, using a geometric growth rate. + /// + /// var buffer = RigidDeque() + /// buffer.append(999) + /// var i = 0 + /// buffer.prepend(count: 6) { target in + /// while !target.isFull { + /// target.append(i) + /// i += 1 + /// } + /// } + /// // `buffer` now contains [0, 1, 2, 3, 4, 5, 6, 999] + /// + /// The newly prepended items are not guaranteed to form a single contiguous + /// storage region. Therefore, the supplied callback may be invoked multiple + /// times to initialize each successive chunk of storage. However, invocations + /// cease if the callback fails to fully populate its output span or if + /// it throws an error. In such cases, the deque keeps all items that were + /// successfully initialized before the callback terminated the prepend. + /// + /// Note: Partial prepends create a gap in ring buffer storage that needs to + /// be closed by moving newly prepended items to their correct positions given + /// the adjusted count. This adds some overhead compared to adding exactly as + /// many items as promised. + /// + /// var buffer = RigidDeque() + /// buffer.append(999) + /// var i = 0 + /// buffer.prepend(count: 6) { target in + /// while !target.isFull, i <= 3 { + /// target.append(i) + /// i += 1 + /// } + /// } + /// // `buffer` now contains [0, 1, 2, 3, 999] + /// + /// - Parameters: + /// - maximumCount: The maximum number of items to prepend to the deque. + /// - body: A callback that gets called at most twice to directly + /// populate newly reserved storage within the deque. + /// + /// - Complexity: O(`maximumCount`) in addition to the complexity of the callback + /// invocations, when amortized over many similar invocations on the same + /// deque. + @_alwaysEmitIntoClient + public mutating func prepend( + maximumCount: Int, + initializingWith body: (inout OutputSpan) throws(E) -> Void + ) throws(E) -> Void { + guard maximumCount > 0 else { return } + _ensureFreeCapacity(maximumCount) + try _storage._handle.uncheckedPrepend( + addingCount: maximumCount, initializingWith: body) + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque where Element: ~Copyable { + /// Moves the elements of a buffer to the front of this deque, leaving the + /// buffer uninitialized. + /// + /// If the deque doesn't have sufficient capacity to accommodate the new + /// elements, then this method reallocates the deque's storage to grow it, + /// using a geometric growth rate. + /// + /// - Parameters: + /// - items: A fully initialized buffer whose contents to move into + /// the deque. + /// + /// - Complexity: O(`items.count`) when amortized over many similar + /// invocations on the same deque. + @_alwaysEmitIntoClient + @inline(__always) + public mutating func prepend( + moving items: UnsafeMutableBufferPointer + ) { + _ensureFreeCapacity(items.count) + _storage._handle.uncheckedPrepend(moving: items) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Moves the elements of an input span by prepending them to the front of + /// this deque, leaving the span empty. + /// + /// If the deque doesn't have sufficient capacity to accommodate the new + /// elements, then this method reallocates the deque's storage to grow it, + /// using a geometric growth rate. + /// + /// - Parameters: + /// - items: An input span whose contents need to be prepended to this deque. + /// + /// - Complexity: O(`items.count`) when amortized over many similar + /// invocations on the same deque. + @_alwaysEmitIntoClient + public mutating func prepend( + moving items: inout InputSpan + ) { + items.withUnsafeMutableBufferPointer { buffer, count in + let source = buffer._extracting(last: count) + unsafe self.prepend(moving: source) + count = 0 + } + } +#endif + + /// Moves the elements of an output span by prepending them to the front of + /// this deque, leaving the span empty. + /// + /// If the deque doesn't have sufficient capacity to accommodate the new + /// elements, then this method reallocates the deque's storage to grow it, + /// using a geometric growth rate. + /// + /// - Parameters: + /// - items: An output span whose contents need to be prepended to this deque. + /// + /// - Complexity: O(`items.count`) when amortized over many similar + /// invocations on the same deque. + @_alwaysEmitIntoClient + public mutating func prepend( + moving items: inout OutputSpan + ) { + items.withUnsafeMutableBufferPointer { buffer, count in + let source = buffer._extracting(first: count) + unsafe self.prepend(moving: source) + count = 0 + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Prepends at most `maximumCount` items generated by a producer to the front of + /// this deque. If `maximumCount` is nil, this appends every item the producer + /// can generate. + /// + /// If the deque doesn't have sufficient capacity to accommodate the specified + /// number of new elements, then this method reallocates the deque's storage + /// to grow it, using a geometric growth rate. + /// + /// This operation prepends as many items as the producer can generate before + /// either reaching its end (or throwing an error), or filling the specified + /// capacity. This operation only consumes the first `maximumCount` items in the + /// producer; if the producer has more, then they remain available after this + /// method returns. + /// + /// Note: Partial prepends create a gap in ring buffer storage that needs to + /// be closed by moving newly prepended items to their correct positions given + /// the adjusted count. This adds some overhead compared to adding exactly as + /// many items as promised. + /// + /// - Parameters: + /// - maximumCount: The maximum number of items to prepend to the deque, or + /// nil to use all available capacity. + /// - producer: A producer that generates the items to prepend. + /// + /// - Complexity: O(*n*) where *n* is the number of new items, when + /// amortized over many similar invocations on the same deque. + @_alwaysEmitIntoClient + @inline(__always) + public mutating func prepend< + P: Producer & ~Copyable & ~Escapable + >( + maximumCount: Int? = nil, + from producer: inout P + ) throws(P.ProducerError) { + if let maximumCount { + _ensureFreeCapacity(maximumCount) + try _storage._handle.uncheckedPrepend( + addingCount: maximumCount + ) { target throws(P.ProducerError) in + while !target.isFull, try producer.generate(into: &target) { + // Do nothing + } + } + return + } + + while true { + _ensureFreeCapacity(1) + try _storage._handle.uncheckedAppend( + maximumCount: freeCapacity + ) { target throws(P.ProducerError) in + while !target.isFull, try producer.generate(into: &target) { + // Do nothing + } + } + } + } +#endif +} + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque /*where Element: Copyable*/ { + /// Copies the elements of a buffer and prepend them to the front of this + /// rigid deque. + /// + /// If the deque doesn't have sufficient capacity to accommodate the specified + /// number of new elements, then this method reallocates the deque's storage + /// to grow it, using a geometric growth rate. + /// + /// - Parameters: + /// - items: A fully initialized buffer whose contents to copy into + /// the deque. + /// + /// - Complexity: O(`items.count`) when amortized over many similar + /// invocations on the same deque. + @inlinable + @_alwaysEmitIntoClient + public mutating func prepend( + copying items: UnsafeBufferPointer + ) { + _ensureFreeCapacity(items.count) + _storage._handle.uncheckedPrepend(copying: items) + } + + /// Copies the elements of a buffer and prepend them to the front of this + /// deque. + /// + /// If the deque doesn't have sufficient capacity to accommodate the specified + /// number of new elements, then this method reallocates the deque's storage + /// to grow it, using a geometric growth rate. + /// + /// - Parameters: + /// - items: A fully initialized buffer whose contents to copy into + /// the deque. + /// + /// - Complexity: O(`items.count`) when amortized over many similar + /// invocations on the same deque. + @inlinable + @_alwaysEmitIntoClient + public mutating func prepend( + copying items: UnsafeMutableBufferPointer + ) { + unsafe self.prepend(copying: UnsafeBufferPointer(items)) + } + + /// Copy the elements of a span and prepend them to the front of this deque. + /// + /// If the deque does not have sufficient capacity to hold all items in the + /// span, then this triggers a runtime error. + /// + /// - Parameters: + /// - items: A span whose contents to copy into the deque. + /// + /// - Complexity: O(`items.count`) when amortized over many similar + /// invocations on the same deque. + @inlinable + @_alwaysEmitIntoClient + public mutating func prepend(copying items: Span) { + unsafe items.withUnsafeBufferPointer { source in + unsafe self.prepend(copying: source) + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @inlinable + internal mutating func _prepend< + S: BorrowingSequence & ~Copyable & ~Escapable + >(copying items: borrowing S) { + // We don't know the exact count of new elements, so we cannot initialize + // them in place. Append them to the end of the deque first, then rotate + // them to their correct location. + // + // FIXME: If we get a BorrowingSequence.estimatedCount with an exact case, + // then we should use that when possible to copy items to their final + // location in a single pass. + let oldCount = self.count + self._append(copying: items) // Not a typo! + _storage._handle.rotate(toStartAtOffset: oldCount) + } + + @inlinable + internal mutating func _prepend< + S: BorrowingSequence & ~Copyable & ~Escapable + >( + copying items: borrowing S, + exactCount: Int + ) { + var it = items.makeBorrowingIterator() + self.prepend(maximumCount: exactCount) { target in + let span = it.nextSpan(maximumCount: target.freeCapacity) + target._append(copying: span) + } + } + + /// Copies the elements of a borrowing sequence and prepend them to the front + /// of this deque. + /// + /// If the deque does not have sufficient capacity to hold all items in the + /// sequence, then this triggers a runtime error. + /// + /// As borrowing sequences do not necessarily provide an exact count, this + /// operation works by first appending the items, then finalizing the + /// prepend by rotating them in place as a postprocessing step. + /// + /// - Parameters: + /// - items: The new elements to copy into the deque. + /// + /// - Complexity: O(*m*), where *m* is the length of `items`, as amortized + /// over many similar invocations on the same deque. + @_alwaysEmitIntoClient + public mutating func prepend & ~Copyable & ~Escapable>( + copying items: borrowing S + ) { + self._prepend(copying: items) + } + + /// Copies the elements of a container and prepends them to the front + /// of this deque. + /// + /// If the deque does not have sufficient capacity to hold all items in the + /// container, then this triggers a runtime error. + /// + /// - Parameters: + /// - items: The new elements to copy into the deque. + /// + /// - Complexity: O(`items.count`) when amortized over many similar + /// invocations on the same deque. + @_alwaysEmitIntoClient + public mutating func prepend & ~Copyable & ~Escapable>( + copying items: borrowing C + ) { + self._prepend(copying: items, exactCount: items.count) + } +#endif + + /// Prepend the elements of a sequence to the front of this deque by copying + /// them. + /// + /// If the deque does not have sufficient capacity to hold all items in the + /// sequence, then this triggers a runtime error. + /// + /// This example prepends the elements of a `Range` instance + /// to a rigid deque of integers. + /// + /// var numbers = RigidDeque(capacity: 10) + /// numbers.append(copying: [1, 2, 3, 4, 5]) + /// numbers.prepend(copying: 10...15) + /// // `numbers` now contains [10, 11, 12, 13, 14, 15, 1, 2, 3, 4, 5] + /// + /// As borrowing sequences do not necessarily provide an exact count, this + /// operation works by first appending the items, then finalizing the + /// prepend by rotating them in place as a postprocessing step. + /// + /// - Parameter items: The elements to prepend to the deque. + /// + /// - Complexity: O(`items.count`) when amortized over many similar + /// invocations on the same deque. + @inlinable + @_alwaysEmitIntoClient + public mutating func prepend( + copying items: some Sequence + ) { + let done: Void? = items.withContiguousStorageIfAvailable { source in + unsafe self.prepend(copying: source) + return + } + guard done == nil else { return } + let oldCount = self.count + self.append(copying: items) // Not a typo! + _storage._handle.rotate(toStartAtOffset: oldCount) + } + + /// Prepend the elements of a collection to the front of this deque by copying + /// them. + /// + /// If the deque does not have sufficient capacity to hold all items in the + /// sequence, then this triggers a runtime error. + /// + /// This example prepends the elements of a `Range` instance + /// to a rigid deque of integers. + /// + /// var numbers = RigidDeque(capacity: 10) + /// numbers.append(copying: [1, 2, 3, 4, 5]) + /// numbers.prepend(copying: 10...15) + /// // `numbers` now contains [10, 11, 12, 13, 14, 15, 1, 2, 3, 4, 5] + /// + /// - Parameter items: The elements to prepend to the deque. + /// + /// - Complexity: O(`items.count`) when amortized over many similar + /// invocations on the same deque. + @inlinable + @_alwaysEmitIntoClient + public mutating func prepend( + copying items: some Collection + ) { + let done: Void? = items.withContiguousStorageIfAvailable { source in + unsafe self.prepend(copying: source) + return + } + guard done == nil else { return } + let c = items.count + guard c > 0 else { return } + _ensureFreeCapacity(c) + _storage._handle.uncheckedPrepend(copying: items, exactCount: c) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Copies the elements of a borrowing sequence to the end of this deque. + /// + /// If the deque does not have sufficient capacity to hold all items in the + /// sequence, then this triggers a runtime error. + /// + /// - Parameters: + /// - items: The new elements to copy into the deque. + /// + /// - Complexity: O(*m*), where *m* is the length of `items`, as amortized + /// over many similar invocations on the same deque. + @_alwaysEmitIntoClient + public mutating func prepend & Sequence>( + copying items: borrowing S + ) { + self._prepend(copying: items) + } + + /// Copies the elements of a borrowing sequence to the end of this deque. + /// + /// If the deque does not have sufficient capacity to hold all items in the + /// sequence, then this triggers a runtime error. + /// + /// - Parameters: + /// - newElements: The new elements to copy into the deque. + /// + /// - Complexity: O(*m*), where *m* is the length of `items` when amortized + /// over many similar invocations on the same deque. + @_alwaysEmitIntoClient + public mutating func prepend & Collection>( + copying items: borrowing S + ) { + self._prepend(copying: items, exactCount: items.count) + } + + /// Copies the elements of a container to the end of this deque. + /// + /// If the deque does not have sufficient capacity to hold all items in the + /// sequence, then this triggers a runtime error. + /// + /// - Parameters: + /// - items: The new elements to copy into the deque. + /// + /// - Complexity: O(*m*), where *m* is the length of `items` when amortized + /// over many similar invocations on the same deque. + @_alwaysEmitIntoClient + public mutating func prepend & Sequence>( + copying items: borrowing C + ) { + self._prepend(copying: items, exactCount: items.count) + } + + /// Copies the elements of a container to the end of this deque. + /// + /// If the deque does not have sufficient capacity to hold all items in the + /// sequence, then this triggers a runtime error. + /// + /// - Parameters: + /// - items: The new elements to copy into the deque. + /// + /// - Complexity: O(*m*), where *m* is the length of `items` when amortized + /// over many similar invocations on the same deque. + @_alwaysEmitIntoClient + public mutating func prepend & Collection>( + copying items: C + ) { + self._prepend(copying: items, exactCount: items.count) + } +#endif +} +#endif diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Removals.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Removals.swift new file mode 100644 index 00000000..ae7f4a83 --- /dev/null +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Removals.swift @@ -0,0 +1,150 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2025 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque where Element: ~Copyable { + /// Removes and returns the element at the specified position. + /// + /// Existing elements in the deque's storage are moved as needed to close the + /// gap left by the removed item. (The direction of the move depends on the + /// location of the removal, minimizing the cost.) + /// + /// - Parameter i: The position of the element to remove. `index` must be + /// a valid index of the deque that is not equal to the end index. + /// - Returns: The removed element. + /// + /// - Complexity: O(`count`) + @discardableResult + @_alwaysEmitIntoClient + @inline(__always) + public mutating func remove(at index: Int) -> Element { + _storage.remove(at: index) + } + + /// Removes all elements from the deque, preserving its allocated capacity. + /// + /// - Complexity: O(`count`) + @_alwaysEmitIntoClient + @inline(__always) + public mutating func removeAll() { + _storage.removeAll() + } + + /// Removes and returns the first element of the deque. + /// + /// The deque must not be empty. + /// + /// - Returns: The first element of the original deque. + /// + /// - Complexity: O(1) + @discardableResult + @_alwaysEmitIntoClient + @inline(__always) + public mutating func removeFirst() -> Element { + _storage.removeFirst() + } + + /// Removes and returns the last element of the deque. + /// + /// The deque must not be empty. + /// + /// - Returns: The last element of the original deque. + /// + /// - Complexity: O(1) + @discardableResult + @_alwaysEmitIntoClient + @inline(__always) + public mutating func removeLast() -> Element { + _storage.removeLast() + } + + /// Removes and discards the specified number of elements from the start of + /// the deque. + /// + /// Attempting to remove more elements than exist in the deque + /// triggers a runtime error. + /// + /// - Parameter k: The number of elements to remove from the deque. + /// `k` must be greater than or equal to zero and must not exceed + /// the count of the deque. + /// + /// - Complexity: O(`k`) + @_alwaysEmitIntoClient + @inline(__always) + public mutating func removeFirst(_ k: Int) { + _storage.removeFirst(k) + } + + /// Removes and discards the specified number of elements from the end of the + /// deque. + /// + /// Attempting to remove more elements than exist in the deque + /// triggers a runtime error. + /// + /// - Parameter k: The number of elements to remove from the deque. + /// `k` must be greater than or equal to zero and must not exceed + /// the count of the deque. + /// + /// - Complexity: O(`k`) + @_alwaysEmitIntoClient + @inline(__always) + public mutating func removeLast(_ k: Int) { + _storage.removeLast(k) + } + + /// Removes the specified subrange of elements from the deque. + /// + /// - Parameter bounds: The subrange to remove. The bounds of the + /// range must be valid indices of the deque. + /// + /// - Complexity: O(`count`) + @_alwaysEmitIntoClient + @inline(__always) + public mutating func removeSubrange(_ bounds: Range) { + _storage.removeSubrange(bounds) + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque where Element: ~Copyable { + /// Removes and returns the first element of the deque, if there is one. + /// + /// - Returns: The first element of the original deque if it was not empty; + /// otherwise, `nil`. + /// + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @inline(__always) + public mutating func popFirst() -> Element? { + _storage.popFirst() + } + + /// Removes and returns the last element of the deque, if there is one. + /// + /// - Returns: The last element of the original deque if it was not empty; + /// otherwise, `nil`. + /// + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @inline(__always) + public mutating func popLast() -> Element? { + _storage.popLast() + } +} + +#endif diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Replacements.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Replacements.swift new file mode 100644 index 00000000..344c1fab --- /dev/null +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Replacements.swift @@ -0,0 +1,627 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque where Element: ~Copyable { + /// Replaces the specified range of elements by a given count of new items, + /// using a callback to directly initialize deque storage by populating + /// a series of output spans. + /// + /// The number of new elements need not match the number of elements being + /// removed. + /// + /// This method has the same overall effect as calling + /// + /// try deque.consume(subrange, consumingWith: consumer) + /// try deque.insert( + /// addingCount: newItemCount, + /// at: subrange.lowerBound, + /// initializingWith: initializer) + /// + /// Except it performs faster (by a constant factor), by avoiding moving + /// some items in the deque twice. + /// + /// If the deque doesn't have sufficient capacity to accommodate the new + /// elements, then this method reallocates the deque's storage to grow it, + /// using a geometric growth rate. + /// + /// Neither the removed nor the newly inserted items are guaranteed to form a + /// single contiguous storage region. Therefore, the supplied callbacks may be + /// invoked multiple times to consume, then initialize successive chunks of + /// storage. Calls to `consumer` do not get interleaved with calls to + /// `initializer`: no new item is inserted until every replaced item has been + /// fully consumed. + /// + /// The `consumer` callback is not required to fully depopulate its input + /// span. Any items the callback leaves in the span still get removed and + /// discarded from the deque before insertions begin. If there are more + /// spans to consume, the callback will get called again after such a partial + /// consumption. + /// + /// The `initializer` callback is not required to fully populate its + /// output span, and it is allowed to throw an error. In such cases, the + /// replacement operation ends, and the deque keeps all items that were + /// successfully initialized before the callback terminated. + /// + /// Partial insertions create a gap in ring buffer storage that needs to be + /// closed by moving newly inserted items to their correct positions given + /// the adjusted count. This adds some overhead compared to adding exactly as + /// many items as promised. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - newItemCount: the maximum number of items to replace the old subrange. + /// - initializer: A callback that gets called at most twice to directly + /// populate newly reserved storage within the deque. The function + /// is always called with an empty output span. + /// + /// - Complexity: O(`self.count` + `newCount`) + @inlinable + public mutating func replaceSubrange( + _ subrange: Range, + addingCount newItemCount: Int, + initializingWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) -> Void { + _storage._checkValidBounds(subrange) + precondition(newItemCount >= 0, "Cannot add a negative number of items") + _ensureFreeCapacity(newItemCount - subrange.count) + try _storage._handle.uncheckedReplace( + removing: subrange, + addingCount: capacity, + initializingWith: initializer) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Replaces the specified range of elements by a given count of new items, + /// using callbacks to consume old items, and to then insert new ones. + /// + /// The number of new elements need not match the number of elements being + /// removed. + /// + /// This method has the same overall effect as calling + /// + /// try deque.consume(subrange, consumingWith: consumer) + /// try deque.insert( + /// addingCount: newItemCount, + /// at: subrange.lowerBound, + /// initializingWith: initializer) + /// + /// Except it performs faster (by a constant factor), by avoiding moving + /// some items in the deque twice. + /// + /// If the deque doesn't have sufficient capacity to accommodate the new + /// elements, then this method reallocates the deque's storage to grow it, + /// using a geometric growth rate. + /// + /// The removed and newly inserted items are not guaranteed to form a single + /// contiguous storage region. Therefore, the supplied callbacks may be + /// invoked multiple times to consume, then initialize successive chunks of + /// storage. Calls to `consumer` do not get interleaved with calls to + /// `initializer`: no new item is inserted until every replaced item has been + /// consumed. + /// + /// The `initializer` callback is not required to fully populate its + /// output span, and it is allowed to throw an error. In such cases, the + /// deque keeps all items that were successfully initialized before the + /// callback terminated. + /// + /// Partial insertions create a gap in ring buffer storage that needs to be + /// closed by moving newly inserted items to their correct positions given + /// the adjusted count. This adds some overhead compared to adding exactly as + /// many items as promised. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - newItemCount: the maximum number of items to replace the old subrange. + /// - consumer: A callback that gets called at most twice to consume + /// the elements to be removed directly from the deque's storage. The + /// function is always called with a non-empty input span. + /// - initializer: A callback that gets called at most twice to directly + /// populate newly reserved storage within the deque. The function + /// is always called with an empty output span. + /// + /// - Complexity: O(`self.count` + `newItemCount`) in addition to the complexity + /// of the callback invocations. + @inlinable + public mutating func replaceSubrange( + _ subrange: Range, + consumingWith consumer: (inout InputSpan) -> Void, + addingCount newItemCount: Int, + initializingWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) -> Void { + _storage._checkValidBounds(subrange) + precondition(newItemCount >= 0, "Cannot add a negative number of items") + _ensureFreeCapacity(newItemCount - subrange.count) + try _storage._handle.uncheckedReplace( + removing: subrange, + consumingWith: consumer, + addingCount: newItemCount, + initializingWith: initializer) + } +#endif +} + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque where Element: ~Copyable { + /// Replaces the specified range of elements by moving the elements of a + /// fully initialized buffer into their place. On return, the buffer is left + /// in an uninitialized state. + /// + /// This method has the effect of removing the specified range of elements + /// from the deque and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the deque doesn't have sufficient capacity to accommodate the new + /// elements, then this method reallocates the deque's storage to grow it, + /// using a geometric growth rate. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `items` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(moving:at:)`. + /// + /// Likewise, if you pass a zero-length buffer as the `items` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - items: A fully initialized buffer whose contents to move into + /// the deque. + /// + /// - Complexity: O(`self.count` + `items.count`) + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + moving items: UnsafeMutableBufferPointer, + ) { + var remainder = items + replaceSubrange(subrange, addingCount: remainder.count) { target in + target.withUnsafeMutableBufferPointer { buffer, count in + buffer.moveInitializeAll( + fromContentsOf: remainder._trim(first: buffer.count)) + count = buffer.count + } + } + assert(remainder.isEmpty) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Replaces the specified range of elements by moving the contents of an + /// input span into their place. On return, the span is left empty. + /// + /// This method has the effect of removing the specified range of elements + /// from the deque and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the deque doesn't have sufficient capacity to accommodate the new + /// elements, then this method reallocates the deque's storage to grow it, + /// using a geometric growth rate. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `items` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(moving:at:)`. + /// + /// Likewise, if you pass a zero-length buffer as the `items` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - items: An input span whose contents are to be moved into the deque. + /// + /// - Complexity: O(`self.count` + `items.count`) + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + moving items: inout InputSpan + ) { + items.withUnsafeMutableBufferPointer { buffer, count in + let source = buffer._extracting(last: count) + unsafe self.replaceSubrange(subrange, moving: source) + count = 0 + } + } +#endif + + /// Replaces the specified range of elements by moving the contents of an + /// output span into their place. On return, the span is left empty. + /// + /// This method has the effect of removing the specified range of elements + /// from the deque and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the deque doesn't have sufficient capacity to accommodate the new + /// elements, then this method reallocates the deque's storage to grow it, + /// using a geometric growth rate. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `items` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(moving:at:)`. + /// + /// Likewise, if you pass a zero-length buffer as the `items` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the deque. + /// - items: An output span whose contents are to be moved into the deque. + /// + /// - Complexity: O(`self.count` + `items.count`) + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + moving items: inout OutputSpan + ) { + items.withUnsafeMutableBufferPointer { buffer, count in + let source = buffer._extracting(first: count) + unsafe self.replaceSubrange(subrange, moving: source) + count = 0 + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Replaces the specified range of elements by at most `maximumCount` items + /// generated by a producer. + /// + /// This method has the effect of removing the specified range of elements + /// from the deque and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the deque doesn't have sufficient capacity to accommodate the new + /// elements, then this method reallocates the deque's storage to grow it, + /// using a geometric growth rate. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the items generated by `producer` at `subrange.lowerBound`. This + /// case is more directly expressed by calling `insert(moving:at:)`. + /// + /// Likewise, if the given producer is empty, then this method removes the + /// elements in the given subrange without replacement. This case is more + /// directly expressed by calling `removeSubrange`. + /// + /// This operation inserts as many items as the producer can generate before + /// either reaching `maximumCount`, or the producer hitting its end, or + /// throwing an error. If the producer has more than `maximumCount` items left in + /// its underlying sequence, then extra items remain available after this + /// method returns. + /// + /// If the operation inserts fewer than `maximumCount` items, then it results in + /// a gap in ring buffer storage that needs to be closed by moving some + /// items to their correct positions given the adjusted count. This adds some + /// overhead compared to adding exactly as many items as promised. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - maximumCount: The maximum number of items to insert into the deque. + /// - producer: A producer that generates the items to append. + /// + /// - Complexity: O(`self.count` + `maximumCount`) + @_alwaysEmitIntoClient + public mutating func replaceSubrange< + P: Producer & ~Copyable & ~Escapable + >( + _ subrange: Range, + addingCount newItemCount: Int, + from producer: inout P + ) throws(P.ProducerError) { + try replaceSubrange(subrange, addingCount: newItemCount) { target throws(P.ProducerError) in + while !target.isFull, try producer.generate(into: &target) { + // Do nothing + } + } + } +#endif +} + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque /* where Element: Copyable */ { + /// Replaces the specified subrange of elements by copying the elements of + /// the given buffer pointer, which must be fully initialized. + /// + /// This method has the effect of removing the specified range of elements + /// from the deque and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the deque doesn't have sufficient capacity to accommodate the new + /// elements, then this method reallocates the deque's storage to grow it, + /// using a geometric growth rate. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `items` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(copying:at:)`. + /// + /// Likewise, if you pass a zero-length buffer as the `items` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - items: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `items.count`) + @inlinable + public mutating func replaceSubrange( + _ subrange: Range, + copying items: UnsafeBufferPointer + ) { + var remainder = items + replaceSubrange(subrange, addingCount: remainder.count) { target in + target.withUnsafeMutableBufferPointer { dst, dstCount in + dst.initializeAll(fromContentsOf: remainder._trim(first: dst.count)) + dstCount += dst.count + } + } + assert(remainder.isEmpty) + } + + /// Replaces the specified subrange of elements by copying the elements of + /// the given buffer pointer, which must be fully initialized. + /// + /// This method has the effect of removing the specified range of elements + /// from the deque and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the deque doesn't have sufficient capacity to accommodate the new + /// elements, then this method reallocates the deque's storage to grow it, + /// using a geometric growth rate. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `items` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(copying:at:)`. + /// + /// Likewise, if you pass a zero-length buffer as the `items` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - items: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `items.count`) + @inlinable + public mutating func replaceSubrange( + _ subrange: Range, + copying items: UnsafeMutableBufferPointer + ) { + unsafe self.replaceSubrange( + subrange, + copying: UnsafeBufferPointer(items)) + } + + /// Replaces the specified subrange of elements by copying the elements of + /// the given span. + /// + /// This method has the effect of removing the specified range of elements + /// from the deque and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the deque doesn't have sufficient capacity to accommodate the new + /// elements, then this method reallocates the deque's storage to grow it, + /// using a geometric growth rate. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `items` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(copying:at:)`. + /// + /// Likewise, if you pass a zero-length span as the `items` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - items: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `items.count`) + @inlinable + public mutating func replaceSubrange( + _ subrange: Range, + copying items: Span + ) { + unsafe items.withUnsafeBufferPointer { buffer in + unsafe self.replaceSubrange(subrange, copying: buffer) + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @inlinable + internal mutating func _replaceSubrange< + C: Container & ~Copyable & ~Escapable + >( + _ subrange: Range, + copyingContainer items: borrowing C, + newCount: Int + ) { + + let expectedCount = self.count - subrange.count + newCount + var it = items.makeBorrowingIterator() + self.replaceSubrange(subrange, addingCount: newCount) { target in + it.copyContents(into: &target) + } + precondition( + it.nextSpan().isEmpty && count == expectedCount, + "Broken Container: count doesn't match contents") + } +#endif + + @inlinable + internal mutating func _replaceSubrange( + _ subrange: Range, + copyingCollection items: __owned some Collection, + newCount: Int + ) { + let done: Void? = items.withContiguousStorageIfAvailable { src in + precondition( + src.count == newCount, + "Broken Collection: count doesn't match contents") + self.replaceSubrange(subrange, copying: src) + } + if done != nil { return } + + var i = items.startIndex + self.replaceSubrange(subrange, addingCount: newCount) { target in + while !target.isFull { + target.append(items[i]) + items.formIndex(after: &i) + } + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Replaces the specified subrange of elements by copying the elements of + /// the given container. + /// + /// This method has the effect of removing the specified range of elements + /// from the deque and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the deque doesn't have sufficient capacity to accommodate the new + /// elements, then this method reallocates the deque's storage to grow it, + /// using a geometric growth rate. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `items` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(copying:at:)`. + /// + /// Likewise, if you pass a zero-length container as the `items` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the array. + /// - items: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `items.count`) + @inlinable + @inline(__always) + public mutating func replaceSubrange< + C: Container & ~Copyable & ~Escapable + >( + _ subrange: Range, + copying items: borrowing C + ) { + _replaceSubrange( + subrange, copyingContainer: items, newCount: items.count) + } +#endif + + /// Replaces the specified subrange of elements by copying the elements of + /// the given collection. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the deque doesn't have sufficient capacity to accommodate the new + /// elements, then this method reallocates the deque's storage to grow it, + /// using a geometric growth rate. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `items` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(copying:at:)`. + /// + /// Likewise, if you pass a zero-length collection as the `items` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - items: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `items.count`) + @inlinable + @inline(__always) + public mutating func replaceSubrange( + _ subrange: Range, + copying items: __owned some Collection + ) { + _replaceSubrange( + subrange, copyingCollection: items, newCount: items.count) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Replaces the specified subrange of elements by copying the elements of + /// the given container. + /// + /// This method has the effect of removing the specified range of elements + /// from the deque and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the deque doesn't have sufficient capacity to accommodate the new + /// elements, then this method reallocates the deque's storage to grow it, + /// using a geometric growth rate. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `items` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(copying:at:)`. + /// + /// Likewise, if you pass a zero-length container as the `items` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the array. + /// - items: The new elements to copy into the collection. + /// + /// - Complexity: O(*n* + *m*), where *n* is count of this deque and + /// *m* is the count of `items`. + @inlinable + @inline(__always) + public mutating func replaceSubrange< + C: Container & Collection + >( + _ subrange: Range, + copying items: C + ) { + _replaceSubrange( + subrange, copyingContainer: items, newCount: items.count) + } +#endif +} + +#endif diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque.swift new file mode 100644 index 00000000..ab52644c --- /dev/null +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque.swift @@ -0,0 +1,323 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2025 - 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(<6.2) + +/// A dynamically self-resizing, heap allocated, noncopyable double-ended +/// queue of potentially noncopyable elements. A deque (pronounced "deck") +/// is an ordered random-access container that supports efficient +/// insertions and removals from both ends. +@frozen +@available(*, unavailable, message: "UniqueDeque requires a Swift 6.2 toolchain") +public struct UniqueDeque: ~Copyable { + public init() { + fatalError() + } +} + +#else + +/// A dynamically self-resizing, heap allocated, noncopyable double-ended +/// queue of potentially noncopyable elements. A deque (pronounced "deck") +/// is an ordered random-access container that supports efficient +/// insertions and removals from both ends. +/// +/// Deques implement the same indexing semantics as arrays: they use integer +/// indices, and the first element of a nonempty deque is always at logical +/// index zero. +/// +/// var colors = UniqueDeque() +/// colors.append("red") +/// colors.prepend("yellow") +/// colors.append("blue") +/// // `colors` now contains "yellow", "red", "blue" +/// +/// print(colors[0]) // prints "yellow" +/// print(colors[1]) // prints "red" +/// +/// print(colors.removeFirst()) // prints "yellow" +/// print(colors.removeLast()) // prints "blue" +/// // `colors` now contains "red" +/// +/// This double-ended nature makes deques particularly well-suited for +/// representing first-in-first-out (FIFO) buffers, where new items are +/// inserted at one end, and old items are retrieved from the other. +/// For example, they are ideal for modeling buffered data streams, such as +/// networking channels, or other producer/consumer scenarios. +/// +/// ### Implementation Notes +/// +/// `UniqueDeque` implements a ring buffer. It stores its elements in a +/// single heap-allocated buffer, and to allow fast insertions and removals +/// from both ends, the buffer behaves as if its ends were glued together into +/// a ring shape. This comes at the cost of potentially discontiguous storage, as +/// the contents of the ring buffer sometimes wrap around the edges. +/// +/// While the first item in the deque is always addressed by the logical index +/// zero, its physical location can be anywhere in the underlying ring buffer. +/// Compare this with `UniqueArray`'s contiguous storage, where the first item +/// is always stored at the start of the buffer, so new data can always be +/// efficiently appended to the end, but inserting at the front is relatively +/// slow, as existing elements need to be shifted to make room. +/// +/// ### Dynamic Storage Sizing +/// +/// `UniqueDeque` instances automatically resize their underlying storage as +/// needed to accommodate newly inserted items, using a geometric growth curve. +/// This lets code using `UniqueDeque` avoid having to carefully allocate enough +/// capacity in advance; on the other hand, it makes it difficult to tell +/// when and where such reallocations may happen. +/// +/// For example, appending an element to a `UniqueDeque` has highly variable +/// complexity; often, it runs at a constant cost, but if the operation has to +/// resize storage, then the cost of an individual append suddenly becomes +/// proportional to the size of the whole container. +/// +/// The geometric growth curve allows the cost of such latency spikes to +/// get amortized across repeated invocations, bringing the average cost back +/// to O(1); but the spikes make this construct less suitable for use cases that +/// expect predictable, consistent performance on every operation. +/// +/// Implicit growth also makes it more difficult to predict/analyze the amount +/// of memory an algorithm would need. Developers targeting environments with +/// stringent limits on heap allocations may prefer to avoid using dynamically +/// resizing container types as a matter of policy. The type `RigidDeque` +/// provides a fixed-capacity deque variant that caters specifically for these +/// use cases, trading ease-of-use for more consistent/predictable execution. +@available(SwiftStdlib 5.0, *) +@frozen +@safe +public struct UniqueDeque: ~Copyable { + @usableFromInline + package var _storage: RigidDeque + + @_alwaysEmitIntoClient + @inline(__always) + package init(_storage: consuming RigidDeque) { + self._storage = _storage + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque: @unchecked Sendable where Element: Sendable & ~Copyable {} + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque where Element: ~Copyable { +#if COLLECTIONS_INTERNAL_CHECKS + @usableFromInline @inline(never) @_effects(releasenone) + package func _checkInvariants() { + _storage._handle._checkInvariants() + } +#else + @_transparent + package func _checkInvariants() {} +#endif // COLLECTIONS_INTERNAL_CHECKS +} + +//MARK: - Basics + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque where Element: ~Copyable { + /// The maximum number of elements this array can hold without reallocating + /// its storage. + /// + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @_transparent + public var capacity: Int { _assumeNonNegative(_storage.capacity) } + + /// The number of additional elements that can be added to this array without + /// reallocating its storage. + /// + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @_transparent + public var freeCapacity: Int { _assumeNonNegative(_storage.freeCapacity) } + + @_alwaysEmitIntoClient + @_transparent + public var _isFull: Bool { _storage.isFull } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque where Element: ~Copyable { + public typealias Index = Int + + /// A Boolean value indicating whether this deque contains no elements. + /// + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @_transparent + public var isEmpty: Bool { _storage.isEmpty } + + /// The number of elements in this deque. + /// + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @_transparent + public var count: Int { _storage.count } + + /// The position of the first element in a nonempty deque. This is always zero. + /// + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @_transparent + public var startIndex: Int { _storage.startIndex } + + /// The deque’s "past the end” position—that is, the position one greater than + /// the last valid subscript argument. This is always equal to deque's count. + /// + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @_transparent + public var endIndex: Int { _storage.endIndex } + + /// The range of indices that are valid for subscripting the deque. + /// + /// - Complexity: O(1) + @inlinable + @inline(__always) + public var indices: Range { unsafe Range(uncheckedBounds: (0, count)) } + + @_alwaysEmitIntoClient + public subscript(position: Int) -> Element { + @inline(__always) + @_transparent + unsafeAddress { + precondition(position >= 0 && position < count, "Index out of bounds") + let slot = _storage._handle.slot(forOffset: position) + return _storage._handle.ptr(at: slot) + } + @inline(__always) + @_transparent + unsafeMutableAddress { + precondition(position >= 0 && position < count, "Index out of bounds") + let slot = _storage._handle.slot(forOffset: position) + return _storage._handle.mutablePtr(at: slot) + } + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque where Element: ~Copyable { + /// Exchanges the values at the specified indices of the deque. + /// + /// Both parameters must be valid indices of the deque and not equal to + /// `endIndex`. Passing the same index as both `i` and `j` has no effect. + /// + /// - Parameter i: The index of the first value to swap. + /// - Parameter j: The index of the second valud to swap. + /// + /// - Complexity: O(1) + @_transparent + public mutating func swapAt(_ i: Int, _ j: Int) { + _storage.swapAt(i, j) + } +} + +//MARK: - Resizing + +@_alwaysEmitIntoClient +@_transparent +internal func _growUniqueDequeCapacity(_ capacity: Int) -> Int { + // A growth factor of 1.5 seems like a reasonable compromise between + // over-allocating memory and wasting cycles on repeatedly resizing storage. + let c = (3 &* UInt(bitPattern: capacity) &+ 1) / 2 + return Int(bitPattern: c) +} + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque where Element: ~Copyable { + /// Grow or shrink the capacity of this deque instance without discarding + /// its contents. + /// + /// This operation replaces the deque's storage buffer with a newly allocated + /// buffer of the specified capacity, moving all existing elements + /// to its new storage. The old storage is then deallocated. + /// + /// - Parameter newCapacity: The desired new capacity. `newCapacity` must be + /// greater than or equal to the current count. + /// + /// - Complexity: O(`count`) + @inlinable + public mutating func reallocate(capacity: Int) { + _storage.reallocate(capacity: capacity) + } + + /// Ensure that the array has capacity to store the specified number of + /// elements, by growing its storage buffer if necessary. + /// + /// If `capacity < n`, then this operation reallocates the unique array's + /// storage to grow it; on return, the array's capacity becomes `n`. + /// Otherwise the array is left as is. + /// + /// - Complexity: O(`count`) + @inlinable + public mutating func reserveCapacity(_ n: Int) { + _storage.reserveCapacity(n) + } + + + @_alwaysEmitIntoClient + @_transparent + internal mutating func _ensureFreeCapacity(_ freeCapacity: Int) { + guard _storage.freeCapacity < freeCapacity else { return } + _ensureFreeCapacitySlow(freeCapacity) + } + + @_alwaysEmitIntoClient + @_transparent + internal func _grow(freeCapacity: Int) -> Int { + Swift.max( + count + freeCapacity, + _growUniqueDequeCapacity(capacity)) + } + + @inlinable + internal mutating func _ensureFreeCapacitySlow(_ freeCapacity: Int) { + let newCapacity = _grow(freeCapacity: freeCapacity) + reallocate(capacity: newCapacity) + } +} + +//MARK: - Copying helpers + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque { + /// Copy the contents of this deque into a newly allocated deque + /// instance with just enough capacity to hold all its elements. + /// + /// - Complexity: O(`count`) + @_alwaysEmitIntoClient + public func clone() -> Self { + UniqueDeque(_storage: _storage.clone()) + } + + /// Copy the contents of this deque into a newly allocated rigid deque + /// instance with the specified capacity. + /// + /// - Parameter capacity: The desired capacity of the resulting rigid deque. + /// `capacity` must be greater than or equal to `count`. + /// + /// - Complexity: O(`count`) + @_alwaysEmitIntoClient + public func clone(capacity: Int) -> Self { + UniqueDeque(_storage: _storage.clone(capacity: capacity)) + } +} + + +#endif // compiler(<6.2) diff --git a/Sources/DequeModule/_DequeSlot.swift b/Sources/DequeModule/_DequeSlot.swift index 2d281cb9..0a584477 100644 --- a/Sources/DequeModule/_DequeSlot.swift +++ b/Sources/DequeModule/_DequeSlot.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors +// Copyright (c) 2021 - 2026 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information @@ -11,12 +11,12 @@ @usableFromInline @frozen -internal struct _DequeSlot { +package struct _DequeSlot { @usableFromInline internal var position: Int - @inlinable - @inline(__always) + @_alwaysEmitIntoClient + @_transparent init(at position: Int) { assert(position >= 0) self.position = position @@ -24,18 +24,18 @@ internal struct _DequeSlot { } extension _DequeSlot { - @inlinable - @inline(__always) + @_alwaysEmitIntoClient + @_transparent internal static var zero: Self { Self(at: 0) } - @inlinable - @inline(__always) + @_alwaysEmitIntoClient + @_transparent internal func advanced(by delta: Int) -> Self { Self(at: position &+ delta) } - @inlinable - @inline(__always) + @_alwaysEmitIntoClient + @_transparent internal func orIfZero(_ value: Int) -> Self { guard position > 0 else { return Self(at: value) } return self @@ -44,29 +44,35 @@ extension _DequeSlot { extension _DequeSlot: CustomStringConvertible { @usableFromInline - internal var description: String { + package var description: String { "@\(position)" } } extension _DequeSlot: Equatable { - @inlinable - @inline(__always) - static func ==(left: Self, right: Self) -> Bool { + @_alwaysEmitIntoClient + @_transparent + package static func ==(left: Self, right: Self) -> Bool { left.position == right.position } } extension _DequeSlot: Comparable { - @inlinable - @inline(__always) - static func <(left: Self, right: Self) -> Bool { + @_alwaysEmitIntoClient + @_transparent + package static func <(left: Self, right: Self) -> Bool { left.position < right.position } } extension Range where Bound == _DequeSlot { - @inlinable - @inline(__always) + @_alwaysEmitIntoClient + @_transparent internal var _count: Int { upperBound.position - lowerBound.position } + + @_alwaysEmitIntoClient + @_transparent + internal var _offsets: Range { + Range(uncheckedBounds: (lowerBound.position, upperBound.position)) + } } diff --git a/Sources/DequeModule/_UnsafeDequeHandle.swift b/Sources/DequeModule/_UnsafeDequeHandle.swift new file mode 100644 index 00000000..b9546237 --- /dev/null +++ b/Sources/DequeModule/_UnsafeDequeHandle.swift @@ -0,0 +1,1441 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021 - 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +@frozen +@usableFromInline +package struct _UnsafeDequeHandle: ~Copyable { + @usableFromInline + package typealias Slot = _DequeSlot + + @usableFromInline + package var _buffer: UnsafeMutableBufferPointer + + @usableFromInline + package var count: Int + + @usableFromInline + package var startSlot: Slot + + @_alwaysEmitIntoClient + @_transparent + internal init( + buffer: UnsafeMutableBufferPointer, + count: Int, + startSlot: _DequeSlot + ) { + self._buffer = buffer + self.count = count + self.startSlot = startSlot + } + + @inlinable + internal consuming func dispose() { + _checkInvariants() + self.mutableSegments().deinitialize() + _buffer.deallocate() + } +} + +extension _UnsafeDequeHandle where Element: ~Copyable { + @_alwaysEmitIntoClient + @_transparent + internal static var empty: Self { + Self(buffer: ._empty, count: 0, startSlot: .zero) + } + + @_alwaysEmitIntoClient + @_transparent + internal static func allocate( + capacity: Int + ) -> Self { + Self( + buffer: capacity > 0 ? .allocate(capacity: capacity) : ._empty, + count: 0, + startSlot: .zero) + } +} + +extension _UnsafeDequeHandle where Element: ~Copyable { +#if COLLECTIONS_INTERNAL_CHECKS + @usableFromInline @inline(never) @_effects(releasenone) + internal func _checkInvariants() { + precondition(capacity >= 0) + precondition(count >= 0 && count <= capacity) + precondition(startSlot.position >= 0 && startSlot.position <= capacity) + } +#else + @inlinable @inline(__always) + internal func _checkInvariants() {} +#endif // COLLECTIONS_INTERNAL_CHECKS +} + +extension _UnsafeDequeHandle where Element: ~Copyable { + @usableFromInline + internal var description: String { + "(capacity: \(capacity), count: \(count), start: \(startSlot))" + } +} + +extension _UnsafeDequeHandle where Element: ~Copyable { + @_alwaysEmitIntoClient + @_transparent + internal var _baseAddress: UnsafeMutablePointer { + _buffer.baseAddress.unsafelyUnwrapped + } + + @_alwaysEmitIntoClient + @_transparent + internal var capacity: Int { + _buffer.count + } +} + +extension _UnsafeDequeHandle where Element: ~Copyable { + @_alwaysEmitIntoClient + @_transparent + internal func isIdentical(to other: borrowing Self) -> Bool { + self._buffer._isIdentical(to: other._buffer) + && self.count == other.count + && self.startSlot == other.startSlot + } +} + +// MARK: Test initializer + +extension _UnsafeDequeHandle where Element: ~Copyable { + internal static func allocate( + capacity: Int, + startSlot: Slot, + count: Int, + generator: (Int) -> Element + ) -> Self { + precondition(capacity >= 0) + precondition( + startSlot.position >= 0 && + (startSlot.position < capacity || (capacity == 0 && startSlot.position == 0))) + precondition(count <= capacity) + + var h = Self.allocate(capacity: capacity) + h.count = count + h.startSlot = startSlot + if h.count > 0 { + let segments = h.mutableSegments() + let c = segments.first.count + for i in 0 ..< c { + segments.first.initializeElement(at: i, to: generator(i)) + } + if let second = segments.second { + for i in c ..< h.count { + second.initializeElement(at: i - c, to: generator(i)) + } + } + } + return h + } +} + +// MARK: Slots + +extension _UnsafeDequeHandle where Element: ~Copyable { + /// The slot immediately following the last valid one. (`endSlot` refers to + /// the valid slot corresponding to `endIndex`, which is a different thing + /// entirely.) + @_alwaysEmitIntoClient + @_transparent + internal var limSlot: Slot { + Slot(at: capacity) + } + + @_alwaysEmitIntoClient + @_transparent + internal func slot(after slot: Slot) -> Slot { + assert(slot.position < capacity) + let position = slot.position + 1 + if position >= capacity { + return Slot(at: 0) + } + return Slot(at: position) + } + + @_alwaysEmitIntoClient + @_transparent + internal func slot(before slot: Slot) -> Slot { + assert(slot.position < capacity) + if slot.position == 0 { return Slot(at: capacity - 1) } + return Slot(at: slot.position - 1) + } + + @_alwaysEmitIntoClient + @_transparent + internal func slot(_ slot: Slot, offsetBy delta: Int) -> Slot { + assert(slot.position <= capacity) + let position = slot.position + delta + if delta >= 0 { + if position >= capacity { return Slot(at: position - capacity) } + } else { + if position < 0 { return Slot(at: position + capacity) } + } + return Slot(at: position) + } + + @_alwaysEmitIntoClient + @_transparent + internal var endSlot: Slot { + slot(startSlot, offsetBy: count) + } + + /// Return the storage slot corresponding to the specified offset, which may + /// or may not address an existing element. + @_alwaysEmitIntoClient + @_transparent + internal func slot(forOffset offset: Int) -> Slot { + assert(offset >= 0) + assert(offset <= capacity) // Not `count`! + + // Note: The use of wrapping addition/subscription is justified here by the + // fact that `offset` is guaranteed to fall in the range `0 ..< capacity`. + // Eliminating the overflow checks leads to a measurable speedup for + // random-access subscript operations. (Up to 2x on some microbenchmarks.) + let position = startSlot.position &+ offset + guard position < capacity else { return Slot(at: position &- capacity) } + return Slot(at: position) + } + + @_alwaysEmitIntoClient + @_transparent + internal func distance(from start: Slot, to end: Slot) -> Int { + assert(start.position >= 0 && start.position <= capacity) + assert(end.position >= 0 && end.position <= capacity) + + if end.position >= start.position { + return end.position - start.position + } else { + // Handle wrap-around case + return capacity - start.position + end.position + } + } +} + +// MARK: Element Access + +extension _UnsafeDequeHandle where Element: ~Copyable { + @_alwaysEmitIntoClient + @_transparent + internal func ptr(at slot: Slot) -> UnsafePointer { + assert(slot.position >= 0 && slot.position <= capacity) + return UnsafePointer(_baseAddress + slot.position) + } + + @_alwaysEmitIntoClient + @_transparent + internal mutating func mutablePtr( + at slot: Slot + ) -> UnsafeMutablePointer { + assert(slot.position >= 0 && slot.position <= capacity) + return _baseAddress + slot.position + } +} + +extension _UnsafeDequeHandle where Element: ~Copyable { + @inlinable + internal subscript(offset offset: Int) -> Element { + @inline(__always) + _read { + precondition(offset >= 0 && offset < count, "Index out of bounds") + let slot = slot(forOffset: offset) + yield ptr(at: slot).pointee + } + @inline(__always) + _modify { + precondition(offset >= 0 && offset < count, "Index out of bounds") + let slot = slot(forOffset: offset) + yield &mutablePtr(at: slot).pointee + } + } +} + +// MARK: Access to contiguous regions + +extension _UnsafeDequeHandle where Element: ~Copyable { + @_alwaysEmitIntoClient + @_transparent + internal var mutableBuffer: UnsafeMutableBufferPointer { + mutating get { + _buffer + } + } + + @_alwaysEmitIntoClient + @_transparent + internal func buffer(for range: Range) -> UnsafeBufferPointer { + assert(range.upperBound.position <= capacity) + return .init(_buffer._extracting(unchecked: range._offsets)) + } + + @_alwaysEmitIntoClient + @_transparent + internal mutating func mutableBuffer( + for range: Range + ) -> UnsafeMutableBufferPointer { + assert(range.upperBound.position <= capacity) + return _buffer._extracting(unchecked: range._offsets) + } +} + +extension _UnsafeDequeHandle { + @discardableResult + @_alwaysEmitIntoClient + internal mutating func initialize( + at start: Slot, + from source: UnsafeBufferPointer + ) -> Slot { + assert(start.position + source.count <= capacity) + guard source.count > 0 else { return start } + mutablePtr(at: start).initialize(from: source.baseAddress!, count: source.count) + return Slot(at: start.position + source.count) + } +} + +extension _UnsafeDequeHandle where Element: ~Copyable { + @discardableResult + @_alwaysEmitIntoClient + internal mutating func moveInitialize( + at start: Slot, + from source: UnsafeMutableBufferPointer + ) -> Slot { + assert(start.position + source.count <= capacity) + guard source.count > 0 else { return start } + mutablePtr(at: start) + .moveInitialize(from: source.baseAddress!, count: source.count) + return Slot(at: start.position + source.count) + } +} + +// MARK: Access to Segments + +extension _UnsafeDequeHandle where Element: ~Copyable { + @_alwaysEmitIntoClient + internal func nextSegment( + from startOffset: Int + ) -> UnsafeBufferPointer { + assert(startOffset >= 0 && startOffset <= count) + guard _buffer.baseAddress != nil else { + return .init(._empty) + } + let position = startSlot.position &+ startOffset + if position < capacity { + return UnsafeBufferPointer( + start: ptr(at: Slot(at: position)), + count: Swift.min(count &- startOffset, capacity &- position)) + } + // We're after the wrap + return UnsafeBufferPointer( + start: ptr(at: Slot(at: position &- capacity)), + count: startSlot.position &+ count &- position) + } + + @_alwaysEmitIntoClient + internal func segments() -> _UnsafeDequeSegments { + guard _buffer.baseAddress != nil else { + return .init(._empty) + } + let wrap = capacity &- startSlot.position + if count <= wrap { + return .init(start: ptr(at: startSlot), count: count) + } + return .init(first: ptr(at: startSlot), count: wrap, + second: ptr(at: .zero), count: count &- wrap) + } + + @_alwaysEmitIntoClient + internal func segments( + forOffsets offsets: Range + ) -> _UnsafeDequeSegments { + // Note: no asserts for bounds checks, as this is used to implement + // appends/prepends + assert(offsets.count <= capacity) + guard _buffer.baseAddress != nil else { + return .init(._empty) + } + let start = slot(forOffset: offsets.lowerBound) + let wrap = capacity &- start.position + if offsets.count <= wrap { + return .init(start: ptr(at: start), count: offsets.count) + } + return .init( + first: ptr(at: start), count: capacity &- start.position, + second: ptr(at: .zero), count: offsets.count &- wrap) + } + + @_alwaysEmitIntoClient + @_transparent + internal mutating func mutableSegments() -> _UnsafeMutableDequeSegments { + .init(mutating: segments()) + } + + @_alwaysEmitIntoClient + @_transparent + internal mutating func mutableSegments( + forOffsets range: Range + ) -> _UnsafeMutableDequeSegments { + .init(mutating: segments(forOffsets: range)) + } + + @_alwaysEmitIntoClient + internal mutating func mutableSegments( + between start: Slot, + and end: Slot + ) -> _UnsafeMutableDequeSegments { + assert(start.position <= capacity) + assert(end.position <= capacity) + if start < end { + return .init( + start: mutablePtr(at: start), + count: end.position - start.position) + } + return .init( + first: mutablePtr(at: start), count: capacity - start.position, + second: mutablePtr(at: .zero), count: end.position) + } +} + +extension _UnsafeDequeHandle where Element: ~Copyable { + @_alwaysEmitIntoClient + internal mutating func availableSegments() -> _UnsafeMutableDequeSegments { + guard _buffer.baseAddress != nil else { + return .init(._empty) + } + let endSlot = self.endSlot + guard count < capacity else { return .init(start: mutablePtr(at: endSlot), count: 0) } + if endSlot < startSlot { return .init(mutableBuffer(for: endSlot ..< startSlot)) } + return .init(mutableBuffer(for: endSlot ..< limSlot), + mutableBuffer(for: .zero ..< startSlot)) + } +} + +// MARK: Wholesale Copying and Reallocation + +extension _UnsafeDequeHandle { + /// Copy elements in `handle` into a newly allocated handle without changing its + /// capacity or layout. + @_alwaysEmitIntoClient + internal borrowing func allocateCopy() -> Self { + var result: _UnsafeDequeHandle = .allocate(capacity: self.capacity) + result.count = self.count + result.startSlot = self.startSlot + let src = self.segments() + result.initialize(at: self.startSlot, from: src.first) + if let second = src.second { + result.initialize(at: .zero, from: second) + } + return result + } + + /// Copy elements in `handle` into a newly allocated handle with the specified + /// minimum capacity. This operation does not preserve layout. + @_alwaysEmitIntoClient + internal func allocateCopy(capacity: Int) -> Self { + precondition(capacity >= self.count) + var result: _UnsafeDequeHandle = .allocate(capacity: capacity) + result.count = self.count + let src = self.segments() + let next = result.initialize(at: .zero, from: src.first) + if let second = src.second { + result.initialize(at: next, from: second) + } + return result + } +} + +extension _UnsafeDequeHandle where Element: ~Copyable { + @_alwaysEmitIntoClient + internal mutating func reallocate(capacity newCapacity: Int) { + precondition(newCapacity >= count, "Capacity overflow") + guard newCapacity != capacity else { return } + + var new = _UnsafeDequeHandle.allocate(capacity: newCapacity) + let source = self.mutableSegments() + let next = new.moveInitialize(at: .zero, from: source.first) + if let second = source.second { + new.moveInitialize(at: next, from: second) + } + _buffer.deallocate() + _buffer = new._buffer + startSlot = .zero + } +} + +// MARK: Iteration + +extension _UnsafeDequeHandle where Element: ~Copyable { + @_alwaysEmitIntoClient + internal func slotRange(following offset: inout Int) -> Range { + precondition(offset >= 0 && offset <= count, "Index out of bounds") + guard _buffer.baseAddress != nil else { + return Range(uncheckedBounds: (Slot.zero, Slot.zero)) + } + let wrapOffset = Swift.min(capacity - startSlot.position, count) + + if offset < wrapOffset { + defer { offset += wrapOffset - offset } + return Range( + uncheckedBounds: (startSlot.advanced(by: offset), startSlot.advanced(by: wrapOffset))) + } + let lowerSlot = Slot.zero.advanced(by: offset - wrapOffset) + let upperSlot = lowerSlot.advanced(by: count - wrapOffset) + defer { offset += count - offset } + return Range(uncheckedBounds: (lower: lowerSlot, upper: upperSlot)) + } + + @_alwaysEmitIntoClient + internal func slotRange(preceding offset: inout Int) -> Range { + precondition(offset >= 0 && offset <= count, "Index out of bounds") + guard _buffer.baseAddress != nil else { + return Range(uncheckedBounds: (Slot.zero, Slot.zero)) + } + let wrapOffset = Swift.min(capacity - startSlot.position, count) + + if offset <= wrapOffset { + defer { offset = 0 } + return Range( + uncheckedBounds: (startSlot, startSlot.advanced(by: offset))) + } + let lowerSlot = Slot.zero + let upperSlot = lowerSlot.advanced(by: offset - wrapOffset) + defer { offset = wrapOffset } + return Range(uncheckedBounds: (lower: lowerSlot, upper: upperSlot)) + } +} + +// MARK: Swap + +extension _UnsafeDequeHandle where Element: ~Copyable { + @_alwaysEmitIntoClient + @_transparent + internal mutating func uncheckedSwapAt(_ i: Int, _ j: Int) { + let slot1 = self.slot(forOffset: i) + let slot2 = self.slot(forOffset: j) + self.mutableBuffer.swapAt(slot1.position, slot2.position) + } +} + +// MARK: Replacement + +extension _UnsafeDequeHandle { + /// Replace the elements in `range` with `newElements`. The deque's count must + /// not change as a result of calling this function. + /// + /// This function does not validate its input arguments in release builds. Nor + /// does it ensure that the storage buffer is uniquely referenced. + @_alwaysEmitIntoClient + internal mutating func uncheckedReplaceInPlace( + inOffsets range: Range, + with newElements: C + ) where C.Element == Element { + assert(range.upperBound <= count) + assert(newElements.count == range.count) + guard !range.isEmpty else { return } + let target = mutableSegments(forOffsets: range) + target.reassign(copying: newElements) + } +} + +// MARK: Consumption + +extension _UnsafeDequeHandle where Element: ~Copyable { + @_alwaysEmitIntoClient + @_transparent + internal mutating func unsafeConsumeAll( + with body: (UnsafeMutableBufferPointer) -> Void + ) { + let segments = mutableSegments() + body(segments.first) + if let second = segments.second { + body(second) + } + self.count = 0 + } + + @_alwaysEmitIntoClient + @_transparent + internal mutating func unsafeConsumePrefix( + upTo offset: Int, + with body: (UnsafeMutableBufferPointer) -> Void + ) { + assert(offset >= 0 && offset <= count) + let segments = mutableSegments(forOffsets: Range(uncheckedBounds: (0, offset))) + body(segments.first) + if let second = segments.second { + body(second) + } + self.startSlot = self.slot(forOffset: offset) + self.count &-= offset + } +} + +// MARK: Appending and prepending + +extension _UnsafeDequeHandle where Element: ~Copyable { + /// Append `element` to the end of this buffer. The buffer must have enough + /// free capacity to insert one new element. + /// + /// This function does not validate its input arguments in release builds. Nor + /// does it ensure that the storage buffer is uniquely referenced. + @_alwaysEmitIntoClient + @_transparent + internal mutating func uncheckedAppend(_ element: consuming Element) { + assert(count < capacity) + mutablePtr(at: endSlot).initialize(to: element) + count &+= 1 + } + + /// Prepend `element` to the front of this buffer. The buffer must have enough + /// free capacity to insert one new element. + /// + /// This function does not validate its input arguments in release builds. Nor + /// does it ensure that the storage buffer is uniquely referenced. + @_alwaysEmitIntoClient + @_transparent + internal mutating func uncheckedPrepend(_ element: consuming Element) { + assert(count < capacity) + let slot = self.slot(before: startSlot) + mutablePtr(at: slot).initialize(to: element) + startSlot = slot + count &+= 1 + } +} + +#if compiler(>=6.2) +@available(SwiftStdlib 5.0, *) +extension UnsafeMutableBufferPointer where Element: ~Copyable { + @_alwaysEmitIntoClient + @_transparent + internal func _initialize( + initializedCount: inout Int, + initializingWith body: (inout OutputSpan) throws(E) -> R + ) throws(E) -> R { + var span = OutputSpan(buffer: self, initializedCount: 0) + defer { + initializedCount &+= span.finalize(for: self) + span = OutputSpan() + } + return try body(&span) + } +} +#endif + +extension _UnsafeDequeHandle where Element: ~Copyable { + @_alwaysEmitIntoClient + internal mutating func _append( + count: Int + ) -> _UnsafeMutableDequeSegments? { + guard count > 0 else { return nil } + let origCount = self.count + self.count &+= count + return self.mutableSegments(forOffsets: origCount ..< origCount + count) + } + + @_alwaysEmitIntoClient + internal mutating func _prepend( + count: Int + ) -> _UnsafeMutableDequeSegments? { + assert(self.count + count <= capacity) + guard count > 0 else { return .init() } + let oldStart = self.startSlot + self.startSlot = self.slot(startSlot, offsetBy: -count) + self.count &+= count + + return self.mutableSegments(between: self.startSlot, and: oldStart) + } +} + +#if compiler(>=6.2) +@available(SwiftStdlib 5.0, *) +extension _UnsafeDequeHandle where Element: ~Copyable { + /// Append a given number of items to the end of this deque by populating + /// a series of storage regions through repeated calls of the specified + /// callback function. + /// + /// This unchecked routine does not verify that the deque has sufficient + /// capacity to store the new items. + /// + /// The newly appended items are not guaranteed to form a single contiguous + /// storage region. Therefore, the supplied callback may be invoked multiple + /// times to initialize each successive chunk of storage. However, invocations + /// cease when the callback fails to fully populate its output span or when if + /// it throws an error. In such cases, the deque keeps all items that were + /// successfully initialized before the callback terminated. + /// + /// - Parameters: + /// - capacity: The maximum number of items to append to the deque. + /// - body: A callback that gets called at most twice to directly + /// populate newly reserved storage within the deque. The function + /// is allowed to initialize fewer than `count` items. The deque is + /// appended however many items the callback adds to the output span + /// before it returns (or before it throws an error). + /// + /// - Complexity: O(`capacity`) + @_alwaysEmitIntoClient + internal mutating func uncheckedAppend( + maximumCount: Int, + initializingWith body: (inout OutputSpan) throws(E) -> Void + ) throws(E) { + let gap = self.mutableSegments(forOffsets: count ..< count + maximumCount) + let c = self.count &+ gap.first.count + try gap.first._initialize( + initializedCount: &self.count, initializingWith: body) + if self.count == c, let second = gap.second { + try second._initialize( + initializedCount: &self.count, initializingWith: body) + } + } + + /// Prepend a given number of items to the end of this deque by populating + /// a series of storage regions through repeated calls of the specified + /// callback function. + /// + /// This unchecked routine does not verify that the deque has sufficient + /// capacity to store the new items. + /// + /// var buffer = RigidDeque(capacity: 20) + /// buffer.append(10) + /// var i = 0 + /// buffer.prepend(count: 10) { target in + /// while !target.isFull { + /// target.append(i) + /// i += 1 + /// } + /// } + /// // `buffer` now contains [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + /// + /// The newly prepended items are not guaranteed to form a single contiguous + /// storage region. Therefore, the supplied callback may be invoked multiple + /// times to initialize each successive chunk of storage. However, invocations + /// cease when the callback fails to fully populate its output span or when if + /// it throws an error. In such cases, the deque keeps all items that were + /// successfully initialized before the callback terminated. + /// + /// var buffer = RigidDeque(capacity: 20) + /// buffer.append(10) + /// var i = 0 + /// buffer.prepend(count: 10) { target in + /// while !target.isFull, i <= 5 { + /// target.append(i) + /// i += 1 + /// } + /// } + /// // `buffer` now contains [0, 1, 2, 3, 4, 5, 10] + /// + /// - Parameters: + /// - count: The number of items to append to the deque. + /// - body: A callback that gets called at most twice to directly + /// populate newly reserved storage within the deque. The function + /// is allowed to initialize fewer than `count` items. The deque is + /// prepended however many items the callback adds to output span + /// before it returns (or before it throws an error). + /// + /// - Complexity: O(`count`) + @_alwaysEmitIntoClient + internal mutating func uncheckedPrepend( + addingCount newItemCount: Int, + initializingWith body: (inout OutputSpan) throws(E) -> Void + ) throws(E) { + guard let gap = self._prepend(count: newItemCount) else { return } + + var c = 0 + defer { + if c < newItemCount { + closeGap(offsets: c ..< newItemCount) + } + } + try gap.first._initialize(initializedCount: &c, initializingWith: body) + if c == gap.first.count, let second = gap.second { + try second._initialize(initializedCount: &c, initializingWith: body) + } + } +} +#endif + +@available(SwiftStdlib 5.0, *) +extension _UnsafeDequeHandle where Element: ~Copyable { + /// Appends the elements of a buffer to the end of this deque, leaving the + /// buffer uninitialized. + /// + /// This unchecked routine does not verify that the deque has sufficient + /// capacity to store the new items. + /// + /// - Parameters: + /// - items: A fully initialized buffer whose contents to move into + /// the deque. + /// + /// - Complexity: O(`items.count`) + @_alwaysEmitIntoClient + internal mutating func uncheckedAppend( + moving items: UnsafeMutableBufferPointer + ) { + guard let gap = _append(count: items.count) else { return } + + gap.first.moveInitializeAll( + fromContentsOf: items._extracting(first: gap.first.count)) + + if let second = gap.second { + assert(gap.first.count + second.count == items.count) + second.moveInitializeAll( + fromContentsOf: items._extracting(last: second.count)) + } + } + + /// Prepends the elements of a buffer to the front of this deque, leaving the + /// buffer uninitialized. + /// + /// This unchecked routine does not verify that the deque has sufficient + /// capacity to store the new items. + /// + /// - Parameters: + /// - items: A fully initialized buffer whose contents to move into + /// the deque. + /// + /// - Complexity: O(`items.count`) + @_alwaysEmitIntoClient + internal mutating func uncheckedPrepend( + moving items: UnsafeMutableBufferPointer + ) { + guard let gap = _prepend(count: items.count) else { return } + + gap.first.moveInitializeAll( + fromContentsOf: items._extracting(first: gap.first.count)) + + if let second = gap.second { + assert(gap.first.count + second.count == items.count) + second.moveInitializeAll( + fromContentsOf: items._extracting(last: second.count)) + } + } +} + +extension _UnsafeDequeHandle { + /// Append the contents of `source` to this buffer. The buffer must have + /// enough free capacity to insert the new elements. + /// + /// This function does not validate its input arguments in release builds. Nor + /// does it ensure that the storage buffer is uniquely referenced. + @_alwaysEmitIntoClient + @_transparent + internal mutating func uncheckedAppend(copying source: UnsafeBufferPointer) { + guard let gap = _append(count: source.count) else { return } + gap.initialize(copying: source) + } + + /// Prepend the contents of `source` to this buffer. The buffer must have + /// enough free capacity to insert the new elements. + /// + /// This function does not validate its input arguments in release builds. Nor + /// does it ensure that the storage buffer is uniquely referenced. + @_alwaysEmitIntoClient + @_transparent + internal mutating func uncheckedPrepend(copying source: UnsafeBufferPointer) { + guard let gap = _prepend(count: source.count) else { return } + gap.initialize(copying: source) + } +} + +@available(SwiftStdlib 5.0, *) +extension _UnsafeDequeHandle { + @_alwaysEmitIntoClient + @inline(__always) + internal mutating func uncheckedAppend>( + copyingPrefixOf items: S + ) -> S.Iterator { + // Note: You're supposed to handle contiguous sequences before calling + // this function. You do this by invoking `withContiguousStorageIfAvailable`. + let (it, c) = self.availableSegments().initialize(fromSequencePrefix: items) + self.count += c + return it + } + + @_alwaysEmitIntoClient + @inline(__always) + internal mutating func uncheckedPrepend>( + copying items: C, + exactCount: Int + ) { + // Note: You're supposed to handle contiguous sequences before calling + // this function. You do this by invoking `withContiguousStorageIfAvailable`. + guard let gap = self._prepend(count: exactCount) else { return } + gap.initialize(copying: items) + } +} + +// MARK: Opening and Closing Gaps + +extension _UnsafeDequeHandle where Element: ~Copyable { + @discardableResult + @_alwaysEmitIntoClient + @_transparent + internal mutating func move( + from source: Slot, + to target: Slot, + count: Int + ) -> (source: Slot, target: Slot) { + assert(count >= 0) + assert(source.position + count <= self.capacity) + assert(target.position + count <= self.capacity) + guard count > 0 else { return (source, target) } + mutablePtr(at: target) + .moveInitialize(from: mutablePtr(at: source), count: count) + return (slot(source, offsetBy: count), slot(target, offsetBy: count)) + } + + @_alwaysEmitIntoClient + @_transparent + func isLeftLeaning(_ offset: Int) -> Bool { + offset < count - offset + } + + @_alwaysEmitIntoClient + @_transparent + func isLeftLeaning(_ subrange: Range) -> Bool { + subrange.lowerBound < count - subrange.upperBound + } + + /// Slide elements around so that there is a gap of uninitialized slots of + /// size `gapSize` starting at `offset`, and return a (potentially wrapped) + /// buffer holding the newly inserted slots. + /// + /// This function does not validate its input arguments in release builds. Nor + /// does it ensure that the storage buffer is uniquely referenced. + /// + /// - Parameter gapSize: The number of uninitialized slots to create. + /// - Parameter offset: The offset from the start at which the uninitialized + /// slots should start. + @_alwaysEmitIntoClient + internal mutating func openGap( + ofSize gapSize: Int, + atOffset offset: Int + ) -> _UnsafeMutableDequeSegments { + assert(offset >= 0 && offset <= self.count) + assert(self.count + gapSize <= capacity) + assert(gapSize > 0) + + let headCount = offset + let tailCount = count - offset + if tailCount <= headCount { + // Open the gap by sliding elements to the right. + + let originalEnd = self.slot(startSlot, offsetBy: count) + let newEnd = self.slot(startSlot, offsetBy: count + gapSize) + let gapStart = self.slot(forOffset: offset) + let gapEnd = self.slot(gapStart, offsetBy: gapSize) + + let sourceIsContiguous = gapStart <= originalEnd.orIfZero(capacity) + let targetIsContiguous = gapEnd <= newEnd.orIfZero(capacity) + + if sourceIsContiguous && targetIsContiguous { + // No need to deal with wrapping; we just need to slide + // elements after the gap. + + // Illustrated steps: (underscores mark eventual gap position) + // + // 0) ....ABCDE̲F̲G̲H..... EFG̲H̲.̲........ABCD .̲.......ABCDEFGH̲.̲ + // 1) ....ABCD.̲.̲.̲EFGH.. EF.̲.̲.̲GH......ABCD .̲H......ABCDEFG.̲.̲ + move(from: gapStart, to: gapEnd, count: tailCount) + } else if targetIsContiguous { + // The gap itself will be wrapped. + + // Illustrated steps: (underscores mark eventual gap position) + // + // 0) E̲FGH.........ABC̲D̲ + // 1) .̲..EFGH......ABC̲D̲ + // 2) .̲CDEFGH......AB.̲.̲ + assert(startSlot > originalEnd.orIfZero(capacity)) + move(from: .zero, to: Slot.zero.advanced(by: gapSize), count: originalEnd.position) + move(from: gapStart, to: gapEnd, count: capacity - gapStart.position) + } else if sourceIsContiguous { + // Opening the gap pushes subsequent elements across the wrap. + + // Illustrated steps: (underscores mark eventual gap position) + // + // 0) ........ABC̲D̲E̲FGH. + // 1) GH......ABC̲D̲E̲F... + // 2) GH......AB.̲.̲.̲CDEF + move(from: limSlot.advanced(by: -gapSize), to: .zero, count: newEnd.position) + move(from: gapStart, to: gapEnd, count: tailCount - newEnd.position) + } else { + // The rest of the items are wrapped, and will remain so. + + // Illustrated steps: (underscores mark eventual gap position) + // + // 0) GH.........AB̲C̲D̲EF + // 1) ...GH......AB̲C̲D̲EF + // 2) DEFGH......AB̲C̲.̲.. + // 3) DEFGH......A.̲.̲.̲BC + move(from: .zero, to: Slot.zero.advanced(by: gapSize), count: originalEnd.position) + move(from: limSlot.advanced(by: -gapSize), to: .zero, count: gapSize) + move(from: gapStart, to: gapEnd, count: tailCount - gapSize - originalEnd.position) + } + count += gapSize + return mutableSegments(between: gapStart, and: gapEnd.orIfZero(capacity)) + } + + // Open the gap by sliding elements to the left. + + let originalStart = self.startSlot + let newStart = self.slot(originalStart, offsetBy: -gapSize) + let gapEnd = self.slot(forOffset: offset) + let gapStart = self.slot(gapEnd, offsetBy: -gapSize) + + let sourceIsContiguous = originalStart <= gapEnd.orIfZero(capacity) + let targetIsContiguous = newStart <= gapStart.orIfZero(capacity) + + if sourceIsContiguous && targetIsContiguous { + // No need to deal with any wrapping. + + // Illustrated steps: (underscores mark eventual gap position) + // + // 0) ....A̲B̲C̲DEFGH... GH.........̲A̲B̲CDEF .̲A̲B̲CDEFGH.......̲.̲ + // 1) .ABC.̲.̲.̲DEFGH... GH......AB.̲.̲.̲CDEF .̲.̲.̲CDEFGH....AB.̲.̲ + move(from: originalStart, to: newStart, count: headCount) + } else if targetIsContiguous { + // The gap itself will be wrapped. + + // Illustrated steps: (underscores mark eventual gap position) + // + // 0) C̲D̲EFGH.........A̲B̲ + // 1) C̲D̲EFGH.....AB...̲.̲ + // 2) .̲.̲EFGH.....ABCD.̲.̲ + assert(originalStart >= newStart) + move(from: originalStart, to: newStart, count: capacity - originalStart.position) + move(from: .zero, to: limSlot.advanced(by: -gapSize), count: gapEnd.position) + } else if sourceIsContiguous { + // Opening the gap pushes preceding elements across the wrap. + + // Illustrated steps: (underscores mark eventual gap position) + // + // 0) .AB̲C̲D̲EFGH......... + // 1) ...̲C̲D̲EFGH.......AB + // 2) CD.̲.̲.̲EFGH.......AB + move(from: originalStart, to: newStart, count: capacity - newStart.position) + move(from: Slot.zero.advanced(by: gapSize), to: .zero, count: gapStart.position) + } else { + // The preceding of the items are wrapped, and will remain so. + + // Illustrated steps: (underscores mark eventual gap position) + // 0) CD̲E̲F̲GHIJKL.........AB + // 1) CD̲E̲F̲GHIJKL......AB... + // 2) ..̲.̲F̲GHIJKL......ABCDE + // 3) F.̲.̲.̲GHIJKL......ABCDE + move(from: originalStart, to: newStart, count: capacity - originalStart.position) + move(from: .zero, to: limSlot.advanced(by: -gapSize), count: gapSize) + move(from: Slot.zero.advanced(by: gapSize), to: .zero, count: gapStart.position) + } + startSlot = newStart + count += gapSize + return mutableSegments(between: gapStart, and: gapEnd.orIfZero(capacity)) + } + + /// Close the gap of already uninitialized elements in `bounds`, sliding + /// elements outside of the gap to eliminate it, and updating `count` to + /// reflect the removal. + /// + /// This function does not validate its input arguments in release builds. Nor + /// does it ensure that the storage buffer is uniquely referenced. + @_alwaysEmitIntoClient + @_transparent + internal mutating func closeGap(offsets bounds: Range) { + assert(bounds.lowerBound >= 0 && bounds.upperBound <= self.count) + let gapSize = bounds.count + guard gapSize > 0 else { return } + + let gapStart = self.slot(forOffset: bounds.lowerBound) + let gapEnd = self.slot(forOffset: bounds.upperBound) + + let headCount = bounds.lowerBound + let tailCount = count - bounds.upperBound + + if headCount >= tailCount { + // Close the gap by sliding elements to the left. + let originalEnd = endSlot + let newEnd = self.slot(forOffset: count - gapSize) + + let sourceIsContiguous = gapEnd < originalEnd.orIfZero(capacity) + let targetIsContiguous = gapStart <= newEnd.orIfZero(capacity) + if tailCount == 0 { + // No need to move any elements. + } else if sourceIsContiguous && targetIsContiguous { + // No need to deal with wrapping. + + // 0) ....ABCD.̲.̲.̲EFGH.. EF.̲.̲.̲GH........ABCD .̲.̲.̲E..........ABCD.̲.̲ .̲.̲.̲EF........ABCD .̲.̲.̲DE.......ABC + // 1) ....ABCDE̲F̲G̲H..... EFG̲H̲.̲..........ABCD .̲.̲.̲...........ABCDE̲.̲ E̲F̲.̲..........ABCD D̲E̲.̲.........ABC + move(from: gapEnd, to: gapStart, count: tailCount) + } else if sourceIsContiguous { + // The gap lies across the wrap from the subsequent elements. + + // 0) .̲.̲.̲EFGH.......ABCD.̲.̲ EFGH.......ABCD.̲.̲.̲ + // 1) .̲.̲.̲..GH.......ABCDE̲F̲ ..GH.......ABCDE̲F̲G̲ + // 2) G̲H̲.̲...........ABCDE̲F̲ GH.........ABCDE̲F̲G̲ + let c = capacity - gapStart.position + assert(tailCount > c) + let next = move(from: gapEnd, to: gapStart, count: c) + move(from: next.source, to: .zero, count: tailCount - c) + } else if targetIsContiguous { + // We need to move elements across a wrap, but the wrap will + // disappear when we're done. + + // 0) HI....ABCDE.̲.̲.̲FG + // 1) HI....ABCDEF̲G̲.̲.. + // 2) ......ABCDEF̲G̲H̲I. + let next = move(from: gapEnd, to: gapStart, count: capacity - gapEnd.position) + move(from: .zero, to: next.target, count: originalEnd.position) + } else { + // We need to move elements across a wrap that won't go away. + + // 0) HIJKL....ABCDE.̲.̲.̲FG + // 1) HIJKL....ABCDEF̲G̲.̲.. + // 2) ...KL....ABCDEF̲G̲H̲IJ + // 3) KL.......ABCDEF̲G̲H̲IJ + var next = move(from: gapEnd, to: gapStart, count: capacity - gapEnd.position) + next = move(from: .zero, to: next.target, count: gapSize) + move(from: next.source, to: .zero, count: newEnd.position) + } + count -= gapSize + } else { + // Close the gap by sliding elements to the right. + let originalStart = startSlot + let newStart = slot(startSlot, offsetBy: gapSize) + + let sourceIsContiguous = originalStart < gapStart.orIfZero(capacity) + let targetIsContiguous = newStart <= gapEnd.orIfZero(capacity) + + if headCount == 0 { + // No need to move any elements. + } else if sourceIsContiguous && targetIsContiguous { + // No need to deal with wrapping. + + // 0) ....ABCD.̲.̲.̲EFGH..... EFGH........AB.̲.̲.̲CD .̲.̲.̲CDEFGH.......AB.̲.̲ DEFGH.......ABC.̲.̲ + // 1) .......AB̲C̲D̲EFGH..... EFGH...........̲A̲B̲CD .̲A̲B̲CDEFGH..........̲.̲ DEFGH.........AB̲C̲ ABCDEFGH........̲.̲.̲ + move(from: originalStart, to: newStart, count: headCount) + } else if sourceIsContiguous { + // The gap lies across the wrap from the preceding elements. + + // 0) .̲.̲DEFGH.......ABC.̲.̲ .̲.̲.̲EFGH.......ABCD + // 1) B̲C̲DEFGH.......A...̲.̲ B̲C̲D̲DEFGH......A... + // 2) B̲C̲DEFGH...........̲A̲ B̲C̲D̲DEFGH.........A + move(from: limSlot.advanced(by: -gapSize), to: .zero, count: gapEnd.position) + move(from: startSlot, to: newStart, count: headCount - gapEnd.position) + } else if targetIsContiguous { + // We need to move elements across a wrap, but the wrap will + // disappear when we're done. + + // 0) CD.̲.̲.̲EFGHI.....AB + // 1) ...̲C̲D̲EFGHI.....AB + // 1) .AB̲C̲D̲EFGHI....... + move(from: .zero, to: gapEnd.advanced(by: -gapStart.position), count: gapStart.position) + move(from: startSlot, to: newStart, count: headCount - gapStart.position) + } else { + // We need to move elements across a wrap that won't go away. + // 0) FG.̲.̲.̲HIJKLMNO....ABCDE + // 1) ...̲F̲G̲HIJKLMNO....ABCDE + // 2) CDE̲F̲G̲HIJKLMNO....AB... + // 3) CDE̲F̲G̲HIJKLMNO.......AB + move(from: .zero, to: Slot.zero.advanced(by: gapSize), count: gapStart.position) + move(from: limSlot.advanced(by: -gapSize), to: .zero, count: gapSize) + move(from: startSlot, to: newStart, count: headCount - gapEnd.position) + } + startSlot = newStart + count -= gapSize + } + } +} + +// MARK: Rotating elements + +extension _UnsafeDequeHandle where Element: ~Copyable { + @_alwaysEmitIntoClient + internal mutating func rotate( + toStartAtOffset newStart: Int + ) { + let oldCount = count + // Open a gap at `newStart` that's the size of the free capacity, swapping + // the positions of the prefix (`startSlot.. 0 { + _ = openGap(ofSize: gapSize, atOffset: newStart) + } + + // With the prefix and suffix swapped, update the starting slot and + // restore the count. + startSlot = slot(startSlot, offsetBy: newStart - oldCount) + count = oldCount + } +} + +// MARK: Insertion + +extension _UnsafeDequeHandle where Element: ~Copyable { + @_alwaysEmitIntoClient + @_transparent + internal mutating func uncheckedInsert( + _ newElement: consuming Element, at offset: Int + ) { + assert(count < capacity) + if offset == 0 { + uncheckedPrepend(newElement) + return + } + if offset == count { + uncheckedAppend(newElement) + return + } + let gap = openGap(ofSize: 1, atOffset: offset) + assert(gap.first.count == 1) + gap.first.baseAddress!.initialize(to: newElement) + } +} + +#if compiler(>=6.2) +@available(SwiftStdlib 5.0, *) +extension _UnsafeDequeHandle where Element: ~Copyable { + @_alwaysEmitIntoClient + internal mutating func uncheckedInsert( + addingCount newItemCount: Int, + at offset: Int, + initializingWith body: (inout OutputSpan) throws(E) -> Void + ) throws(E) { + guard newItemCount > 0 else { return } + let gap = self.openGap(ofSize: newItemCount, atOffset: offset) + + var c = 0 + defer { + if c < newItemCount { + closeGap(offsets: offset + c ..< offset + newItemCount) + } + } + try gap.first._initialize(initializedCount: &c, initializingWith: body) + if c == gap.first.count, let second = gap.second { + try second._initialize(initializedCount: &c, initializingWith: body) + } + } +} +#endif + +extension _UnsafeDequeHandle { + /// Insert all elements from `newElements` into this deque, starting at + /// `offset`. + /// + /// This function does not validate its input arguments in release builds. Nor + /// does it ensure that the storage buffer is uniquely referenced. + /// + /// - Parameter newElements: The elements to insert. + /// - Parameter newCount: Must be equal to `newElements.count`. Used to + /// prevent calling `count` more than once. + /// - Parameter offset: The desired offset from the start at which to place + /// the first element. + @_alwaysEmitIntoClient + internal mutating func uncheckedInsert( + contentsOf newElements: __owned C, + count newCount: Int, + atOffset offset: Int + ) where C.Element == Element { + assert(offset <= count) + assert(newElements.count == newCount) + guard newCount > 0 else { return } + let gap = openGap(ofSize: newCount, atOffset: offset) + gap.initialize(copying: newElements) + } +} + +// MARK: Removal + +extension _UnsafeDequeHandle where Element: ~Copyable { + @_alwaysEmitIntoClient + @_transparent + internal mutating func uncheckedRemove(at offset: Int) -> Element { + let slot = self.slot(forOffset: offset) + let result = mutablePtr(at: slot).move() + closeGap(offsets: Range(uncheckedBounds: (offset, offset + 1))) + return result + } + + @_alwaysEmitIntoClient + @_transparent + internal mutating func uncheckedRemoveFirst() -> Element { + assert(count > 0) + let result = mutablePtr(at: startSlot).move() + startSlot = slot(after: startSlot) + count -= 1 + return result + } + + @_alwaysEmitIntoClient + @_transparent + internal mutating func uncheckedRemoveLast() -> Element { + assert(count > 0) + let slot = self.slot(forOffset: count - 1) + let result = mutablePtr(at: slot).move() + count -= 1 + return result + } + + @_alwaysEmitIntoClient + @_transparent + internal mutating func uncheckedRemoveFirst(_ n: Int) { + assert(count >= n) + guard n > 0 else { return } + let target = mutableSegments(forOffsets: 0 ..< n) + target.deinitialize() + startSlot = slot(startSlot, offsetBy: n) + count -= n + } + + @_alwaysEmitIntoClient + @_transparent + internal mutating func uncheckedRemoveLast(_ n: Int) { + assert(count >= n) + guard n > 0 else { return } + let target = mutableSegments(forOffsets: count - n ..< count) + target.deinitialize() + count -= n + } + + /// Remove all elements stored in this instance, deinitializing their storage. + /// + /// This method does not ensure that the storage buffer is uniquely + /// referenced. + @_alwaysEmitIntoClient + @_transparent + internal mutating func uncheckedRemoveAll() { + guard count > 0 else { return } + let target = mutableSegments() + target.deinitialize() + count = 0 + startSlot = .zero + } + + /// Remove all elements in `bounds`, deinitializing their storage and sliding + /// remaining elements to close the resulting gap. + /// + /// This function does not validate its input arguments in release builds. Nor + /// does it ensure that the storage buffer is uniquely referenced. + @_alwaysEmitIntoClient + @_transparent + internal mutating func uncheckedRemove(offsets bounds: Range) { + assert(bounds.lowerBound >= 0 && bounds.upperBound <= self.count) + + // Deinitialize elements in `bounds`. + mutableSegments(forOffsets: bounds).deinitialize() + closeGap(offsets: bounds) + } +} + +// MARK: Replacement + +#if compiler(>=6.2) +@available(SwiftStdlib 5.0, *) +extension _UnsafeDequeHandle where Element: ~Copyable { + @_alwaysEmitIntoClient + internal mutating func _insertAfterReplace( + _ subrange: Range, + addingCount newItemCount: Int, + initializingWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) -> Void { + // Note: we're careful to open/close the gap in a direction that does not + // lead to trying to move slots we deinitialized above. + let delta = newItemCount - subrange.count + let left = isLeftLeaning(subrange) + if delta > 0 { + _ = self.openGap( + ofSize: delta, + atOffset: (left ? subrange.lowerBound : subrange.upperBound)) + } else { + self.closeGap( + offsets: (left ? subrange.prefix(-delta) : subrange.suffix(-delta))) + } + let newRange = Range( + uncheckedBounds: ( + subrange.lowerBound, + subrange.lowerBound &+ newItemCount)) + let gap = self.mutableSegments(forOffsets: newRange) + + var c = 0 + defer { + if c < newItemCount { + closeGap(offsets: newRange.dropFirst(c)) + } + } + try gap.first._initialize(initializedCount: &c, initializingWith: initializer) + if c == gap.first.count, let second = gap.second { + try second._initialize(initializedCount: &c, initializingWith: initializer) + } + } + + @_alwaysEmitIntoClient + internal mutating func uncheckedReplace( + removing subrange: Range, + addingCount newItemCount: Int, + initializingWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) -> Void { + assert( + subrange.lowerBound >= 0 && subrange.upperBound <= count, + "Subrange out of bounds") + assert(newItemCount >= 0, "Cannot add a negative number of items") + assert(count + newItemCount - subrange.count <= capacity, "RigidDeque capacity overflow") + self.mutableSegments(forOffsets: subrange).deinitialize() + try _insertAfterReplace( + subrange, + addingCount: newItemCount, + initializingWith: initializer) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @_alwaysEmitIntoClient + internal mutating func uncheckedReplace( + removing subrange: Range, + consumingWith consumer: (inout InputSpan) -> Void, + addingCount newItemCount: Int, + initializingWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) -> Void { + assert( + subrange.lowerBound >= 0 && subrange.upperBound <= count, + "Subrange out of bounds") + assert(newItemCount >= 0, "Cannot add a negative number of items") + assert(count + newItemCount - subrange.count <= capacity, "RigidDeque capacity overflow") + do { + let removed = self.mutableSegments(forOffsets: subrange) + var span = InputSpan( + buffer: removed.first, + initializedCount: removed.first.count) + consumer(&span) + if let second = removed.second { + span = InputSpan(buffer: second, initializedCount: second.count) + consumer(&span) + } + } + try _insertAfterReplace( + subrange, + addingCount: newItemCount, + initializingWith: initializer) + } +#endif +} +#endif diff --git a/Sources/DequeModule/_UnsafeWrappedBuffer.swift b/Sources/DequeModule/_UnsafeDequeSegments.swift similarity index 64% rename from Sources/DequeModule/_UnsafeWrappedBuffer.swift rename to Sources/DequeModule/_UnsafeDequeSegments.swift index 1faefacc..c5e334a6 100644 --- a/Sources/DequeModule/_UnsafeWrappedBuffer.swift +++ b/Sources/DequeModule/_UnsafeDequeSegments.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors +// Copyright (c) 2021 - 2026 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information @@ -11,19 +11,20 @@ #if !COLLECTIONS_SINGLE_MODULE import InternalCollectionsUtilities +import ContainersPreview #endif @frozen @usableFromInline -internal struct _UnsafeWrappedBuffer { +internal struct _UnsafeDequeSegments { @usableFromInline internal let first: UnsafeBufferPointer @usableFromInline internal let second: UnsafeBufferPointer? - @inlinable - @inline(__always) + @_alwaysEmitIntoClient + @_transparent internal init( _ first: UnsafeBufferPointer, _ second: UnsafeBufferPointer? = nil @@ -33,7 +34,8 @@ internal struct _UnsafeWrappedBuffer { assert(first.count > 0 || second == nil) } - @inlinable + @_alwaysEmitIntoClient + @_transparent internal init( start: UnsafePointer, count: Int @@ -41,7 +43,8 @@ internal struct _UnsafeWrappedBuffer { self.init(UnsafeBufferPointer(start: start, count: count)) } - @inlinable + @_alwaysEmitIntoClient + @_transparent internal init( first start1: UnsafePointer, count count1: Int, @@ -52,21 +55,40 @@ internal struct _UnsafeWrappedBuffer { UnsafeBufferPointer(start: start2, count: count2)) } - @inlinable + @_alwaysEmitIntoClient + @_transparent internal var count: Int { first.count + (second?.count ?? 0) } + + @_alwaysEmitIntoClient + @_transparent + internal func isIdentical(to other: Self) -> Bool { + guard self.first._isIdentical(to: other.first) else { return false } + switch (self.second, other.second) { + case (nil, nil): return true + case let (a?, b?): return a._isIdentical(to: b) + default: return false + } + } } @frozen @usableFromInline -internal struct _UnsafeMutableWrappedBuffer { +internal struct _UnsafeMutableDequeSegments { @usableFromInline internal let first: UnsafeMutableBufferPointer @usableFromInline internal let second: UnsafeMutableBufferPointer? - @inlinable - @inline(__always) + @_alwaysEmitIntoClient + @_transparent + internal init() { + self.first = .init(start: nil, count: 0) + self.second = nil + } + + @_alwaysEmitIntoClient + @_transparent internal init( _ first: UnsafeMutableBufferPointer, _ second: UnsafeMutableBufferPointer? = nil @@ -76,26 +98,8 @@ internal struct _UnsafeMutableWrappedBuffer { assert(first.count > 0 || second == nil) } - @inlinable - @inline(__always) - internal init( - _ first: UnsafeMutableBufferPointer.SubSequence, - _ second: UnsafeMutableBufferPointer? = nil - ) { - self.init(UnsafeMutableBufferPointer(rebasing: first), second) - } - - @inlinable - @inline(__always) - internal init( - _ first: UnsafeMutableBufferPointer, - _ second: UnsafeMutableBufferPointer.SubSequence - ) { - self.init(first, UnsafeMutableBufferPointer(rebasing: second)) - } - - @inlinable - @inline(__always) + @_alwaysEmitIntoClient + @_transparent internal init( start: UnsafeMutablePointer, count: Int @@ -103,8 +107,8 @@ internal struct _UnsafeMutableWrappedBuffer { self.init(UnsafeMutableBufferPointer(start: start, count: count)) } - @inlinable - @inline(__always) + @_alwaysEmitIntoClient + @_transparent internal init( first start1: UnsafeMutablePointer, count count1: Int, @@ -115,58 +119,84 @@ internal struct _UnsafeMutableWrappedBuffer { UnsafeMutableBufferPointer(start: start2, count: count2)) } - @inlinable - @inline(__always) - internal init(mutating buffer: _UnsafeWrappedBuffer) { + @_alwaysEmitIntoClient + @_transparent + internal init(mutating buffer: _UnsafeDequeSegments) { self.init(.init(mutating: buffer.first), buffer.second.map { .init(mutating: $0) }) } } -extension _UnsafeMutableWrappedBuffer { - @inlinable - @inline(__always) +extension _UnsafeMutableDequeSegments { + @_alwaysEmitIntoClient + @_transparent + internal init( + _ first: UnsafeMutableBufferPointer.SubSequence, + _ second: UnsafeMutableBufferPointer? = nil + ) { + self.init(UnsafeMutableBufferPointer(rebasing: first), second) + } + + @_alwaysEmitIntoClient + @_transparent + internal init( + _ first: UnsafeMutableBufferPointer, + _ second: UnsafeMutableBufferPointer.SubSequence + ) { + self.init(first, UnsafeMutableBufferPointer(rebasing: second)) + } +} + +extension _UnsafeMutableDequeSegments where Element: ~Copyable { + @_alwaysEmitIntoClient + @_transparent internal var count: Int { first.count + (second?.count ?? 0) } - @inlinable + @_alwaysEmitIntoClient + @_transparent internal func prefix(_ n: Int) -> Self { assert(n >= 0) if n >= self.count { return self } if n <= first.count { - return Self(first.prefix(n)) + return Self(first._extracting(first: n)) } - return Self(first, second!.prefix(n - first.count)) + return Self(first, second!._extracting(first: n - first.count)) } - @inlinable + @_alwaysEmitIntoClient + @_transparent internal func suffix(_ n: Int) -> Self { assert(n >= 0) if n >= self.count { return self } guard let second = second else { - return Self(first.suffix(n)) + return Self(first._extracting(last: n)) } if n <= second.count { - return Self(second.suffix(n)) + return Self(second._extracting(last: n)) } - return Self(first.suffix(n - second.count), second) + return Self(first._extracting(last: n - second.count), second) } } -extension _UnsafeMutableWrappedBuffer { - @inlinable +extension _UnsafeMutableDequeSegments where Element: ~Copyable { + @_alwaysEmitIntoClient + @_transparent internal func deinitialize() { first.deinitialize() second?.deinitialize() } +} - @inlinable +extension _UnsafeMutableDequeSegments { @discardableResult + @_alwaysEmitIntoClient + @_transparent internal func initialize( - fromPrefixOf iterator: inout I + copyingPrefixOf iterator: inout I ) -> Int where I.Element == Element { var copied = 0 @@ -186,14 +216,15 @@ extension _UnsafeMutableWrappedBuffer { return wrapped ? first.count + copied : copied } - @inlinable + @_alwaysEmitIntoClient + @_transparent internal func initialize( fromSequencePrefix elements: __owned S ) -> (iterator: S.Iterator, count: Int) where S.Element == Element { guard second == nil || first.count >= elements.underestimatedCount else { var it = elements.makeIterator() - let copied = initialize(fromPrefixOf: &it) + let copied = initialize(copyingPrefixOf: &it) return (it, copied) } // Note: Array._copyContents traps when not given enough space, so we @@ -214,10 +245,34 @@ extension _UnsafeMutableWrappedBuffer { return (it, copied) } - @inlinable - internal func initialize( - from elements: __owned C - ) where C.Element == Element { + @_alwaysEmitIntoClient + @_transparent + internal func initialize( + copying elements: UnsafeBufferPointer + ) { + assert(self.count == elements.count) + if let second = second { + let wrap = first.count + first.initializeAll(fromContentsOf: elements._extracting(first: wrap)) + second.initializeAll(fromContentsOf: elements._extracting(last: second.count)) + } else { + first.initializeAll(fromContentsOf: elements) + } + } + + @_alwaysEmitIntoClient + @_transparent + internal func initialize( + copying elements: UnsafeMutableBufferPointer + ) { + self.initialize(copying: UnsafeBufferPointer(elements)) + } + + @_alwaysEmitIntoClient + @_transparent + internal func initialize( + copying elements: __owned some Collection + ) { assert(self.count == elements.count) if let second = second { let wrap = elements.index(elements.startIndex, offsetBy: first.count) @@ -228,12 +283,13 @@ extension _UnsafeMutableWrappedBuffer { } } - @inlinable - internal func assign( - from elements: C + @_alwaysEmitIntoClient + @_transparent + internal func reassign( + copying elements: C ) where C.Element == Element { assert(elements.count == self.count) deinitialize() - initialize(from: elements) + initialize(copying: elements) } } diff --git a/Sources/HashTreeCollections/HashNode/_HashNode+Storage.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Storage.swift index 0ce0ec3c..1f6375d0 100644 --- a/Sources/HashTreeCollections/HashNode/_HashNode+Storage.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Storage.swift @@ -42,6 +42,7 @@ extension _HashNode { @usableFromInline internal typealias UnsafeHandle = _HashNode.UnsafeHandle + @inlinable deinit { UnsafeHandle.update(self) { handle in handle.children.deinitialize() diff --git a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Collection.swift b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Collection.swift index a3012eb3..06ea6bcd 100644 --- a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Collection.swift +++ b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Collection.swift @@ -159,7 +159,7 @@ extension TreeDictionary: Collection { @inlinable public subscript(i: Index) -> Element { precondition(_isValid(i), "Invalid index") - precondition(i._path.isOnItem, "Can't get element at endIndex") + precondition(i._path.isOnItem, "Cannot get element at endIndex") return _UnsafeHandle.read(i._path.node) { $0[item: i._path.currentItemSlot] } diff --git a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary.swift b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary.swift index 5152e1bf..02795f9b 100644 --- a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary.swift +++ b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary.swift @@ -542,7 +542,7 @@ extension TreeDictionary { @inlinable public mutating func remove(at index: Index) -> Element { precondition(_isValid(index), "Invalid index") - precondition(index._path._isItem, "Can't remove item at end index") + precondition(index._path._isItem, "Cannot remove item at end index") _invalidateIndices() let r = _root.remove(.top, at: index._path) assert(r.remainder == nil) diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+Collection.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+Collection.swift index b0a8f72d..8e36ad51 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+Collection.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+Collection.swift @@ -159,7 +159,7 @@ extension TreeSet: Collection { @inlinable public subscript(position: Index) -> Element { precondition(_isValid(position), "Invalid index") - precondition(position._path.isOnItem, "Can't get element at endIndex") + precondition(position._path.isOnItem, "Cannot get element at endIndex") return _UnsafeHandle.read(position._path.node) { $0[item: position._path.currentItemSlot].key } diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+Extras.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+Extras.swift index f02ac45f..f8325a5f 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+Extras.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+Extras.swift @@ -56,7 +56,7 @@ extension TreeSet { public mutating func update(_ member: Element, at index: Index) -> Element { defer { _fixLifetime(self) } precondition(_isValid(index), "Invalid index") - precondition(index._path.isOnItem, "Can't get element at endIndex") + precondition(index._path.isOnItem, "Cannot get element at endIndex") _invalidateIndices() return _UnsafeHandle.update(index._path.node) { let p = $0.itemPtr(at: index._path.currentItemSlot) diff --git a/Sources/InternalCollectionsUtilities/CMakeLists.txt b/Sources/InternalCollectionsUtilities/CMakeLists.txt index c007ce1c..c1154d81 100644 --- a/Sources/InternalCollectionsUtilities/CMakeLists.txt +++ b/Sources/InternalCollectionsUtilities/CMakeLists.txt @@ -25,10 +25,11 @@ target_sources(${module_name} PRIVATE "Descriptions.swift" "LifetimeOverride.swift" "RandomAccessCollection+Offsets.swift" + "Span+Extras.swift" "UnsafeBufferPointer+Extras.swift" "UnsafeMutableBufferPointer+Extras.swift" - "UnsafeRawBufferPointer+Extras.swift" "UnsafeMutableRawBufferPointer+Extras.swift" + "UnsafeRawBufferPointer+Extras.swift" "IntegerTricks/FixedWidthInteger+roundUpToPowerOfTwo.swift" "IntegerTricks/Integer rank.swift" "IntegerTricks/UInt+first and last set bit.swift" diff --git a/Sources/InternalCollectionsUtilities/IntegerTricks/FixedWidthInteger+roundUpToPowerOfTwo.swift b/Sources/InternalCollectionsUtilities/IntegerTricks/FixedWidthInteger+roundUpToPowerOfTwo.swift index dc38cb86..15dc9717 100644 --- a/Sources/InternalCollectionsUtilities/IntegerTricks/FixedWidthInteger+roundUpToPowerOfTwo.swift +++ b/Sources/InternalCollectionsUtilities/IntegerTricks/FixedWidthInteger+roundUpToPowerOfTwo.swift @@ -13,7 +13,7 @@ extension FixedWidthInteger { /// Round up `self` to the nearest power of two, assuming it's representable. /// Returns 0 if `self` isn't positive. @inlinable - package func _roundUpToPowerOfTwo() -> Self { + public func _roundUpToPowerOfTwo() -> Self { guard self > 0 else { return 0 } let l = Self.bitWidth - (self &- 1).leadingZeroBitCount return 1 << l diff --git a/Sources/InternalCollectionsUtilities/Span+Extras.swift b/Sources/InternalCollectionsUtilities/Span+Extras.swift new file mode 100644 index 00000000..a1e7473c --- /dev/null +++ b/Sources/InternalCollectionsUtilities/Span+Extras.swift @@ -0,0 +1,73 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension Span where Element: ~Copyable { + @_lifetime(copy self) + @_alwaysEmitIntoClient + package mutating func _trim(first maxLength: Int) -> Self { + precondition(maxLength >= 0, "Cannot have a prefix of negative length") + let cut = Swift.min(maxLength, count) + guard cut > 0 else { return .init() } + let result = self.extracting(first: cut) + self = self.extracting(droppingFirst: cut) + return result + } + + @_lifetime(copy self) + @_alwaysEmitIntoClient + package mutating func _trim(last maxLength: Int) -> Self { + precondition(maxLength >= 0, "Cannot have a suffix of negative length") + let cut = Swift.min(maxLength, count) + guard cut > 0 else { return .init() } + let result = self.extracting(last: cut) + self = self.extracting(droppingLast: cut) + return result + } +} + +@available(SwiftStdlib 5.0, *) +extension Span where Element: Equatable /* & ~Copyable */ { + @_alwaysEmitIntoClient + package func _elementsEqual(to other: borrowing Self) -> Bool { + return self.withUnsafeBufferPointer { a in + other.withUnsafeBufferPointer { b in + guard a.count == b.count else { return false } + guard a.baseAddress != b.baseAddress else { return true } + var i = 0 + while i < self.count { + guard a[i] == b[i] else { return false } + i &+= 1 + } + return true + } + } + } +} + +@available(SwiftStdlib 5.0, *) +extension Span where Element: Hashable /* & ~Copyable */ { + @_alwaysEmitIntoClient + package func _hashContents(into hasher: inout Hasher) { + // Note: no discriminating combine call -- caller is expected to do that + // separately when needed. + var i = 0 + while i < self.count { + hasher.combine(self[unchecked: i]) + i &+= 1 + } + + } +} + +#endif diff --git a/Sources/InternalCollectionsUtilities/UnsafeBitSet/_UnsafeBitSet.swift b/Sources/InternalCollectionsUtilities/UnsafeBitSet/_UnsafeBitSet.swift index 5fc44ca9..07d205af 100644 --- a/Sources/InternalCollectionsUtilities/UnsafeBitSet/_UnsafeBitSet.swift +++ b/Sources/InternalCollectionsUtilities/UnsafeBitSet/_UnsafeBitSet.swift @@ -331,7 +331,7 @@ extension _UnsafeBitSet: BidirectionalCollection { } while w.isEmpty { word -= 1 - precondition(word >= 0, "Can't advance below startIndex") + precondition(word >= 0, "Cannot advance below startIndex") w = _words[word] } return Index(word: word, bit: w.lastMember!) diff --git a/Sources/InternalCollectionsUtilities/UnsafeBufferPointer+Extras.swift b/Sources/InternalCollectionsUtilities/UnsafeBufferPointer+Extras.swift index 5cc4116a..ce2e1895 100644 --- a/Sources/InternalCollectionsUtilities/UnsafeBufferPointer+Extras.swift +++ b/Sources/InternalCollectionsUtilities/UnsafeBufferPointer+Extras.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021 - 2025 Apple Inc. and the Swift project authors +// Copyright (c) 2021 - 2026 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information @@ -25,9 +25,23 @@ extension UnsafeBufferPointer where Element: ~Copyable { package func _isIdentical(to other: Self) -> Bool { (self.baseAddress == other.baseAddress) && (self.count == other.count) } + + @inlinable + @inline(__always) + package static var _empty: Self { + .init(start: nil, count: 0) + } } extension UnsafeBufferPointer where Element: ~Copyable { + @_alwaysEmitIntoClient + package func _extracting(uncheckedFrom start: Int, to end: Int) -> Self { + guard let base = self.baseAddress else { + return Self(_empty: ()) + } + return Self(start: base + start, count: end - start) + } + /// Returns a buffer pointer containing the initial elements of this buffer, /// up to the specified maximum length. /// @@ -46,11 +60,34 @@ extension UnsafeBufferPointer where Element: ~Copyable { @_alwaysEmitIntoClient @inline(__always) package func _extracting(first maxLength: Int) -> Self { - precondition(maxLength >= 0, "Can't have a prefix of negative length") + precondition(maxLength >= 0, "Cannot have a prefix of negative length") let newCount = Swift.min(maxLength, count) return Self(start: baseAddress, count: newCount) } + /// Returns a buffer pointer containing all but the given number of initial + /// elements. + /// + /// If the number of elements to drop exceeds the number of elements in the + /// buffer, the result is an empty buffer. + /// + /// The returned buffer's first item is always at offset 0; unlike buffer + /// slices, extracted buffers do not share their indices with the + /// buffer from which they are extracted. + /// + /// - Parameter maxLength: The maximum number of elements to drop. + /// `maxLength` must be greater than or equal to zero. + /// - Returns: A buffer pointer with at most `maxLength` elements. + /// + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @inline(__always) + package func _extracting(droppingFirst maxLength: Int) -> Self { + precondition(maxLength >= 0, "Cannot have a prefix of negative length") + let cut = Swift.min(maxLength, count) + return Self(start: baseAddress?.advanced(by: cut), count: count &- cut) + } + /// Returns a buffer pointer containing the final elements of this buffer, /// up to the given maximum length. /// @@ -69,9 +106,53 @@ extension UnsafeBufferPointer where Element: ~Copyable { @_alwaysEmitIntoClient @inline(__always) package func _extracting(last maxLength: Int) -> Self { - precondition(maxLength >= 0, "Can't have a suffix of negative length") + precondition(maxLength >= 0, "Cannot have a suffix of negative length") let newCount = Swift.min(maxLength, count) return extracting(Range(uncheckedBounds: (count - newCount, count))) } + + /// Returns a buffer pointer containing all but the given number of trailing + /// elements. + /// + /// If the number of elements to drop exceeds the number of elements in the + /// buffer, the result is an empty buffer. + /// + /// The returned buffer's first item is always at offset 0; unlike buffer + /// slices, extracted buffers do not share their indices with the + /// buffer from which they are extracted. + /// + /// - Parameter maxLength: The maximum number of elements to drop. + /// `maxLength` must be greater than or equal to zero. + /// - Returns: A buffer pointer with at most `maxLength` elements. + /// + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @inline(__always) + package func _extracting(droppingLast maxLength: Int) -> Self { + precondition(maxLength >= 0, "Cannot have a prefix of negative length") + let newCount = count &- Swift.min(maxLength, count) + return Self(start: baseAddress, count: newCount) + } + } +extension UnsafeBufferPointer where Element: ~Copyable { + @_alwaysEmitIntoClient + package mutating func _trim(first maxLength: Int) -> Self { + precondition(maxLength >= 0, "Cannot have a prefix of negative length") + let cut = Swift.min(maxLength, count) + guard cut > 0 else { return .init(start: nil, count: 0) } + let oldStart = baseAddress.unsafelyUnwrapped + self = Self(start: oldStart + cut, count: count - cut) + return Self(start: baseAddress, count: cut) + } + + @_alwaysEmitIntoClient + package mutating func _trim(last maxLength: Int) -> Self { + precondition(maxLength >= 0, "Cannot have a suffix of negative length") + let cut = Swift.min(maxLength, count) + guard cut > 0 else { return .init(start: nil, count: 0) } + self = .init(start: baseAddress, count: count &- cut) + return Self(start: baseAddress.unsafelyUnwrapped + (count &- cut), count: cut) + } +} diff --git a/Sources/InternalCollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift b/Sources/InternalCollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift index a9eaadcb..3b0ded25 100644 --- a/Sources/InternalCollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift +++ b/Sources/InternalCollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2022 - 2025 Apple Inc. and the Swift project authors +// Copyright (c) 2022 - 2026 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information @@ -17,9 +17,34 @@ extension UnsafeMutableBufferPointer where Element: ~Copyable { package func _isIdentical(to other: Self) -> Bool { (self.baseAddress == other.baseAddress) && (self.count == other.count) } + + @inlinable + @inline(__always) + package static var _empty: Self { + .init(start: nil, count: 0) + } } extension UnsafeMutableBufferPointer where Element: ~Copyable { + @_alwaysEmitIntoClient + @inline(__always) + package func _extracting(unchecked bounds: Range) -> Self { + assert(bounds.lowerBound >= 0 && bounds.upperBound <= count, + "Index out of range") + guard let start = self.baseAddress else { + return Self(start: nil, count: 0) + } + return Self(start: start + bounds.lowerBound, count: bounds.count) + } + + @_alwaysEmitIntoClient + package func _extracting(uncheckedFrom start: Int, to end: Int) -> Self { + guard let base = self.baseAddress else { + return Self(_empty: ()) + } + return Self(start: base + start, count: end - start) + } + /// Returns a buffer pointer containing the initial elements of this buffer, /// up to the specified maximum length. /// @@ -37,12 +62,35 @@ extension UnsafeMutableBufferPointer where Element: ~Copyable { /// - Complexity: O(1) @_alwaysEmitIntoClient @inline(__always) - public func _extracting(first maxLength: Int) -> Self { - precondition(maxLength >= 0, "Can't have a prefix of negative length") + package func _extracting(first maxLength: Int) -> Self { + precondition(maxLength >= 0, "Cannot have a prefix of negative length") let newCount = Swift.min(maxLength, count) return Self(start: baseAddress, count: newCount) } + /// Returns a buffer pointer containing all but the given number of initial + /// elements. + /// + /// If the number of elements to drop exceeds the number of elements in the + /// buffer, the result is an empty buffer. + /// + /// The returned buffer's first item is always at offset 0; unlike buffer + /// slices, extracted buffers do not share their indices with the + /// buffer from which they are extracted. + /// + /// - Parameter maxLength: The maximum number of elements to drop. + /// `maxLength` must be greater than or equal to zero. + /// - Returns: A buffer pointer with at most `maxLength` elements. + /// + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @inline(__always) + package func _extracting(droppingFirst maxLength: Int) -> Self { + precondition(maxLength >= 0, "Cannot have a prefix of negative length") + let cut = Swift.min(maxLength, count) + return Self(start: baseAddress?.advanced(by: cut), count: count &- cut) + } + /// Returns a buffer pointer containing the final elements of this buffer, /// up to the given maximum length. /// @@ -60,11 +108,57 @@ extension UnsafeMutableBufferPointer where Element: ~Copyable { /// - Complexity: O(1) @_alwaysEmitIntoClient @inline(__always) - public func _extracting(last maxLength: Int) -> Self { - precondition(maxLength >= 0, "Can't have a suffix of negative length") + package func _extracting(last maxLength: Int) -> Self { + precondition(maxLength >= 0, "Cannot have a suffix of negative length") let newCount = Swift.min(maxLength, count) return extracting(Range(uncheckedBounds: (count - newCount, count))) } + + /// Returns a buffer pointer containing all but the given number of trailing + /// elements. + /// + /// If the number of elements to drop exceeds the number of elements in the + /// buffer, the result is an empty buffer. + /// + /// The returned buffer's first item is always at offset 0; unlike buffer + /// slices, extracted buffers do not share their indices with the + /// buffer from which they are extracted. + /// + /// - Parameter maxLength: The maximum number of elements to drop. + /// `maxLength` must be greater than or equal to zero. + /// - Returns: A buffer pointer with at most `maxLength` elements. + /// + /// - Complexity: O(1) + @_alwaysEmitIntoClient + @inline(__always) + package func _extracting(droppingLast maxLength: Int) -> Self { + precondition(maxLength >= 0, "Cannot have a prefix of negative length") + let newCount = count &- Swift.min(maxLength, count) + return Self(start: baseAddress, count: newCount) + } +} + +extension UnsafeMutableBufferPointer where Element: ~Copyable { + @_alwaysEmitIntoClient + @inline(__always) + package mutating func _trim(first maxLength: Int) -> Self { + precondition(maxLength >= 0, "Cannot have a prefix of negative length") + let cut = Swift.min(maxLength, count) + guard cut > 0 else { return .init(start: nil, count: 0) } + let oldStart = baseAddress.unsafelyUnwrapped + self = Self(start: oldStart + cut, count: count - cut) + return Self(start: baseAddress, count: cut) + } + + @_alwaysEmitIntoClient + @inline(__always) + package mutating func _trim(last maxLength: Int) -> Self { + precondition(maxLength >= 0, "Cannot have a suffix of negative length") + let cut = Swift.min(maxLength, count) + guard cut > 0 else { return .init(start: nil, count: 0) } + self = .init(start: baseAddress, count: count &- cut) + return Self(start: baseAddress.unsafelyUnwrapped + (count &- cut), count: cut) + } } extension UnsafeMutableBufferPointer where Element: ~Copyable { diff --git a/Sources/OrderedCollections/HashTable/_HashTable+Constants.swift b/Sources/OrderedCollections/HashTable/_HashTable+Constants.swift index 49fcf935..6086eacb 100644 --- a/Sources/OrderedCollections/HashTable/_HashTable+Constants.swift +++ b/Sources/OrderedCollections/HashTable/_HashTable+Constants.swift @@ -48,7 +48,7 @@ extension _HashTable { @inline(__always) internal static var minimumLoadFactor: Double { 1 / 4 } - /// The maximum number of items that can be held in a hash table of the given scale. + /// The minimum number of items that can be held in a hash table of the given scale. @usableFromInline @_effects(readnone) internal static func minimumCapacity(forScale scale: Int) -> Int { diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial RangeReplaceableCollection.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial RangeReplaceableCollection.swift index 603319bf..cbca5f45 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial RangeReplaceableCollection.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial RangeReplaceableCollection.swift @@ -121,8 +121,8 @@ extension OrderedDictionary { /// high-quality hashing. @inlinable public mutating func removeLast(_ n: Int) { - precondition(n >= 0, "Can't remove a negative number of elements") - precondition(n <= count, "Can't remove more elements than there are in the collection") + precondition(n >= 0, "Cannot remove a negative number of items") + precondition(n <= count, "Cannot remove more elements than there are in the collection") _keys.removeLast(n) _values.removeLast(n) } @@ -152,8 +152,8 @@ extension OrderedDictionary { /// - Complexity: O(`count`). @inlinable public mutating func removeFirst(_ n: Int) { - precondition(n >= 0, "Can't remove a negative number of elements") - precondition(n <= count, "Can't remove more elements than there are in the collection") + precondition(n >= 0, "Cannot remove a negative number of elements") + precondition(n <= count, "Cannot remove more elements than there are in the collection") _keys.removeFirst(n) _values.removeFirst(n) } diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial RangeReplaceableCollection.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial RangeReplaceableCollection.swift index bb8900f1..ea560e88 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial RangeReplaceableCollection.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial RangeReplaceableCollection.swift @@ -157,7 +157,7 @@ extension OrderedSet { /// high-quality hashing. @inlinable public mutating func removeLast(_ n: Int) { - precondition(n >= 0, "Can't remove a negative number of elements") + precondition(n >= 0, "Cannot remove a negative number of items") precondition(n <= count, "Can't remove more elements than there are in the collection") removeSubrange(count - n ..< count) } @@ -171,7 +171,7 @@ extension OrderedSet { @inlinable @discardableResult public mutating func removeFirst() -> Element { - precondition(!isEmpty, "Cannot remove first element of an empty collection") + precondition(!isEmpty, "Cannot remove first item of an empty collection") return remove(at: startIndex) } @@ -187,8 +187,8 @@ extension OrderedSet { /// - Complexity: O(`count`). @inlinable public mutating func removeFirst(_ n: Int) { - precondition(n >= 0, "Can't remove a negative number of elements") - precondition(n <= count, "Can't remove more elements than there are in the collection") + precondition(n >= 0, "Cannot remove a negative number of items") + precondition(n <= count, "Cannot remove more elements than there are in the collection") removeSubrange(0 ..< n) } diff --git a/Sources/RopeModule/BigString/Basics/BigString+Contents.swift b/Sources/RopeModule/BigString/Basics/BigString+Contents.swift index 3a998789..2553f5ab 100644 --- a/Sources/RopeModule/BigString/Basics/BigString+Contents.swift +++ b/Sources/RopeModule/BigString/Basics/BigString+Contents.swift @@ -267,7 +267,7 @@ extension BigString { } func _utf8Index(after i: Index) -> Index { - precondition(i < endIndex, "Can't advance above end index") + precondition(i < endIndex, "Cannot advance above end index") let i = resolve(i, preferEnd: false) let ri = i._rope! var ci = i._chunkIndex @@ -299,7 +299,7 @@ extension BigString { } func _utf8Index(before i: Index) -> Index { - precondition(i > startIndex, "Can't advance below start index") + precondition(i > startIndex, "Cannot advance below start index") let i = resolve(i, preferEnd: true) var ri = i._rope! let ci = i._chunkIndex diff --git a/Sources/RopeModule/BigString/Conformances/BigString+RangeReplaceableCollection.swift b/Sources/RopeModule/BigString/Conformances/BigString+RangeReplaceableCollection.swift index ed02eeac..2e6f16c9 100644 --- a/Sources/RopeModule/BigString/Conformances/BigString+RangeReplaceableCollection.swift +++ b/Sources/RopeModule/BigString/Conformances/BigString+RangeReplaceableCollection.swift @@ -105,7 +105,7 @@ extension BigString: RangeReplaceableCollection { } public init(repeating value: Self, count: Int) { - precondition(count >= 0, "Negative count") + precondition(count >= 0, "Cannot add a negative number of items") guard count > 0 else { self.init() return diff --git a/Sources/RopeModule/BigString/Views/BigSubstring+UTF16View.swift b/Sources/RopeModule/BigString/Views/BigSubstring+UTF16View.swift index c1750bc5..231bdb12 100644 --- a/Sources/RopeModule/BigString/Views/BigSubstring+UTF16View.swift +++ b/Sources/RopeModule/BigString/Views/BigSubstring+UTF16View.swift @@ -145,13 +145,13 @@ extension BigSubstring.UTF16View: BidirectionalCollection { @inline(__always) public func index(after i: Index) -> Index { - precondition(i < endIndex, "Can't advance above end index") + precondition(i < endIndex, "Cannot advance above end index") return _base._utf16Index(after: i) } @inline(__always) public func index(before i: Index) -> Index { - precondition(i > startIndex, "Can't advance below start index") + precondition(i > startIndex, "Cannot advance below start index") return _base._utf16Index(before: i) } diff --git a/Sources/RopeModule/BigString/Views/BigSubstring+UTF8View.swift b/Sources/RopeModule/BigString/Views/BigSubstring+UTF8View.swift index 996d78b0..8a4c1e2c 100644 --- a/Sources/RopeModule/BigString/Views/BigSubstring+UTF8View.swift +++ b/Sources/RopeModule/BigString/Views/BigSubstring+UTF8View.swift @@ -117,13 +117,13 @@ extension BigSubstring.UTF8View: BidirectionalCollection { @inline(__always) public func index(after i: Index) -> Index { - precondition(i < endIndex, "Can't advance above end index") + precondition(i < endIndex, "Cannot advance above end index") return _base._utf8Index(after: i) } @inline(__always) public func index(before i: Index) -> Index { - precondition(i > startIndex, "Can't advance below start index") + precondition(i > startIndex, "Cannot advance below start index") return _base._utf8Index(before: i) } diff --git a/Sources/RopeModule/BigString/Views/BigSubstring+UnicodeScalarView.swift b/Sources/RopeModule/BigString/Views/BigSubstring+UnicodeScalarView.swift index 44238691..7e3057a5 100644 --- a/Sources/RopeModule/BigString/Views/BigSubstring+UnicodeScalarView.swift +++ b/Sources/RopeModule/BigString/Views/BigSubstring+UnicodeScalarView.swift @@ -147,13 +147,13 @@ extension BigSubstring.UnicodeScalarView: BidirectionalCollection { @inline(__always) public func index(after i: Index) -> Index { - precondition(i < endIndex, "Can't advance above end index") + precondition(i < endIndex, "Cannot advance above end index") return _base._unicodeScalarIndex(after: i) } @inline(__always) public func index(before i: Index) -> Index { - precondition(i > startIndex, "Can't advance below start index") + precondition(i > startIndex, "Cannot advance below start index") return _base._unicodeScalarIndex(before: i) } diff --git a/Sources/RopeModule/BigString/Views/BigSubstring.swift b/Sources/RopeModule/BigString/Views/BigSubstring.swift index 3f05920d..a69fe4ee 100644 --- a/Sources/RopeModule/BigString/Views/BigSubstring.swift +++ b/Sources/RopeModule/BigString/Views/BigSubstring.swift @@ -174,13 +174,13 @@ extension BigSubstring: BidirectionalCollection { @inline(__always) public func index(after i: Index) -> Index { - precondition(i < endIndex, "Can't advance above end index") + precondition(i < endIndex, "Cannot advance above end index") return _base.index(after: i) } @inline(__always) public func index(before i: Index) -> Index { - precondition(i > startIndex, "Can't advance below start index") + precondition(i > startIndex, "Cannot advance below start index") return _base.index(before: i) } diff --git a/Sources/RopeModule/Rope/Conformances/Rope+Collection.swift b/Sources/RopeModule/Rope/Conformances/Rope+Collection.swift index 2414baed..ea507bbe 100644 --- a/Sources/RopeModule/Rope/Conformances/Rope+Collection.swift +++ b/Sources/RopeModule/Rope/Conformances/Rope+Collection.swift @@ -92,7 +92,7 @@ extension Rope: BidirectionalCollection { @inlinable public func formIndex(after i: inout Index) { validate(i) - precondition(i < endIndex, "Can't move after endIndex") + precondition(i < endIndex, "Cannot advance above endIndex") if let leaf = i._leaf { let done = leaf.read { let slot = i._path[$0.height] &+ 1 @@ -110,7 +110,7 @@ extension Rope: BidirectionalCollection { @inlinable public func formIndex(before i: inout Index) { validate(i) - precondition(i > startIndex, "Can't move before startIndex") + precondition(i > startIndex, "Cannot advance below startIndex") if let leaf = i._leaf { let done = leaf.read { let slot = i._path[$0.height] diff --git a/Tests/BasicContainersTests/ArrayLayout.swift b/Tests/BasicContainersTests/ArrayLayout.swift index 6ae6e1dd..fc35ad2d 100644 --- a/Tests/BasicContainersTests/ArrayLayout.swift +++ b/Tests/BasicContainersTests/ArrayLayout.swift @@ -26,6 +26,10 @@ struct ArrayLayout { self.capacity = capacity self.count = count } + + var isFull: Bool { count == capacity } + var isEmpty: Bool { count == 0 } + var freeCapacity: Int { capacity - count } } func withSomeArrayLayouts( @@ -49,7 +53,7 @@ func withSomeArrayLayouts( counts.insert(2) counts.insert(capacity - 2) } - for count in counts { + for count in counts.sorted() { let layout = ArrayLayout(capacity: capacity, count: count) let entry = context.push("\(label): \(layout)", file: file, line: line) @@ -90,7 +94,7 @@ extension LifetimeTracker { ) -> RigidArray> { RigidArray(layout: layout, using: { self.instance(for: generator($0)) }) } - + func uniqueArray( layout: ArrayLayout, using generator: (Int) -> Element = { $0 } @@ -100,5 +104,36 @@ extension LifetimeTracker { } return UniqueArray(consuming: contents) } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + func withInputSpan( + layout: ArrayLayout, + using generator: (Int) -> Element, + _ body: (inout InputSpan>) -> Void + ) { + let buffer = UnsafeMutableBufferPointer> + .allocate(capacity: layout.capacity) + for i in 0 ..< layout.count { + buffer.initializeElement( + at: layout.capacity - layout.count + i, + to: self.instance(for: generator(i))) + } + var span = InputSpan(buffer: buffer, initializedCount: layout.count) + body(&span) + _ = consume span + buffer.deallocate() + } +#endif + + func withOutputSpan( + layout: ArrayLayout, + using generator: (Int) -> Element, + _ body: (inout OutputSpan>) -> Void + ) { + var contents = RigidArray(layout: layout) { + self.instance(for: generator($0)) + } + contents.edit(body) + } } #endif diff --git a/Tests/BasicContainersTests/RigidArrayTests.swift b/Tests/BasicContainersTests/RigidArrayTests.swift index 622c2f14..46a40fbe 100644 --- a/Tests/BasicContainersTests/RigidArrayTests.swift +++ b/Tests/BasicContainersTests/RigidArrayTests.swift @@ -22,7 +22,7 @@ import BasicContainers #if !COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW /// Check if `left` and `right` contain equal elements in the same order. @available(SwiftStdlib 5.0, *) -public func expectContainerContents< +internal func expectIterableContents< Element: Equatable, C2: Collection, >( @@ -30,10 +30,10 @@ public func expectContainerContents< equalTo right: C2, _ message: @autoclosure () -> String = "", trapping: Bool = false, - file: StaticString = #file, + file: StaticString = #filePath, line: UInt = #line ) { - expectContainerContents( + expectIterableContents( left.span, equalTo: right, message(), trapping: trapping, file: file, line: line) @@ -41,22 +41,24 @@ public func expectContainerContents< /// Check if `left` and `right` contain equal elements in the same order. @available(SwiftStdlib 5.0, *) -public func expectContainerContents< +internal func expectIterableContents< E1: ~Copyable, C2: Collection, >( _ left: borrowing RigidArray, equivalentTo right: C2, by areEquivalent: (borrowing E1, C2.Element) -> Bool, + printer: (borrowing E1) -> String, _ message: @autoclosure () -> String = "", trapping: Bool = false, - file: StaticString = #file, + file: StaticString = #filePath, line: UInt = #line ) { - expectContainerContents( + expectIterableContents( left.span, equivalentTo: right, by: areEquivalent, + printer: printer, message(), trapping: trapping, file: file, line: line) } #endif @@ -69,9 +71,9 @@ class RigidArrayTests: CollectionTestCase { let items = tracker.rigidArray(layout: layout) let expected = (0 ..< layout.count).map { tracker.instance(for: $0) } expectEqual(tracker.instances, 2 * layout.count) - expectContainerContents(items, equalTo: expected) + expectIterableContents(items, equalTo: expected) #if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW - checkContainer(items, expectedContents: expected) + checkIterable(items, expectedContents: expected) #endif } } @@ -115,10 +117,11 @@ class RigidArrayTests: CollectionTestCase { expectEqual(a.freeCapacity, layout.capacity - layout.count) expectEqual(a.isEmpty, layout.count == 0) expectEqual(a.isFull, layout.count == layout.capacity) - expectContainerContents( + expectIterableContents( a, equivalentTo: 0 ..< layout.count, - by: { $0.payload == $1 }) + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) } } } @@ -160,6 +163,7 @@ class RigidArrayTests: CollectionTestCase { } #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +#if false // FIXME: Update func test_init_copying_Container() { withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in withEvery("spanCounts", in: [ @@ -185,6 +189,30 @@ class RigidArrayTests: CollectionTestCase { } } #endif +#endif + + func test_init_copying_Span() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + let a = tracker.rigidArray(layout: layout) + let b = RigidArray(capacity: layout.capacity, copying: a.span) + expectEqual(tracker.instances, layout.count) + expectEqual(b.capacity, layout.capacity) + expectEqual(b.count, layout.count) + expectEqual(b.freeCapacity, layout.capacity - layout.count) + expectEqual(b.isEmpty, layout.count == 0) + expectEqual(b.isFull, layout.count == layout.capacity) + for i in 0 ..< layout.count { + expectEqual(b[i].payload, i) + } + expectIterableContents( + b, + equivalentTo: 0 ..< layout.count, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) + } + } + } func test_span() { withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in @@ -286,7 +314,11 @@ class RigidArrayTests: CollectionTestCase { a.swapAt(i, layout.count - 1 - i) } let expected = (0 ..< layout.count).reversed() - expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 }) + expectIterableContents( + a, + equivalentTo: expected, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) expectEqual(tracker.instances, layout.count) } } @@ -349,7 +381,65 @@ class RigidArrayTests: CollectionTestCase { } } #endif - + + func test_equatable() { + withSomeArrayLayouts("layoutA", ofCapacities: [0, 10, 100]) { layoutA in + withSomeArrayLayouts("layoutB", ofCapacities: [0, 10, 100]) { layoutB in + withLifetimeTracking { tracker in + let a = tracker.rigidArray(layout: layoutA) + let b = tracker.rigidArray(layout: layoutB) + expectTrue(a.isTriviallyIdentical(to: a)) + expectEqual( + a.isTriviallyIdentical(to: b), + a.capacity == 0 && b.capacity == 0) + expectEqual(a == b, layoutA.count == layoutB.count) + } + } + } + } + + func test_hashable() { + withSomeArrayLayouts("layoutA", ofCapacities: [0, 10, 100]) { layoutA in + withSomeArrayLayouts("layoutB", ofCapacities: [0, 10, 100]) { layoutB in + withLifetimeTracking { tracker in + let a = tracker.rigidArray(layout: layoutA) + let b = tracker.rigidArray(layout: layoutB) + // FIXME: Use checkHashable when possible + var goodHash = false + for i in 0 ..< 10 { + var ha = Hasher() + ha.combine(i) + a.hash(into: &ha) + let hashValueA = ha.finalize() + + var hb = Hasher() + hb.combine(i) + b.hash(into: &hb) + let hashValueB = hb.finalize() + + if layoutA.count == layoutB.count { + expectEqual(hashValueA, hashValueB) + goodHash = true + } else if hashValueA != hashValueB { + goodHash = true + } + } + expectTrue(goodHash, "Hashing does not differentiate between inequal containers") + } + } + } + } + + func test_descriptions() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + let a = tracker.rigidArray(layout: layout) + expectEqual(a.description, "<\(layout.count) items>") + expectEqual(a.debugDescription, "<\(layout.count) items>") + } + } + } + func test_edit() { withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in withLifetimeTracking { tracker in @@ -390,10 +480,11 @@ class RigidArrayTests: CollectionTestCase { errorHandler: { error in expectTrue(error is TestError) } - expectContainerContents( + expectIterableContents( a, equivalentTo: (0 ..< layout.count).map { -$0 }, - by: { $0.payload == $1 }) + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) expectEqual(tracker.instances, layout.count) } } @@ -415,8 +506,11 @@ class RigidArrayTests: CollectionTestCase { expectEqual(a.count, layout.count) expectEqual(a.capacity, newCapacity) expectEqual(tracker.instances, layout.count) - expectContainerContents( - a, equivalentTo: 0 ..< layout.count, by: { $0.payload == $1 }) + expectIterableContents( + a, + equivalentTo: 0 ..< layout.count, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) } } } @@ -439,8 +533,11 @@ class RigidArrayTests: CollectionTestCase { expectEqual(a.count, layout.count) expectEqual(a.capacity, Swift.max(layout.capacity, newCapacity)) expectEqual(tracker.instances, layout.count) - expectContainerContents( - a, equivalentTo: 0 ..< layout.count, by: { $0.payload == $1 }) + expectIterableContents( + a, + equivalentTo: 0 ..< layout.count, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) } } } @@ -450,12 +547,20 @@ class RigidArrayTests: CollectionTestCase { withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in withLifetimeTracking { tracker in let a = tracker.rigidArray(layout: layout) - let b = a.copy() + let b = a.clone() expectEqual(b.count, layout.count) expectEqual(b.capacity, layout.count) expectEqual(tracker.instances, layout.count) - expectContainerContents(a, equivalentTo: 0 ..< layout.count, by: { $0.payload == $1 }) - expectContainerContents(b, equivalentTo: 0 ..< layout.count, by: { $0.payload == $1 }) + expectIterableContents( + a, + equivalentTo: 0 ..< layout.count, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) + expectIterableContents( + b, + equivalentTo: 0 ..< layout.count, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) } } } @@ -468,12 +573,20 @@ class RigidArrayTests: CollectionTestCase { ) { newCapacity in withLifetimeTracking { tracker in let a = tracker.rigidArray(layout: layout) - let b = a.copy(capacity: newCapacity) + let b = a.clone(capacity: newCapacity) expectEqual(b.count, layout.count) expectEqual(b.capacity, newCapacity) expectEqual(tracker.instances, layout.count) - expectContainerContents(a, equivalentTo: 0 ..< layout.count, by: { $0.payload == $1 }) - expectContainerContents(b, equivalentTo: 0 ..< layout.count, by: { $0.payload == $1 }) + expectIterableContents( + a, + equivalentTo: 0 ..< layout.count, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) + expectIterableContents( + b, + equivalentTo: 0 ..< layout.count, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) } } } @@ -517,8 +630,11 @@ class RigidArrayTests: CollectionTestCase { expectEqual(tracker.instances, layout.count) a.removeLast(k) expectEqual(tracker.instances, layout.count - k) - expectContainerContents( - a, equivalentTo: expected, by: { $0.payload == $1 }) + expectIterableContents( + a, + equivalentTo: expected, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) } } } @@ -534,7 +650,11 @@ class RigidArrayTests: CollectionTestCase { var a = tracker.rigidArray(layout: layout) let old = a.remove(at: i) expectEqual(old.payload, i) - expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 }) + expectIterableContents( + a, + equivalentTo: expected, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) } } } @@ -549,7 +669,11 @@ class RigidArrayTests: CollectionTestCase { var a = tracker.rigidArray(layout: layout) a.removeSubrange(range) - expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 }) + expectIterableContents( + a, + equivalentTo: expected, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) } } } @@ -564,7 +688,7 @@ class RigidArrayTests: CollectionTestCase { var a = tracker.rigidArray(layout: layout) a.removeAll(where: { $0.payload.isMultiple(of: 2) }) - expectContainerContents( + expectIterableContents( a, equivalentTo: expected, by: { $0.payload == $1 }) } } @@ -581,8 +705,11 @@ class RigidArrayTests: CollectionTestCase { let item = a.popLast() expectEquivalent(item, expectedItem, by: { $0?.payload == $1 }) - expectContainerContents( - a, equivalentTo: expected, by: { $0.payload == $1 }) + expectIterableContents( + a, + equivalentTo: expected, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) } } } @@ -594,14 +721,160 @@ class RigidArrayTests: CollectionTestCase { for i in layout.count ..< layout.capacity { a.append(tracker.instance(for: i)) expectEqual(a.count, i + 1) - expectContainerContents(a, equivalentTo: 0 ..< i + 1, by: { $0.payload == $1 }) + expectIterableContents( + a, + equivalentTo: 0 ..< i + 1, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) } expectTrue(a.isFull) expectEqual(tracker.instances, layout.capacity) } } } - + + func test_pushLast() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + var a = tracker.rigidArray(layout: layout) + for i in layout.count ..< layout.capacity { + expectNil(a.pushLast(tracker.instance(for: i))) + expectEqual(a.count, i + 1) + expectIterableContents( + a, + equivalentTo: 0 ..< i + 1, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) + } + expectTrue(a.isFull) + let final = a.pushLast(tracker.instance(for: layout.capacity)) + expectNotNil(final) { value in + expectEqual(value.payload, layout.capacity) + } + } + } + } + + func test_append_addingCount_full() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withEvery("c", in: 0 ..< layout.freeCapacity) { c in + withLifetimeTracking { tracker in + var a = tracker.rigidArray(layout: layout) + a.append(addingCount: c) { target in + expectEqual(target.freeCapacity, c) + for i in 0 ..< c { + target.append(tracker.instance(for: layout.count + i)) + } + } + expectIterableContents( + a, + equivalentTo: 0 ..< layout.count + c, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) + } + } + } + } + + func test_append_addingCount_partial() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + guard layout.freeCapacity > 0 else { return } + withEvery("c", in: 1 ..< layout.freeCapacity) { c in + withEvery("n", in: [0, 1, c / 2, c - 1] as Set) { n in + withLifetimeTracking { tracker in + var a = tracker.rigidArray(layout: layout) + a.append(addingCount: c) { target in + expectEqual(target.freeCapacity, c) + for i in layout.count ..< layout.count + n { + target.append(tracker.instance(for: i)) + } + } + expectIterableContents( + a, + equivalentTo: 0 ..< layout.count + n, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) + } + } + } + } + } + + func test_append_moving_UnsafeMutableBufferPointer() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withEvery("c", in: 0 ..< layout.freeCapacity) { c in + withLifetimeTracking { tracker in + let additions = UnsafeMutableBufferPointer> + .allocate(capacity: c) + for i in 0 ..< c { + additions.initializeElement( + at: i, + to: tracker.instance(for: layout.count + i)) + } + + var a = tracker.rigidArray(layout: layout) + a.append(moving: additions) + + additions.deallocate() + + expectIterableContents( + a, + equivalentTo: 0 ..< layout.count + c, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) + } + } + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + func test_append_moving_InputSpan() { + withSomeArrayLayouts("layout", ofCapacities: [0, 1, 5, 10]) { layout in + withSomeArrayLayouts("spanLayout", ofCapacities: 0 ..< layout.freeCapacity) { spanLayout in + withLifetimeTracking { tracker in + var a = tracker.rigidArray(layout: layout) + + tracker.withInputSpan( + layout: spanLayout, + using: { layout.count + $0 } + ) { span in + a.append(moving: &span) + } + + expectIterableContents( + a, + equivalentTo: 0 ..< layout.count + spanLayout.count, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) + } + } + } + } +#endif + + func test_append_moving_OutputSpan() { + withSomeArrayLayouts("layout", ofCapacities: [0, 1, 5, 10]) { layout in + withSomeArrayLayouts("spanLayout", ofCapacities: 0 ..< layout.freeCapacity) { spanLayout in + withLifetimeTracking { tracker in + var a = tracker.rigidArray(layout: layout) + + tracker.withOutputSpan( + layout: spanLayout, + using: { layout.count + $0 } + ) { span in + a.append(moving: &span) + } + + expectIterableContents( + a, + equivalentTo: 0 ..< layout.count + spanLayout.count, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) + } + } + } + } + func test_append_copying_MinimalSequence() { withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in withEvery("isContiguous", in: [false, true]) { isContiguous in @@ -629,13 +902,18 @@ class RigidArrayTests: CollectionTestCase { using: { layout.count + $0 }) a.append(copying: b.span) expectTrue(a.isFull) - expectContainerContents(a, equivalentTo: 0 ..< layout.capacity, by: { $0.payload == $1 }) + expectIterableContents( + a, + equivalentTo: 0 ..< layout.capacity, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) expectEqual(tracker.instances, layout.capacity) } } } #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +#if false // FIXME: Update func test_append_copying_Container() { withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in withEvery("spanCount", in: 1 ... Swift.max(1, layout.capacity - layout.count)) { spanCount in @@ -648,12 +926,17 @@ class RigidArrayTests: CollectionTestCase { spanCounts: [spanCount]) a.append(copying: b) expectTrue(a.isFull) - expectContainerContents(a, equivalentTo: 0 ..< layout.capacity, by: { $0.payload == $1 }) + expectIterableContents( + a, + equivalentTo: 0 ..< layout.capacity, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) expectEqual(tracker.instances, layout.capacity) } } } } +#endif #endif func test_insert_at() { @@ -667,13 +950,176 @@ class RigidArrayTests: CollectionTestCase { var a = tracker.rigidArray(layout: layout) a.insert(tracker.instance(for: -1), at: i) - expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 }) + expectIterableContents( + a, + equivalentTo: expected, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) expectEqual(tracker.instances, layout.count + 1) } } } } - + + func test_insert_addingCount_full() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 20]) { layout in + withEvery("i", in: 0 ..< layout.count) { i in + withEvery("c", in: 0 ..< layout.freeCapacity) { c in + withLifetimeTracking { tracker in + var a = tracker.rigidArray(layout: layout) + + a.insert(addingCount: c, at: i) { target in + expectEqual(target.freeCapacity, c) + for i in 0 ..< c { + target.append(tracker.instance(for: layout.count + i)) + } + } + + var expected = Array(0 ..< layout.count) + expected.insert( + contentsOf: layout.count ..< layout.count + c, + at: i) + + expectIterableContents( + a, + equivalentTo: expected, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) + } + } + } + } + } + + func test_insert_addingCount_partial() { + withSomeArrayLayouts("layout", ofCapacities: [0, 5, 10]) { layout in + guard !layout.isFull else { return } + withEvery("i", in: 0 ... layout.count) { i in + withEvery("c", in: 1 ..< layout.freeCapacity) { c in + withEvery("n", in: [0, 1, c / 2, c - 1] as Set) { n in + withLifetimeTracking { tracker in + var a = tracker.rigidArray(layout: layout) + + a.insert(addingCount: c, at: i) { target in + expectTrue(target.isEmpty) + expectEqual(target.freeCapacity, c) + for i in 0 ..< n { + target.append(tracker.instance(for: layout.count + i)) + } + } + expectEqual(a.count, layout.count + n) + + var expected = Array(0 ..< layout.count) + expected.insert( + contentsOf: layout.count ..< layout.count + n, + at: i) + + expectIterableContents( + a, + equivalentTo: expected, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) + } + } + } + } + } + } + + func test_insert_moving_UnsafeMutableBufferPointer() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withEvery("i", in: 0 ... layout.count) { i in + withEvery("c", in: 0 ..< layout.freeCapacity) { c in + withLifetimeTracking { tracker in + let additions = UnsafeMutableBufferPointer> + .allocate(capacity: c) + for i in 0 ..< c { + additions.initializeElement( + at: i, + to: tracker.instance(for: layout.count + i)) + } + + var a = tracker.rigidArray(layout: layout) + a.insert(moving: additions, at: i) + + additions.deallocate() + + var expected = Array(0 ..< layout.count) + expected.insert(contentsOf: layout.count ..< layout.count + c, at: i) + + expectIterableContents( + a, + equivalentTo: expected, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) + } + } + } + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + func test_insert_moving_InputSpan() { + withSomeArrayLayouts("layout", ofCapacities: [0, 1, 5, 10]) { layout in + withSomeArrayLayouts("spanLayout", ofCapacities: 0 ..< layout.freeCapacity) { spanLayout in + withEvery("i", in: 0 ... layout.count) { i in + withLifetimeTracking { tracker in + var a = tracker.rigidArray(layout: layout) + + tracker.withInputSpan( + layout: spanLayout, + using: { layout.count + $0 } + ) { span in + a.insert(moving: &span, at: i) + } + + var expected = Array(0 ..< layout.count) + expected.insert( + contentsOf: layout.count ..< layout.count + spanLayout.count, + at: i) + + expectIterableContents( + a, + equivalentTo: expected, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) + } + } + } + } + } +#endif + + func test_insert_moving_OutputSpan() { + withSomeArrayLayouts("layout", ofCapacities: [0, 1, 5, 10]) { layout in + withSomeArrayLayouts("spanLayout", ofCapacities: 0 ..< layout.freeCapacity) { spanLayout in + withEvery("i", in: 0 ... layout.count) { i in + withLifetimeTracking { tracker in + var a = tracker.rigidArray(layout: layout) + + tracker.withOutputSpan( + layout: spanLayout, + using: { layout.count + $0 } + ) { span in + a.insert(moving: &span, at: i) + } + + var expected = Array(0 ..< layout.count) + expected.insert( + contentsOf: layout.count ..< layout.count + spanLayout.count, + at: i) + + expectIterableContents( + a, + equivalentTo: expected, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) + } + } + } + } + } + func test_insert_copying_Collection() { withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in withEvery("i", in: 0 ... layout.count) { i in @@ -690,7 +1136,11 @@ class RigidArrayTests: CollectionTestCase { var a = tracker.rigidArray(layout: layout) a.insert(copying: trackedAddition, at: i) - expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 }) + expectIterableContents( + a, + equivalentTo: expected, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) expectEqual(tracker.instances, layout.capacity) } } @@ -715,35 +1165,39 @@ class RigidArrayTests: CollectionTestCase { } a.insert(copying: rigidAddition.span, at: i) - expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 }) + expectIterableContents( + a, + equivalentTo: expected, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) expectEqual(tracker.instances, layout.capacity) } } } } - + #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW func test_insert_copying_Container() { - withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withSomeArrayLayouts("layout", ofCapacities: [0, 5, 10]) { layout in withEvery("i", in: 0 ... layout.count) { i in withEvery("spanCount", in: 1 ... Swift.max(1, layout.capacity - layout.count)) { spanCount in withLifetimeTracking { tracker in - + var expected = Array(0 ..< layout.count) let addition = Array(layout.count ..< layout.capacity) expected.insert(contentsOf: addition, at: i) - + var a = tracker.rigidArray(layout: layout) let rigidAddition = StaccatoContainer( - contents: RigidArray(capacity: addition.count) { - for item in addition { - $0.append(tracker.instance(for: item)) - } - }, - spanCounts: [Swift.max(spanCount, 1)]) + contents: tracker.instances(for: addition), + spanCounts: [spanCount]) a.insert(copying: rigidAddition, at: i) - - expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 }) + + expectIterableContents( + a, + equivalentTo: expected, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) expectEqual(tracker.instances, layout.capacity) } } @@ -752,7 +1206,72 @@ class RigidArrayTests: CollectionTestCase { } #endif - func test_replaceSubrange_Collection() { + func test_replace_addingCount_full() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 20]) { layout in + withEveryRange("subrange", in: 0 ..< layout.count) { subrange in + withEvery("c", in: 0 ..< subrange.count + layout.freeCapacity) { c in + withLifetimeTracking { tracker in + var a = tracker.rigidArray(layout: layout) + + a.replace(removing: subrange, addingCount: c) { target in + expectEqual(target.freeCapacity, c) + for i in 0 ..< c { + target.append(tracker.instance(for: layout.count + i)) + } + } + + var expected = Array(0 ..< layout.count) + expected.replaceSubrange( + subrange, + with: layout.count ..< layout.count + c) + + expectIterableContents( + a, + equivalentTo: expected, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) + } + } + } + } + } + + func test_replace_addingCount_partial() { + withSomeArrayLayouts("layout", ofCapacities: [0, 5, 10]) { layout in + guard !layout.isFull else { return } + withEveryRange("subrange", in: 0 ..< layout.count) { subrange in + withEvery("c", in: 1 ..< layout.freeCapacity) { c in + withEvery("n", in: [0, 1, c / 2, c - 1] as Set) { n in + withLifetimeTracking { tracker in + var a = tracker.rigidArray(layout: layout) + + a.replace(removing: subrange, addingCount: c) { target in + expectTrue(target.isEmpty) + expectEqual(target.freeCapacity, c) + for i in 0 ..< n { + target.append(tracker.instance(for: layout.count + i)) + } + } + expectEqual(a.count, layout.count - subrange.count + n) + + var expected = Array(0 ..< layout.count) + expected.replaceSubrange( + subrange, + with: layout.count ..< layout.count + n) + + expectIterableContents( + a, + equivalentTo: expected, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) + } + } + } + } + } + } + + func test_replace_Collection() { withSomeArrayLayouts("layout", ofCapacities: [0, 5, 10]) { layout in withEveryRange("range", in: 0 ..< layout.count) { range in withEvery("isContiguous", in: [false, true]) { isContiguous in @@ -766,9 +1285,13 @@ class RigidArrayTests: CollectionTestCase { addition.map { tracker.instance(for: $0) }, isContiguous: isContiguous) var a = tracker.rigidArray(layout: layout) - a.replaceSubrange(range, copying: trackedAddition) + a.replace(removing: range, copying: trackedAddition) - expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 }) + expectIterableContents( + a, + equivalentTo: expected, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) expectEqual(tracker.instances, layout.count - range.count + c) } } @@ -776,7 +1299,7 @@ class RigidArrayTests: CollectionTestCase { } } } - func test_replaceSubrange_Span() { + func test_replace_Span() { withSomeArrayLayouts("layout", ofCapacities: [0, 5, 10]) { layout in withEveryRange("range", in: 0 ..< layout.count) { range in withEvery("c", in: 0 ..< layout.capacity - layout.count + range.count) { c in @@ -787,9 +1310,13 @@ class RigidArrayTests: CollectionTestCase { var a = tracker.rigidArray(layout: layout) let trackedAddition = RigidArray(copying: addition.map { tracker.instance(for: $0) }) - a.replaceSubrange(range, copying: trackedAddition.span) + a.replace(removing: range, copying: trackedAddition.span) - expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 }) + expectIterableContents( + a, + equivalentTo: expected, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) expectEqual(tracker.instances, layout.count - range.count + c) } } @@ -798,7 +1325,7 @@ class RigidArrayTests: CollectionTestCase { } #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW - func test_replaceSubrange_Container() { + func test_replace_Container() { withSomeArrayLayouts("layout", ofCapacities: [0, 5, 10]) { layout in withEveryRange("range", in: 0 ..< layout.count) { range in withEvery("c", in: 0 ..< layout.capacity - layout.count + range.count) { c in @@ -812,9 +1339,13 @@ class RigidArrayTests: CollectionTestCase { let trackedAddition = StaccatoContainer( contents: RigidArray(copying: addition.map { tracker.instance(for: $0) }), spanCounts: [spanCount]) - a.replaceSubrange(range, copying: trackedAddition) + a.replace(removing: range, copying: trackedAddition) - expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 }) + expectIterableContents( + a, + equivalentTo: expected, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) expectEqual(tracker.instances, layout.count - range.count + c) } } diff --git a/Tests/BasicContainersTests/UniqueArrayTests.swift b/Tests/BasicContainersTests/UniqueArrayTests.swift index 3eaf7488..65e0752d 100644 --- a/Tests/BasicContainersTests/UniqueArrayTests.swift +++ b/Tests/BasicContainersTests/UniqueArrayTests.swift @@ -22,7 +22,7 @@ import BasicContainers #if !COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW /// Check if `left` and `right` contain equal elements in the same order. @available(SwiftStdlib 5.0, *) -public func expectContainerContents< +public func expectIterableContents< Element: Equatable, C2: Collection, >( @@ -30,10 +30,10 @@ public func expectContainerContents< equalTo right: C2, _ message: @autoclosure () -> String = "", trapping: Bool = false, - file: StaticString = #file, + file: StaticString = #filePath, line: UInt = #line ) { - expectContainerContents( + expectIterableContents( left.span, equalTo: right, message(), trapping: trapping, file: file, line: line) @@ -41,23 +41,28 @@ public func expectContainerContents< /// Check if `left` and `right` contain equal elements in the same order. @available(SwiftStdlib 5.0, *) -public func expectContainerContents< +public func expectIterableContents< E1: ~Copyable, C2: Collection, >( _ left: borrowing UniqueArray, equivalentTo right: C2, by areEquivalent: (borrowing E1, C2.Element) -> Bool, + printer: (borrowing E1) -> String, _ message: @autoclosure () -> String = "", trapping: Bool = false, - file: StaticString = #file, + file: StaticString = #filePath, line: UInt = #line ) { - expectContainerContents( + expectIterableContents( left.span, equivalentTo: right, by: areEquivalent, - message(), trapping: trapping, file: file, line: line) + printer: printer, + message(), + trapping: trapping, + file: file, + line: line) } #endif @@ -70,9 +75,9 @@ class UniqueArrayTests: CollectionTestCase { let items = UniqueArray(consuming: tracker.rigidArray(layout: layout)) let expected = (0 ..< layout.count).map { tracker.instance(for: $0) } expectEqual(tracker.instances, 2 * layout.count) - expectContainerContents(items, equalTo: expected) + expectIterableContents(items, equalTo: expected) #if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW - checkContainer(items, expectedContents: expected) + checkIterable(items, expectedContents: expected) #endif } } @@ -150,7 +155,11 @@ class UniqueArrayTests: CollectionTestCase { expectEqual(a.count, layout.count) expectEqual(a.freeCapacity, layout.capacity - layout.count) expectEqual(a.isEmpty, layout.count == 0) - expectContainerContents(a, equivalentTo: 0 ..< layout.count, by: { $0.payload == $1 }) + expectIterableContents( + a, + equivalentTo: 0 ..< layout.count, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) } } } @@ -189,6 +198,7 @@ class UniqueArrayTests: CollectionTestCase { } #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +#if false // FIXME: Update func test_init_copying_Container() { withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in withEvery("spanCounts", in: [ @@ -215,6 +225,29 @@ class UniqueArrayTests: CollectionTestCase { } } #endif +#endif + + func test_init_copying_Span() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + let a = tracker.uniqueArray(layout: layout) + let b = UniqueArray(capacity: layout.capacity, copying: a.span) + expectEqual(tracker.instances, layout.count) + expectEqual(b.capacity, layout.capacity) + expectEqual(b.count, layout.count) + expectEqual(b.freeCapacity, layout.capacity - layout.count) + expectEqual(b.isEmpty, layout.count == 0) + for i in 0 ..< layout.count { + expectEqual(b[i].payload, i) + } + expectIterableContents( + b, + equivalentTo: 0 ..< layout.count, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) + } + } + } func test_span() { withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in @@ -316,8 +349,11 @@ class UniqueArrayTests: CollectionTestCase { a.swapAt(i, layout.count - 1 - i) } let expected = (0 ..< layout.count).reversed() - expectContainerContents( - a, equivalentTo: expected, by: { $0.payload == $1 }) + expectIterableContents( + a, + equivalentTo: expected, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) expectEqual(tracker.instances, layout.count) } } @@ -394,10 +430,11 @@ class UniqueArrayTests: CollectionTestCase { errorHandler: { error in expectTrue(error is TestError) } - expectContainerContents( + expectIterableContents( a, equivalentTo: (0 ..< layout.count).map { -$0 }, - by: { $0.payload == $1 }) + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) expectEqual(tracker.instances, layout.count) } } @@ -419,8 +456,11 @@ class UniqueArrayTests: CollectionTestCase { expectEqual(a.count, layout.count) expectEqual(a.capacity, newCapacity) expectEqual(tracker.instances, layout.count) - expectContainerContents( - a, equivalentTo: 0 ..< layout.count, by: { $0.payload == $1 }) + expectIterableContents( + a, + equivalentTo: 0 ..< layout.count, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) } } } @@ -443,8 +483,11 @@ class UniqueArrayTests: CollectionTestCase { expectEqual(a.count, layout.count) expectEqual(a.capacity, Swift.max(layout.capacity, newCapacity)) expectEqual(tracker.instances, layout.count) - expectContainerContents( - a, equivalentTo: 0 ..< layout.count, by: { $0.payload == $1 }) + expectIterableContents( + a, + equivalentTo: 0 ..< layout.count, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) } } } @@ -500,8 +543,11 @@ class UniqueArrayTests: CollectionTestCase { expectEqual(tracker.instances, layout.count) a.removeLast(k) expectEqual(tracker.instances, layout.count - k) - expectContainerContents( - a, equivalentTo: expected, by: { $0.payload == $1 }) + expectIterableContents( + a, + equivalentTo: expected, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) } } } @@ -517,7 +563,11 @@ class UniqueArrayTests: CollectionTestCase { var a = tracker.uniqueArray(layout: layout) let old = a.remove(at: i) expectEqual(old.payload, i) - expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 }) + expectIterableContents( + a, + equivalentTo: expected, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) } } } @@ -532,7 +582,11 @@ class UniqueArrayTests: CollectionTestCase { var a = tracker.uniqueArray(layout: layout) a.removeSubrange(range) - expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 }) + expectIterableContents( + a, + equivalentTo: expected, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) } } } @@ -547,7 +601,7 @@ class UniqueArrayTests: CollectionTestCase { var a = tracker.uniqueArray(layout: layout) a.removeAll(where: { $0.payload.isMultiple(of: 2) }) - expectContainerContents( + expectIterableContents( a, equivalentTo: expected, by: { $0.payload == $1 }) } } @@ -564,8 +618,11 @@ class UniqueArrayTests: CollectionTestCase { let item = a.popLast() expectEquivalent(item, expectedItem, by: { $0?.payload == $1 }) - expectContainerContents( - a, equivalentTo: expected, by: { $0.payload == $1 }) + expectIterableContents( + a, + equivalentTo: expected, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) } } } @@ -634,7 +691,11 @@ class UniqueArrayTests: CollectionTestCase { for i in layout.count ..< c { a.append(tracker.instance(for: i)) expectEqual(a.count, i + 1) - expectContainerContents(a, equivalentTo: 0 ..< i + 1, by: { $0.payload == $1 }) + expectIterableContents( + a, + equivalentTo: 0 ..< i + 1, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) } expectEqual(tracker.instances, c) } @@ -651,8 +712,11 @@ class UniqueArrayTests: CollectionTestCase { elements: (layout.count ..< c).map { tracker.instance(for: $0) }, underestimatedCount: .half, isContiguous: isContiguous)) - expectContainerContents( - a, equivalentTo: 0 ..< c, by: { $0.payload == $1}) + expectIterableContents( + a, + equivalentTo: 0 ..< c, + by: { $0.payload == $1}, + printer: { "\($0.payload)" }) expectEqual(tracker.instances, c) } } @@ -671,8 +735,11 @@ class UniqueArrayTests: CollectionTestCase { } a.append(copying: b.span) let c = layout.count + additions - expectContainerContents( - a, equivalentTo: 0 ..< c, by: { $0.payload == $1 }) + expectIterableContents( + a, + equivalentTo: 0 ..< c, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) expectEqual(tracker.instances, c) } } @@ -680,6 +747,7 @@ class UniqueArrayTests: CollectionTestCase { } #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +#if false // FIXME: Update func test_append_copying_Container() { withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in withEvery("additions", in: [0, 1, 10, 100]) { additions in @@ -695,14 +763,18 @@ class UniqueArrayTests: CollectionTestCase { contents: RigidArray(copying: addition), spanCounts: [spanCount]) a.append(copying: b) - expectContainerContents( - a, equivalentTo: 0 ..< c, by: { $0.payload == $1 }) + expectIterableContents( + a, + equivalentTo: 0 ..< c, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) expectEqual(tracker.instances, c) } } } } } +#endif #endif func test_insert_at() { @@ -715,8 +787,11 @@ class UniqueArrayTests: CollectionTestCase { var a = tracker.uniqueArray(layout: layout) a.insert(tracker.instance(for: -1), at: i) - expectContainerContents( - a, equivalentTo: expected, by: { $0.payload == $1 }) + expectIterableContents( + a, + equivalentTo: expected, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) expectEqual(tracker.instances, layout.count + 1) } } @@ -737,8 +812,11 @@ class UniqueArrayTests: CollectionTestCase { var a = tracker.uniqueArray(layout: layout) a.insert(copying: trackedAddition, at: i) - expectContainerContents( - a, equivalentTo: expected, by: { $0.payload == $1 }) + expectIterableContents( + a, + equivalentTo: expected, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) expectEqual(tracker.instances, layout.count + c) } } @@ -762,8 +840,11 @@ class UniqueArrayTests: CollectionTestCase { var a = tracker.uniqueArray(layout: layout) a.insert(copying: rigidAddition.span, at: i) - expectContainerContents( - a, equivalentTo: expected, by: { $0.payload == $1 }) + expectIterableContents( + a, + equivalentTo: expected, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) expectEqual(tracker.instances, layout.count + c) } } @@ -772,6 +853,7 @@ class UniqueArrayTests: CollectionTestCase { } #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +#if false // FIXME: Update func test_insert_copying_Container() { withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in withEvery("i", in: 0 ... layout.count) { i in @@ -793,8 +875,11 @@ class UniqueArrayTests: CollectionTestCase { spanCounts: [spanCount]) a.insert(copying: rigidAddition, at: i) - expectContainerContents( - a, equivalentTo: expected, by: { $0.payload == $1 }) + expectIterableContents( + a, + equivalentTo: expected, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) expectEqual(tracker.instances, layout.count + c) } } @@ -802,9 +887,10 @@ class UniqueArrayTests: CollectionTestCase { } } } +#endif #endif - func test_replaceSubrange_copying_Collection() { + func test_replace_copying_Collection() { withSomeArrayLayouts("layout", ofCapacities: [0, 5, 10]) { layout in withEveryRange("range", in: 0 ..< layout.count) { range in withEvery("c", in: [0, 1, 10, 100]) { c in @@ -815,10 +901,13 @@ class UniqueArrayTests: CollectionTestCase { var a = tracker.uniqueArray(layout: layout) let trackedAddition = addition.map { tracker.instance(for: $0) } - a.replaceSubrange(range, copying: trackedAddition) + a.replace(removing: range, copying: trackedAddition) - expectContainerContents( - a, equivalentTo: expected, by: { $0.payload == $1 }) + expectIterableContents( + a, + equivalentTo: expected, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) expectEqual(tracker.instances, layout.count - range.count + c) } } @@ -826,7 +915,7 @@ class UniqueArrayTests: CollectionTestCase { } } - func test_replaceSubrange_copying_Span() { + func test_replace_copying_Span() { withSomeArrayLayouts("layout", ofCapacities: [0, 5, 10]) { layout in withEveryRange("range", in: 0 ..< layout.count) { range in withEvery("c", in: [0, 1, 10, 100]) { c in @@ -838,10 +927,13 @@ class UniqueArrayTests: CollectionTestCase { var a = tracker.uniqueArray(layout: layout) let trackedAddition = RigidArray( copying: addition.map { tracker.instance(for: $0) }) - a.replaceSubrange(range, copying: trackedAddition.span) + a.replace(removing: range, copying: trackedAddition.span) - expectContainerContents( - a, equivalentTo: expected, by: { $0.payload == $1 }) + expectIterableContents( + a, + equivalentTo: expected, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) expectEqual(tracker.instances, layout.count - range.count + c) } } @@ -850,7 +942,8 @@ class UniqueArrayTests: CollectionTestCase { } #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW - func test_replaceSubrange_copying_Container() { +#if false // FIXME: Update + func test_replace_copying_Container() { withSomeArrayLayouts("layout", ofCapacities: [0, 5, 10]) { layout in withEveryRange("range", in: 0 ..< layout.count) { range in withEvery("c", in: [0, 1, 10, 100]) { c in @@ -867,8 +960,11 @@ class UniqueArrayTests: CollectionTestCase { spanCounts: [spanCount]) a.replaceSubrange(range, copying: trackedAddition) - expectContainerContents( - a, equivalentTo: expected, by: { $0.payload == $1 }) + expectIterableContents( + a, + equivalentTo: expected, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) expectEqual(tracker.instances, layout.count - range.count + c) } } @@ -877,5 +973,6 @@ class UniqueArrayTests: CollectionTestCase { } } #endif +#endif } #endif diff --git a/Tests/ContainersTests/RefTests.swift b/Tests/ContainersTests/BorrowTests.swift similarity index 86% rename from Tests/ContainersTests/RefTests.swift rename to Tests/ContainersTests/BorrowTests.swift index c23ed74d..7052c467 100644 --- a/Tests/ContainersTests/RefTests.swift +++ b/Tests/ContainersTests/BorrowTests.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2025 Apple Inc. and the Swift project authors +// Copyright (c) 2026 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information @@ -14,7 +14,7 @@ import XCTest import ContainersPreview import Synchronization -final class RefTests: XCTestCase { +final class BorrowTests: XCTestCase { @available(SwiftStdlib 5.0, *) func test_basic() { let x: Atomic? = Atomic(0) diff --git a/Tests/ContainersTests/MutTests.swift b/Tests/ContainersTests/InoutTests.swift similarity index 85% rename from Tests/ContainersTests/MutTests.swift rename to Tests/ContainersTests/InoutTests.swift index a31b204d..9e379ef3 100644 --- a/Tests/ContainersTests/MutTests.swift +++ b/Tests/ContainersTests/InoutTests.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors +// Copyright (c) 2024 - 2026 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information @@ -18,10 +18,10 @@ import ContainersPreview #endif #if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW -final class MutTests: XCTestCase { +final class InoutTests: XCTestCase { func test_basic() { var x = 0 - var y = Mut(&x) + var y = Inout(&x) var v = y[] XCTAssertEqual(v, 0) diff --git a/Tests/DequeTests/DequeInternals.swift b/Tests/DequeTests/DequeInternals.swift index f9fc9b4b..cb38992d 100644 --- a/Tests/DequeTests/DequeInternals.swift +++ b/Tests/DequeTests/DequeInternals.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors +// Copyright (c) 2021 - 2026 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information @@ -16,7 +16,43 @@ import _CollectionsTestSupport @_spi(Testing) import DequeModule #endif -internal struct DequeLayout: CustomStringConvertible { +#if compiler(>=6.2) +@available(SwiftStdlib 5.0, *) +internal struct RigidTestData: ~Copyable { + var deque: RigidDeque + var contents: [Element] + + init(_ deque: consuming RigidDeque, _ contents: [Element]) { + self.deque = deque + self.contents = contents + } + + mutating func take() -> RigidDeque { + exchange(&self.deque, with: .init()) + } + + consuming func consume() -> RigidDeque { + exchange(&self.deque, with: .init()) + } +} + +@available(SwiftStdlib 5.0, *) +internal struct UniqueTestData: ~Copyable { + var deque: UniqueDeque + var contents: [Element] + + init(_ deque: consuming RigidDeque, _ contents: [Element]) { + self.init(UniqueDeque(consuming: deque), contents) + } + + init(_ deque: consuming UniqueDeque, _ contents: [Element]) { + self.deque = deque + self.contents = contents + } +} +#endif + +internal struct DequeLayout: Hashable, CustomStringConvertible { let capacity: Int let startSlot: Int let count: Int @@ -29,6 +65,7 @@ internal struct DequeLayout: CustomStringConvertible { self.startValue = startValue } + var freeCapacity: Int { capacity - count } var valueRange: Range { startValue ..< startValue + count } var description: String { @@ -52,6 +89,16 @@ extension Deque { } } +#if compiler(>=6.2) +@available(SwiftStdlib 5.0, *) +extension RigidDeque { + init(layout: DequeLayout, contents: C) where C.Element == Element { + precondition(contents.count == layout.count) + self.init(_capacity: layout.capacity, startSlot: layout.startSlot, copying: contents) + } +} +#endif + extension LifetimeTracker { func deque( with layout: DequeLayout @@ -60,6 +107,26 @@ extension LifetimeTracker { let deque = Deque(layout: layout, contents: contents) return (deque, contents) } + +#if compiler(>=6.2) + @available(SwiftStdlib 5.0, *) + func rigidDeque( + with layout: DequeLayout + ) -> RigidTestData> { + let contents = self.instances(for: layout.valueRange) + let deque = RigidDeque(layout: layout, contents: contents) + return RigidTestData(deque, contents) + } + + @available(SwiftStdlib 5.0, *) + func uniqueDeque( + with layout: DequeLayout + ) -> UniqueTestData> { + let contents = self.instances(for: layout.valueRange) + let deque = RigidDeque(layout: layout, contents: contents) + return UniqueTestData(deque, contents) + } +#endif } func withEveryDeque( diff --git a/Tests/DequeTests/RigidDequeCrashTests.swift b/Tests/DequeTests/RigidDequeCrashTests.swift new file mode 100644 index 00000000..717919a6 --- /dev/null +++ b/Tests/DequeTests/RigidDequeCrashTests.swift @@ -0,0 +1,81 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2025 - 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +import Testing +#if COLLECTIONS_SINGLE_MODULE +import Collections +#else +import DequeModule +import ContainersPreview +#endif + +#if compiler(>=6.2) +@Suite("RigidDeque Crash Tests") +struct RigidDequeCrashTests { + + // MARK: - Edge Cases and Error Conditions + + @Test("Append to full deque fails") + func appendToFullDequeFails() async { + await #expect(processExitsWith: .failure) { + var deque = RigidDeque(capacity: 2) + deque.append(1) + deque.append(2) + + #expect(deque.isFull == true) + deque.append(3) // Traps with "RigidDeque is full" + } + } + + @Test("Prepend to full deque fails") + func prependToFullDequeFails() async { + await #expect(processExitsWith: .failure) { + var deque = RigidDeque(capacity: 2) + deque.append(1) + deque.append(2) + + #expect(deque.isFull == true) + deque.prepend(0) // Traps with "RigidDeque is full" + } + } + + @Test("Invalid index access") + func invalidIndexAccess() async { + await #expect(processExitsWith: .failure) { + let deque = RigidDeque(copying: [1, 2, 3]) + let _ = deque[-1] // Index out of bounds + } + await #expect(processExitsWith: .failure) { + let deque = RigidDeque(copying: [1, 2, 3]) + let _ = deque[3] // Index out of bounds + } + #if false + await #expect(processExitsWith: .failure) { + let deque = RigidDeque(copying: [1, 2, 3]) + let _ = deque.borrowElement(at: 5) // Index out of bounds + } + #endif + } + + @Test("Remove from empty deque") + func removeFromEmptyDeque() async { + await #expect(processExitsWith: .failure) { + var deque = RigidDeque(capacity: 5) + deque.removeFirst() // Can't remove first element of an empty RigidDeque + } + await #expect(processExitsWith: .failure) { + var deque = RigidDeque(capacity: 5) + deque.removeLast() // Can't remove last element of an empty RigidDeque + } + } +} + +#endif diff --git a/Tests/DequeTests/RigidDequeTests.swift b/Tests/DequeTests/RigidDequeTests.swift new file mode 100644 index 00000000..d1b4ed43 --- /dev/null +++ b/Tests/DequeTests/RigidDequeTests.swift @@ -0,0 +1,1547 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2025 - 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +import XCTest +#if COLLECTIONS_SINGLE_MODULE +@_spi(Testing) import Collections +#else +import _CollectionsTestSupport +import DequeModule +import BasicContainers +import ContainersPreview +#endif + +#if compiler(>=6.2) +#if !COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +/// Check if `left` and `right` contain equal elements in the same order. +@available(SwiftStdlib 5.0, *) +internal func expectIterableContents< + Element: Equatable, + C2: Collection, +>( + _ left: borrowing RigidDeque, + equalTo right: C2, + _ message: @autoclosure () -> String = "", + trapping: Bool = false, + file: StaticString = #filePath, + line: UInt = #line +) { + expectIterableContents( + left, + equivalentTo: right, + by: ==, + message(), trapping: trapping, file: file, line: line) +} + +/// Check if `left` and `right` contain equal elements in the same order. +@available(SwiftStdlib 5.0, *) +internal func expectIterableContents< + E1, + C2: Collection, +>( + _ left: borrowing RigidDeque, + equivalentTo right: C2, + by areEquivalent: (borrowing E1, C2.Element) -> Bool, + _ message: @autoclosure () -> String = "", + trapping: Bool = false, + file: StaticString = #filePath, + line: UInt = #line +) { + expectIterableContents( + left, + equivalentTo: right, + by: areEquivalent, + printer: { "\($0)" }, + message(), + file: file, + line: line) +} + +/// Check if `left` and `right` contain equal elements in the same order. +@available(SwiftStdlib 5.0, *) +internal func expectIterableContents< + E1: ~Copyable, + C2: Collection, +>( + _ left: borrowing RigidDeque, + equivalentTo right: C2, + by areEquivalent: (borrowing E1, C2.Element) -> Bool, + printer: (borrowing E1) -> String, + _ message: @autoclosure () -> String = "", + trapping: Bool = false, + file: StaticString = #filePath, + line: UInt = #line +) { + var c = 0 + var j = right.startIndex + for i in 0 ..< left.count { + expectEquivalent( + left[i], + right[j], + by: areEquivalent, + printer: printer, + "offset: \(c) \(message())", + trapping: trapping, + file: file, line: line) + right.formIndex(after: &j) + c += 1 + } +} + +#endif + +final class RigidDequeTests: CollectionTestCase { + struct TestError: Error, Equatable { + let value: Int + init(_ value: Int) { self.value = value } + } + + func test_testingSPIs() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withLifetimeTracking { tracker in + let data = tracker.rigidDeque(with: layout) + expectEqual(data.deque._startSlot, layout.startSlot) + expectEqual(data.deque.capacity, layout.capacity) + expectEqual(data.deque.count, layout.count) + expectEqual(data.deque.freeCapacity, layout.capacity - layout.count) + for i in 0 ..< layout.count { + expectEqual(data.deque[i], data.contents[i]) + } + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + + func test_basicProperties() { + var deque = RigidDeque(capacity: 10) + + // Empty deque + expectEqual(deque.isEmpty, true) + expectEqual(deque.isFull, false) + expectEqual(deque.count, 0) + expectEqual(deque.capacity, 10) + expectEqual(deque.freeCapacity, 10) + expectEqual(deque.startIndex, 0) + expectEqual(deque.endIndex, 0) + expectEqual(deque.indices, 0 ..< 0) + + // Add some elements + deque.append(1) + deque.append(2) + deque.append(3) + + expectEqual(deque.isEmpty, false) + expectEqual(deque.isFull, false) + expectEqual(deque.count, 3) + expectEqual(deque.capacity, 10) + expectEqual(deque.freeCapacity, 7) + expectEqual(deque.startIndex, 0) + expectEqual(deque.endIndex, 3) + expectEqual(deque.indices, 0 ..< 3) + + // Fill to capacity + for i in 4...10 { + deque.append(i) + } + + expectEqual(deque.isEmpty, false) + expectEqual(deque.isFull, true) + expectEqual(deque.count, 10) + expectEqual(deque.freeCapacity, 0) + expectEqual(deque.indices, 0 ..< 10) + } + + func test_subscriptBorrow() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withLifetimeTracking { tracker in + let data = tracker.rigidDeque(with: layout) + withEvery("i", in: 0 ..< layout.count) { i in + expectEqual(data.deque[i], data.contents[i]) + } + } + } + } + + func test_subscriptMutate() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withEvery("i", in: 0 ..< layout.count) { i in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + let new = tracker.instance(for: 100) + data.deque[i] = new + data.contents[i] = new + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + } + + func test_swapAt() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5]) { layout in + withEvery("i", in: 0 ..< layout.count) { i in + withEvery("j", in: 0 ..< layout.count) { j in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + data.deque.swapAt(i, j) + data.contents.swapAt(i, j) + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + } + } + + func test_reallocate() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withEvery( + "newCapacity", + in: [layout.capacity, layout.count, 2 * layout.capacity] as Set + ) { newCapacity in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + data.deque.reallocate(capacity: newCapacity) + + expectEqual(data.deque.capacity, newCapacity) + expectEqual(data.deque.count, layout.count) + expectEqual(tracker.instances, layout.count) + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + } + + func test_reserveCapacity() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withEvery( + "newCapacity", + in: [layout.capacity, layout.count, 2 * layout.capacity] as Set + ) { newCapacity in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + data.deque.reserveCapacity(newCapacity) + + expectEqual(data.deque.capacity, Swift.max(layout.capacity, newCapacity)) + expectEqual(data.deque.count, layout.count) + expectEqual(tracker.instances, layout.count) + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + } + + func test_initWithCapacity() { + withEvery("capacity", in: [0, 1, 2, 3, 5, 10]) { capacity in + let deque = RigidDeque(capacity: capacity) + expectEqual(deque.capacity, capacity) + expectEqual(deque.count, 0) + expectEqual(deque.freeCapacity, capacity) + if capacity == 0 { + expectNil(deque._handle._buffer.baseAddress) // No allocations + } + } + } + + func test_initEmpty() { + let deque = RigidDeque() + expectEqual(deque.capacity, 0) + expectEqual(deque.count, 0) + expectEqual(deque.freeCapacity, 0) + expectNil(deque._handle._buffer.baseAddress) // No allocations + } + + func test_initWithClosure_Full() { + withEvery("capacity", in: 0 ..< 10) { capacity in + withLifetimeTracking { tracker in + let deque = RigidDeque(capacity: capacity) { span in + for i in 0 ..< capacity { + span.append(tracker.structInstance(for: i)) + } + } + expectEqual(deque.count, capacity) + expectEqual(deque.capacity, capacity) + withEvery("i", in: 0 ..< capacity) { i in + expectEqual(deque[i].payload, i) + } + + expectEqual(tracker.instances, capacity) + _ = consume deque + expectEqual(tracker.instances, 0) + } + } + } + + func test_initWithClosure_Partial() { + withEvery("capacity", in: 0 ..< 10) { capacity in + withEvery("count", in: [0, capacity / 2, max(capacity - 1, 0)] as Set) { count in + withLifetimeTracking { tracker in + let deque = RigidDeque(capacity: capacity) { span in + for i in 0 ..< count { + span.append(tracker.structInstance(for: i)) + } + } + expectEqual(deque.count, count) + expectEqual(deque.capacity, capacity) + withEvery("i", in: 0 ..< count) { i in + expectEqual(deque[i].payload, i) + } + + expectEqual(tracker.instances, count) + _ = consume deque + expectEqual(tracker.instances, 0) + } + } + } + } + + func test_initWithClosure_Failing() { + withEvery("capacity", in: 1 ..< 10 as Range) { capacity -> Void in + withEvery("count", in: [0, capacity / 2, max(capacity - 1, 0)] as Set) { count -> Void in + withLifetimeTracking { tracker -> Void in + expectThrows { () throws(TestError) -> Void in + let deque = try RigidDeque>( + capacity: capacity + ) { span throws(TestError) -> Void in + for i in 0 ..< count { + span.append(tracker.structInstance(for: i)) + } + expectEqual(tracker.instances, count) + throw TestError(42) + } + expectEqual(deque.count, count) + } + errorHandler: { error in + expectEqual(error.value, 42) + } + } + } + } + } + + func test_init_consumingUniqueDeque() { + withLifetimeTracking { tracker in + let ud = UniqueDeque(copying: tracker.instances(for: 0 ..< 10)) + expectEqual(ud.count, 10) + expectEqual(tracker.instances, 10) + let buffer = ud._storage._handle._buffer + expectNotNil(buffer.baseAddress) + + let rd = RigidDeque(consuming: ud) + expectEqual(rd.count, 10) + expectEqual(tracker.instances, 10) + expectEqual(rd._handle._buffer.baseAddress, buffer.baseAddress) + + _ = consume rd + expectEqual(tracker.instances, 0) + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + func test_initFromProducer() { + withEvery("count", in: 0 ..< 10) { count in + withEvery("capacity", in: [count / 2, count, 2 * count] as Set) { capacity in + withLifetimeTracking { tracker in + var invocations = 0 + var producer = CustomProducer, Never> { + if invocations >= count { + return nil + } + defer { invocations += 1 } + return tracker.structInstance(for: invocations) + } + + let c = min(count, capacity) + let deque = RigidDeque(capacity: capacity, from: &producer) + expectEqual(invocations, c) + expectEqual(deque.count, c) + expectEqual(tracker.instances, c) + expectEqual(invocations, c) + + for i in 0 ..< c { + expectEqual(deque[i].payload, i) + } + } + } + } + } + + func test_initFromThrowingProducer() { + withEvery("count", in: 0 ..< 10) { (count: Int) in + withLifetimeTracking { tracker in + var invocations = 0 + var producer = CustomProducer, TestError> + { () throws(TestError) in + if invocations >= count { + throw TestError(42) + } + defer { invocations += 1 } + return tracker.structInstance(for: invocations) + } + + expectThrows { () throws(TestError) in + let _ = try RigidDeque(capacity: count + 10, from: &producer) + } + errorHandler: { error in + expectEqual(error.value, 42) + } + expectEqual(invocations, count) + } + } + } +#endif + + func test_initRepeatingValue() { + withEvery("c", in: 0 ..< 10) { c in + withLifetimeTracking { tracker in + let deque = RigidDeque(repeating: LifetimeTracked(42, for: tracker), count: c) + expectEqual(deque.count, c) + expectEqual(deque.capacity, c) + withEvery("i", in: 0 ..< c) { i in + expectEqual(deque[i].payload, 42) + } + expectEqual(tracker.instances, c == 0 ? 0 : 1) + _ = consume deque + expectEqual(tracker.instances, 0) + } + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + func test_initCopyingBorrowingSequence() { + withEvery("c", in: 0 ..< 10) { c in + withEvery("capacity", in: [c, c + 1]) { capacity in + withLifetimeTracking { tracker in + let values = RigidArray(copying: tracker.instances(for: 0 ..< c)) + let deque = RigidDeque(capacity: capacity, copying: values) + + expectEqual(deque.count, c) + expectEqual(deque.capacity, capacity) + expectIterablePayloads(deque, equalTo: 0 ..< c) + + expectEqual(tracker.instances, c) + _ = consume values + expectEqual(tracker.instances, c) + _ = consume deque + expectEqual(tracker.instances, 0) + } + } + } + } +#endif + + func test_initCopyingSequence() { + withEvery("c", in: 0 ..< 10) { c in + withEvery("capacity", in: [c, c + 1]) { capacity in + withLifetimeTracking { tracker in + let values = tracker.instances(for: 0 ..< c) + let contents = MinimalSequence( + elements: values, + underestimatedCount: .value(0)) + + let deque = RigidDeque(capacity: capacity, copying: contents) + + expectEqual(deque.count, c) + expectEqual(deque.capacity, capacity) + expectIterableContents(deque, equalTo: values) + + expectEqual(tracker.instances, c) + _ = consume values + _ = consume contents + expectEqual(tracker.instances, c) + _ = consume deque + expectEqual(tracker.instances, 0) + } + } + } + } + + func test_initCopyingCollection() { + withEvery("c", in: 0 ..< 10) { c in + withEvery("capacity", in: [c, c + 1]) { capacity in + withLifetimeTracking { tracker in + let values = tracker.instances(for: 0 ..< c) + let contents = MinimalCollection(values) + + let deque = RigidDeque(capacity: capacity, copying: contents) + + expectEqual(deque.count, c) + expectEqual(deque.capacity, capacity) + expectIterableContents(deque, equalTo: values) + + expectEqual(tracker.instances, c) + _ = consume values + _ = consume contents + expectEqual(tracker.instances, c) + _ = consume deque + expectEqual(tracker.instances, 0) + } + } + } + } + + func test_initCopyingRange_classic() { + // With a deployment target <6.2, this tests the Collection initializer + withEvery("c", in: 0 ..< 10) { c in + withEvery("capacity", in: [c, c + 1]) { capacity in + let deque = RigidDeque(capacity: capacity, copying: 0 ..< c) + + expectEqual(deque.count, c) + expectEqual(deque.capacity, capacity) + expectIterableContents(deque, equalTo: 0 ..< c) + } + } + } + + @available(SwiftStdlib 6.2, *) + func test_initCopyingRange_modern() { + // With a deployment target >=6.2, this tests the BorrowingSequence initializer + withEvery("c", in: 0 ..< 10) { c in + withEvery("capacity", in: [c, c + 1]) { capacity in + let deque = RigidDeque(capacity: capacity, copying: 0 ..< c) + + expectEqual(deque.count, c) + expectEqual(deque.capacity, capacity) + expectIterableContents(deque, equalTo: 0 ..< c) + } + } + } + + func test_popFirst() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + let expected = data.contents[...].popFirst() + let actual = data.deque.popFirst() + expectEqual(actual, expected) + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + + func test_popLast() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + let expected = data.contents[...].popLast() + let actual = data.deque.popLast() + expectEqual(actual, expected) + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + + func test_prepend() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + let extra = tracker.instance(for: layout.count) + guard !data.deque.isFull else { return } + data.contents.insert(extra, at: 0) + data.deque.prepend(extra) + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + + func test_append() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + let extra = tracker.instance(for: layout.count) + guard !data.deque.isFull else { return } + data.contents.insert(extra, at: data.contents.count) + data.deque.append(extra) + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + + func test_pushFirst() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + let extra = tracker.instance(for: layout.count) + + let result = data.deque.pushFirst(extra) + + if layout.count == layout.capacity { + expectEqual(result, extra) + expectIterableContents(data.deque, equalTo: data.contents) + } else { + data.contents.insert(extra, at: 0) + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + } + + func test_pushLast() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + let extra = tracker.instance(for: layout.count) + + let result = data.deque.pushLast(extra) + + if layout.count == layout.capacity { + expectEqual(result, extra) + expectIterableContents(data.deque, equalTo: data.contents) + } else { + data.contents.insert(extra, at: data.contents.count) + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + } + + func test_prepend_initializingWith_full() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withEvery("prependCount", in: 0 ..< layout.freeCapacity) { prependCount in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + + let extras = tracker.instances(for: layout.count ..< layout.count + prependCount) + + data.contents.insert(contentsOf: extras, at: 0) + + var i = 0 + data.deque.prepend(addingCount: prependCount) { target in + while !target.isFull { + target.append(extras[i]) + i += 1 + } + } + + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + } + + func test_append_initializingWith_full() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withEvery("prependCount", in: 0 ..< layout.freeCapacity) { prependCount in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + + let extras = tracker.instances(for: layout.count ..< layout.count + prependCount) + + data.contents.append(contentsOf: extras) + + var i = 0 + data.deque.append(maximumCount: prependCount) { target in + while !target.isFull { + target.append(extras[i]) + i += 1 + } + } + + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + } + + func test_prepend_initializingWith_partial() { + withEveryDeque("layout", ofCapacities: [1, 2, 3, 5, 10]) { layout in + withEvery("prependCount", in: 0 ..< layout.freeCapacity) { prependCount in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + + let extras = tracker.instances(for: layout.count ..< layout.count + prependCount) + + data.contents.insert(contentsOf: extras, at: 0) + + var i = 0 + data.deque.prepend(addingCount: layout.freeCapacity) { target in + while !target.isFull, i < prependCount { + target.append(extras[i]) + i += 1 + } + } + expectEqual(i, extras.count) + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + } + + func test_append_initializingWith_partial() { + withEveryDeque("layout", ofCapacities: [1, 2, 3, 5, 10]) { layout in + withEvery("prependCount", in: 0 ..< layout.freeCapacity) { prependCount in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + + let extras = tracker.instances(for: layout.count ..< layout.count + prependCount) + + data.contents.append(contentsOf: extras) + + var i = 0 + data.deque.append(maximumCount: layout.freeCapacity) { target in + while !target.isFull, i < prependCount { + target.append(extras[i]) + i += 1 + } + } + expectEqual(i, extras.count) + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + } + + func test_prepend_initializingWith_failing() { + withEveryDeque("layout", ofCapacities: [1, 2, 3, 5, 10]) { layout in + if layout.freeCapacity == 0 { return } + withEvery("prependCount", in: 0 ..< layout.freeCapacity) { prependCount in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + + let extras = tracker.instances(for: layout.count ..< layout.count + prependCount) + + data.contents.insert(contentsOf: extras, at: 0) + + expectThrows { () throws(TestError) in + var i = 0 + try data.deque.prepend( + addingCount: layout.freeCapacity + ) { target throws(TestError) in + while !target.isFull, i < prependCount { + target.append(extras[i]) + i += 1 + } + if i == prependCount { + throw TestError(42) + } + } + } + errorHandler: { error in + expectEqual(error.value, 42) + } + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + } + + + func test_append_initializingWith_failing() { + withEveryDeque("layout", ofCapacities: [1, 2, 3, 5, 10]) { layout in + if layout.freeCapacity == 0 { return } + withEvery("prependCount", in: 0 ..< layout.freeCapacity) { prependCount in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + + let extras = tracker.instances(for: layout.count ..< layout.count + prependCount) + + data.contents.append(contentsOf: extras) + + expectThrows { () throws(TestError) in + var i = 0 + try data.deque.append( + maximumCount: layout.freeCapacity + ) { target throws(TestError) in + while !target.isFull, i < prependCount { + target.append(extras[i]) + i += 1 + } + if i == prependCount { + throw TestError(42) + } + } + } + errorHandler: { error in + expectEqual(error.value, 42) + } + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + func test_prepend_Producer_full() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5]) { layout in + withEvery("producerSize", in: 0 ..< 6) { producerSize in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + + var extras = tracker.instances(for: 0 ..< producerSize) + + data.contents.insert(contentsOf: extras.prefix(layout.freeCapacity), at: 0) + + var producer = CustomProducer, Never> { + guard !extras.isEmpty else { return nil } + return extras.removeFirst() + } + + data.deque.prepend(from: &producer) + expectEqual(extras.count, max(0, producerSize - layout.freeCapacity)) + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + } +#endif + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + func test_append_Producer() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5]) { layout in + withEvery("producerSize", in: 0 ..< 6) { producerSize in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + + var extras = tracker.instances(for: 0 ..< producerSize) + + data.contents.append(contentsOf: extras.prefix(layout.freeCapacity)) + + var producer = CustomProducer, Never> { + guard !extras.isEmpty else { return nil } + return extras.removeFirst() + } + + data.deque.append(from: &producer) + expectEqual(extras.count, max(0, producerSize - layout.freeCapacity)) + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + } +#endif + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + func test_prepend_Producer_failing() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5]) { layout in + guard layout.freeCapacity > 0 else { return } + withEvery("producerSize", in: 0 ..< layout.freeCapacity - 1) { producerSize in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + + var extras = tracker.instances(for: 0 ..< producerSize) + + data.contents.insert(contentsOf: extras, at: 0) + + var producer = CustomProducer, TestError> { () throws(TestError) in + guard !extras.isEmpty else { throw TestError(23) } + return extras.removeFirst() + } + + expectThrows { () throws(TestError) in + try data.deque.prepend(from: &producer) + } + errorHandler: { error in + expectEqual(error.value, 23) + } + expectEqual(extras.count, 0) + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + } +#endif + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + func test_append_Producer_failing() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5]) { layout in + guard layout.freeCapacity > 0 else { return } + withEvery("producerSize", in: 0 ..< layout.freeCapacity - 1) { producerSize in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + + var extras = tracker.instances(for: 0 ..< producerSize) + + data.contents.append(contentsOf: extras) + + var producer = CustomProducer, TestError> { () throws(TestError) in + guard !extras.isEmpty else { throw TestError(23) } + return extras.removeFirst() + } + + expectThrows { () throws(TestError) in + try data.deque.append(from: &producer) + } + errorHandler: { error in + expectEqual(error.value, 23) + } + expectEqual(extras.count, 0) + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + } +#endif + + func test_prepend_MinimalSequence() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withEvery("c", in: 0 ..< layout.freeCapacity) { c in + withEvery("underestimatedCount", in: [UnderestimatedCountBehavior.precise, .half, .value(min(1, c))]) { underestimatedCount in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + let extras = tracker.instances(for: layout.count ..< layout.count + c) + let sequence = MinimalSequence(elements: extras, underestimatedCount: underestimatedCount) + data.contents.insert(contentsOf: extras, at: 0) + data.deque.prepend(copying: sequence) + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + } + } + + func test_append_MinimalSequence() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withEvery("c", in: 0 ..< layout.freeCapacity) { c in + withEvery("underestimatedCount", in: [UnderestimatedCountBehavior.precise, .half, .value(min(1, c))]) { underestimatedCount in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + let extras = tracker.instances(for: layout.count ..< layout.count + c) + let sequence = MinimalSequence(elements: extras, underestimatedCount: underestimatedCount) + data.contents.append(contentsOf: extras) + data.deque.append(copying: sequence) + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + } + } + + func test_prepend_MinimalCollection() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withEvery("c", in: 0 ..< layout.freeCapacity) { c in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + let extra = tracker.instances(for: layout.count ..< layout.count + c) + let minimal = MinimalCollection(extra) + data.contents.insert(contentsOf: extra, at: 0) + data.deque.prepend(copying: minimal) + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + } + + func test_append_MinimalCollection() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withEvery("c", in: 0 ..< layout.freeCapacity) { c in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + let extra = tracker.instances(for: layout.count ..< layout.count + c) + let minimal = MinimalCollection(extra) + data.contents.append(contentsOf: extra) + data.deque.append(copying: minimal) + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + } + + func test_prepend_ContiguousArray_asCollection() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withEvery("c", in: 0 ..< layout.freeCapacity) { c in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + let extraRange = layout.count ..< layout.count + c + let extra = ContiguousArray(tracker.instances(for: extraRange)) + data.contents.insert(contentsOf: extra, at: 0) + data.deque.prepend(copying: extra) + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + } + + func test_append_ContiguousArray_asCollection() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withEvery("c", in: 0 ..< layout.freeCapacity) { c in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + let extraRange = layout.count ..< layout.count + c + let extra = ContiguousArray(tracker.instances(for: extraRange)) + data.contents.append(contentsOf: extra) + data.deque.append(copying: extra) + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + } + + func test_prepend_ContiguousArray_asSequence() { + // This calls the Sequence-based `Deque.prepend` overload, even if + // `elements` happens to be of a Collection type. + func prependSequence( + contentsOf elements: S, + to deque: inout RigidDeque + ) { + deque.prepend(copying: elements) + } + + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withEvery("c", in: 0 ..< layout.freeCapacity) { c in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + let extraRange = layout.count ..< layout.count + c + let extra = ContiguousArray(tracker.instances(for: extraRange)) + data.contents.insert(contentsOf: extra, at: 0) + prependSequence(contentsOf: extra, to: &data.deque) + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + } + + func test_append_ContiguousArray_asSequence() { + // This calls the Sequence-based `Deque.append` overload, even if + // `elements` happens to be of a Collection type. + func appendSequence( + contentsOf elements: S, + to deque: inout RigidDeque + ) { + deque.append(copying: elements) + } + + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withEvery("c", in: 0 ..< layout.freeCapacity) { c in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + let extraRange = layout.count ..< layout.count + c + let extra = ContiguousArray(tracker.instances(for: extraRange)) + data.contents.append(contentsOf: extra) + appendSequence(contentsOf: extra, to: &data.deque) + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + } + + func test_prepend_BridgedArray() { + // https://github.com/apple/swift-collections/issues/27 + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withEvery("c", in: 0 ..< layout.freeCapacity) { c in + var contents: [NSObject] = (0 ..< layout.count).map { _ in NSObject() } + var deque = RigidDeque(layout: layout, contents: contents) + guard c <= deque.freeCapacity else { return } + let extra: [NSObject] = (0 ..< c) + .map { _ in NSObject() } + .withUnsafeBufferPointer { buffer in + NSArray(objects: buffer.baseAddress, count: buffer.count) as! [NSObject] + } + contents.insert(contentsOf: extra, at: 0) + deque.prepend(copying: extra) + expectIterableContents( + deque, + equivalentTo: contents, + by: ==, + printer: { "\($0)" }) + } + } + } + + func test_append_BridgedArray() { + // https://github.com/apple/swift-collections/issues/27 + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withEvery("c", in: 0 ..< layout.freeCapacity) { c in + var contents: [NSObject] = (0 ..< layout.count).map { _ in NSObject() } + var deque = RigidDeque(layout: layout, contents: contents) + guard c <= deque.freeCapacity else { return } + let extra: [NSObject] = (0 ..< c) + .map { _ in NSObject() } + .withUnsafeBufferPointer { buffer in + NSArray(objects: buffer.baseAddress, count: buffer.count) as! [NSObject] + } + contents.append(contentsOf: extra) + deque.append(copying: extra) + expectIterableContents( + deque, + equivalentTo: contents, + by: ==, + printer: { "\($0)" }) + } + } + } + + func test_insert() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withEvery("offset", in: 0 ... layout.count) { offset in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + let extra = tracker.instance(for: layout.count) + guard !data.deque.isFull else { return } + data.contents.insert(extra, at: offset) + data.deque.insert(extra, at: offset) + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + } + + func test_imsert_initializingWith_full() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withEvery("i", in: 0 ... layout.count) { i in + withEvery("c", in: 0 ..< layout.freeCapacity) { c in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + + let extras = tracker.instances(for: layout.count ..< layout.count + c) + + data.contents.insert(contentsOf: extras, at: i) + + var j = 0 + data.deque.insert(addingCount: c, at: i) { target in + expectLessThanOrEqual(target.count, extras.count - j) + while !target.isFull { + target.append(extras[j]) + j += 1 + } + } + expectEqual(j, extras.count) + + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + } + } + + func test_insert_initializingWith_partial() { + withEveryDeque("layout", ofCapacities: [1, 2, 3, 5, 10]) { layout in + guard layout.freeCapacity > 0 else { return } + withEvery("i", in: 0 ... layout.count) { i in + withEvery("c", in: 0 ..< layout.freeCapacity - 1) { c in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + + let extras = tracker.instances(for: layout.count ..< layout.count + c) + + data.contents.insert(contentsOf: extras, at: i) + + var j = 0 + data.deque.insert(addingCount: layout.freeCapacity, at: i) { target in + while !target.isFull, j < c { + target.append(extras[j]) + j += 1 + } + } + expectEqual(j, extras.count) + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + } + } + + func test_insert_initializingWith_failing() { + withEveryDeque("layout", ofCapacities: [1, 2, 3, 5, 10]) { layout in + if layout.freeCapacity == 0 { return } + withEvery("i", in: 0 ... layout.count) { i in + withEvery("c", in: 0 ..< layout.freeCapacity - 1) { c in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + + let extras = tracker.instances(for: layout.count ..< layout.count + c) + + data.contents.insert(contentsOf: extras, at: i) + + expectThrows { () throws(TestError) in + var j = 0 + try data.deque.insert( + addingCount: layout.freeCapacity, + at: i + ) { target throws(TestError) in + while !target.isFull, j < c { + target.append(extras[j]) + j += 1 + } + if j == c { + throw TestError(42) + } + } + } + errorHandler: { error in + expectEqual(error.value, 42) + } + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + func test_insert_fromProducer() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5]) { layout in + withEvery("i", in: 0 ... layout.count) { i in + withEvery("c", in: 0 ..< 6) { c in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + + var extras = tracker.instances(for: 0 ..< c) + + data.contents.insert( + contentsOf: extras.prefix(layout.freeCapacity), + at: i) + + var producer = CustomProducer, Never> { + guard !extras.isEmpty else { return nil } + return extras.removeFirst() + } + + data.deque.insert( + addingCount: layout.freeCapacity, + from: &producer, + at: i) + expectEqual(extras.count, max(0, c - layout.freeCapacity)) + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + } + } +#endif + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + func test_insert_fromProducer_failing() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5]) { layout in + guard layout.freeCapacity > 0 else { return } + withEvery("i", in: 0 ... layout.count) { i in + withEvery("c", in: 0 ..< layout.freeCapacity - 1) { c in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + + var extras = tracker.instances(for: 0 ..< c) + + data.contents.insert(contentsOf: extras, at: i) + + var producer = CustomProducer, TestError> { () throws(TestError) in + guard !extras.isEmpty else { throw TestError(23) } + return extras.removeFirst() + } + + expectThrows { () throws(TestError) in + try data.deque.insert( + addingCount: layout.freeCapacity, + from: &producer, + at: i) + } + errorHandler: { error in + expectEqual(error.value, 23) + } + expectEqual(extras.count, 0) + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + } + } +#endif + + func test_insert_MinimalCollection() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withEvery("i", in: 0 ... layout.count) { i in + withEvery("c", in: 0 ..< layout.freeCapacity) { c in + withEvery("isContiguous", in: [false, true]) { isContiguous in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + let extras = tracker.instances( + for: layout.count ..< layout.count + c) + let collection = MinimalCollection( + extras, + isContiguous: isContiguous) + data.contents.insert(contentsOf: extras, at: i) + data.deque.insert(copying: collection, at: i) + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + } + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + func test_insert_RigidArray() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withEvery("i", in: 0 ... layout.count) { i in + withEvery("c", in: 0 ..< layout.freeCapacity) { c in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + let extras = tracker.instances( + for: layout.count ..< layout.count + c) + data.contents.insert(contentsOf: extras, at: i) + + let array = RigidArray(copying: extras) + data.deque.insert(copying: array, at: i) + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + } + } +#endif + + func test_replace_addingCount_full() { + withEveryDeque("layout", ofCapacities: [0, 5, 10]) { layout in + withEveryRange("subrange", in: 0 ..< layout.count) { subrange in + withEvery("c", in: 0 ..< subrange.count + layout.freeCapacity) { c in + withLifetimeTracking { tracker in + var a = tracker.rigidDeque(with: layout).consume() + + var i = 0 + a.replace(removing: subrange, addingCount: c) { target in + while !target.isFull { + target.append(tracker.instance(for: layout.count + i)) + i += 1 + } + } + expectEqual(i, c) + + var expected = Array(0 ..< layout.count) + expected.replaceSubrange( + subrange, + with: layout.count ..< layout.count + c) + + expectIterableContents( + a, + equivalentTo: expected, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) + } + } + } + } + } + + func test_replace_addingCount_partial() { + withEveryDeque("layout", ofCapacities: [0, 5, 10]) { layout in + withEveryRange("subrange", in: 0 ..< layout.count) { subrange in + guard layout.freeCapacity - subrange.count > 0 else { return } + withEvery("c", in: 1 ..< subrange.count + layout.freeCapacity) { c in + withEvery("n", in: 0 ..< c - 1) { n in + withLifetimeTracking { tracker in + var a = tracker.rigidDeque(with: layout).consume() + + var i = 0 + a.replace(removing: subrange, addingCount: c) { target in + while !target.isFull, i < n { + target.append(tracker.instance(for: layout.count + i)) + i += 1 + } + } + expectEqual(i, n) + + var expected = Array(0 ..< layout.count) + expected.replaceSubrange( + subrange, + with: layout.count ..< layout.count + n) + + expectIterableContents( + a, + equivalentTo: expected, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) + } + } + } + } + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + func test_replace_consuming_addingCount_full() { + withEveryDeque("layout", ofCapacities: [0, 5, 10]) { layout in + withEveryRange("subrange", in: 0 ..< layout.count) { subrange in + withEvery("c", in: 0 ..< subrange.count + layout.freeCapacity) { c in + withLifetimeTracking { tracker in + var a = tracker.rigidDeque(with: layout).consume() + + var i = subrange.lowerBound + var j = 0 + a.replace( + removing: subrange, + consumingWith: { source in + while let next = source.popFirst() { + expectEqual(next.payload, i) + i += 1 + } + }, + addingCount: c, + initializingWith: { target in + expectEqual(i, subrange.upperBound) + while !target.isFull { + target.append(tracker.instance(for: layout.count + j)) + j += 1 + } + }) + expectEqual(i, subrange.upperBound) + expectEqual(j, c) + + var expected = Array(0 ..< layout.count) + expected.replaceSubrange( + subrange, + with: layout.count ..< layout.count + c) + + expectIterableContents( + a, + equivalentTo: expected, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) + } + } + } + } + } +#endif + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + func test_replace_consuming_addingCount_partial() { + withEveryDeque("layout", ofCapacities: [0, 5, 10]) { layout in + withEveryRange("subrange", in: 0 ..< layout.count) { subrange in + guard layout.freeCapacity - subrange.count > 0 else { return } + withEvery("c", in: 1 ..< subrange.count + layout.freeCapacity) { c in + withEvery("n", in: 0 ..< c - 1) { n in + withLifetimeTracking { tracker in + var a = tracker.rigidDeque(with: layout).consume() + + var i = subrange.lowerBound + var j = 0 + a.replace( + removing: subrange, + consumingWith: { source in + while let next = source.popFirst() { + expectEqual(next.payload, i) + i += 1 + } + }, + addingCount: c, + initializingWith: { target in + expectEqual(i, subrange.upperBound) + while !target.isFull, j < n { + target.append(tracker.instance(for: layout.count + j)) + j += 1 + } + }) + expectEqual(i, subrange.upperBound) + expectEqual(j, n) + + var expected = Array(0 ..< layout.count) + expected.replaceSubrange( + subrange, + with: layout.count ..< layout.count + n) + + expectIterableContents( + a, + equivalentTo: expected, + by: { $0.payload == $1 }, + printer: { "\($0.payload)" }) + } + } + } + } + } + } +#endif + + func test_removeOne() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withEvery("offset", in: 0 ..< layout.count) { offset in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + let expected = data.contents.remove(at: offset) + let actual = data.deque.remove(at: offset) + expectEqual(actual, expected) + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + } + + func test_removeSubrange() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withEveryRange("range", in: 0 ..< layout.count) { range in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + data.contents.removeSubrange(range) + data.deque.removeSubrange(range) + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + } + + func test_removeLast() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + guard layout.count > 0 else { return } + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + let expected = data.contents.removeLast() + let actual = data.deque.removeLast() + expectEqual(actual, expected) + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + + func test_removeLast_many() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + guard layout.count > 0 else { return } + withEvery("n", in: 0 ... layout.count) { n in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + data.contents.removeLast(n) + data.deque.removeLast(n) + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + } + + func test_removeFirst_one() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + guard layout.count > 0 else { return } + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + let expected = data.contents.removeFirst() + let actual = data.deque.removeFirst() + expectEqual(actual, expected) + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + + func test_removeFirst_many() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + guard layout.count > 0 else { return } + withEvery("n", in: 0 ... layout.count) { n in + withLifetimeTracking { tracker in + var data = tracker.rigidDeque(with: layout) + data.contents.removeFirst(n) + data.deque.removeFirst(n) + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + } + + func test_removeAll_keepingCapacity() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withEvery("isShared", in: [false, true]) { isShared in + guard layout.count > 0 else { return } + var data: RigidTestData> = .init(.init(capacity: 0), []) + withLifetimeTracking { tracker in + data = tracker.rigidDeque(with: layout) + data.contents.removeAll(keepingCapacity: true) + data.deque.removeAll() + expectEqual(data.deque.count, 0) + expectEqual(data.deque.capacity, layout.capacity) + } // All elements must be deinitialized at this point. + withExtendedLifetime(data.deque) {} + } + } + } +} +#endif diff --git a/Tests/DequeTests/UniqueDequeTests.swift b/Tests/DequeTests/UniqueDequeTests.swift new file mode 100644 index 00000000..27f5cff3 --- /dev/null +++ b/Tests/DequeTests/UniqueDequeTests.swift @@ -0,0 +1,198 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +import XCTest +#if COLLECTIONS_SINGLE_MODULE +@_spi(Testing) import Collections +#else +import _CollectionsTestSupport +import DequeModule +import BasicContainers +import ContainersPreview +#endif + +#if compiler(>=6.2) +#if !COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +/// Check if `left` and `right` contain equal elements in the same order. +@available(SwiftStdlib 5.0, *) +internal func expectIterableContents< + Element: Equatable, + C2: Collection, +>( + _ left: borrowing UniqueDeque, + equalTo right: C2, + _ message: @autoclosure () -> String = "", + trapping: Bool = false, + file: StaticString = #filePath, + line: UInt = #line +) { + expectIterableContents( + left, + equivalentTo: right, + by: ==, + message(), trapping: trapping, file: file, line: line) +} + +/// Check if `left` and `right` contain equal elements in the same order. +@available(SwiftStdlib 5.0, *) +internal func expectIterableContents< + E1, + C2: Collection, +>( + _ left: borrowing UniqueDeque, + equivalentTo right: C2, + by areEquivalent: (borrowing E1, C2.Element) -> Bool, + _ message: @autoclosure () -> String = "", + trapping: Bool = false, + file: StaticString = #filePath, + line: UInt = #line +) { + expectIterableContents( + left, + equivalentTo: right, + by: areEquivalent, + printer: { "\($0)" }, + message(), + file: file, + line: line) +} + +/// Check if `left` and `right` contain equal elements in the same order. +@available(SwiftStdlib 5.0, *) +internal func expectIterableContents< + E1: ~Copyable, + C2: Collection, +>( + _ left: borrowing UniqueDeque, + equivalentTo right: C2, + by areEquivalent: (borrowing E1, C2.Element) -> Bool, + printer: (borrowing E1) -> String, + _ message: @autoclosure () -> String = "", + trapping: Bool = false, + file: StaticString = #filePath, + line: UInt = #line +) { + var c = 0 + var j = right.startIndex + for i in 0 ..< left.count { + expectEquivalent( + left[i], + right[j], + by: areEquivalent, + printer: printer, + "offset: \(c) \(message())", + trapping: trapping, + file: file, line: line) + right.formIndex(after: &j) + c += 1 + } +} + +#endif + +final class UniqueDequeTests: CollectionTestCase { + struct TestError: Error, Equatable { + let value: Int + init(_ value: Int) { self.value = value } + } + + func test_basicProperties() { + var deque = UniqueDeque() + + // Empty deque + expectEqual(deque.isEmpty, true) + expectEqual(deque._isFull, true) + expectEqual(deque.count, 0) + expectEqual(deque.capacity, 0) + expectEqual(deque.freeCapacity, 0) + expectEqual(deque.startIndex, 0) + expectEqual(deque.endIndex, 0) + expectEqual(deque.indices, 0 ..< 0) + + deque.append(1) + deque.append(2) + deque.append(3) + + expectEqual(deque.isEmpty, false) + expectEqual(deque._isFull, true) + expectEqual(deque.count, 3) + expectEqual(deque.capacity, 3) + expectEqual(deque.freeCapacity, 0) + expectEqual(deque.startIndex, 0) + expectEqual(deque.endIndex, 3) + expectEqual(deque.indices, 0 ..< 3) + + for i in 4...10 { + deque.prepend(i) + } + + expectEqual(deque.isEmpty, false) + expectEqual(deque.count, 10) + expectEqual(deque.capacity, 12) + expectEqual(deque.freeCapacity, 2) + expectEqual(deque.indices, 0 ..< 10) + } + + func test_subscriptBorrow() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withLifetimeTracking { tracker in + let data = tracker.uniqueDeque(with: layout) + withEvery("i", in: 0 ..< layout.count) { i in + expectEqual(data.deque[i], data.contents[i]) + } + } + } + } + + func test_subscriptMutate() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in + withEvery("i", in: 0 ..< layout.count) { i in + withLifetimeTracking { tracker in + var data = tracker.uniqueDeque(with: layout) + let new = tracker.instance(for: 100) + data.deque[i] = new + data.contents[i] = new + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + } + + func test_swapAt() { + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5]) { layout in + withEvery("i", in: 0 ..< layout.count) { i in + withEvery("j", in: 0 ..< layout.count) { j in + withLifetimeTracking { tracker in + var data = tracker.uniqueDeque(with: layout) + data.deque.swapAt(i, j) + data.contents.swapAt(i, j) + expectIterableContents(data.deque, equalTo: data.contents) + } + } + } + } + } + + func test_growth() { + let expectedCapacities = [ + 0, 1, 2, 3, 5, 8, 12, 18, 27, 41, 62, 93, 140, 210, 315 + ] + var actualCapacities: Set = [] + var deque = UniqueDeque() + for i in 0 ..< 256 { + actualCapacities.insert(deque.capacity) + deque.append(i) + } + expectEqualElements(actualCapacities.sorted(), expectedCapacities) + } +} + +#endif diff --git a/Tests/HashTreeCollectionsTests/TreeHashedCollections Fixtures.swift b/Tests/HashTreeCollectionsTests/TreeHashedCollections Fixtures.swift index c61dc868..e993d291 100644 --- a/Tests/HashTreeCollectionsTests/TreeHashedCollections Fixtures.swift +++ b/Tests/HashTreeCollectionsTests/TreeHashedCollections Fixtures.swift @@ -30,6 +30,7 @@ let testItems: [RawCollider] = { RawCollider(5, "ACAD"), RawCollider(6, "ACAD"), ] +#if COLLECTIONS_LONG_TESTS if MemoryLayout.size == 8 { // Cut testing workload down a bit on 32-bit systems. In practice a 32-bit Int // usually means we're running on a watchOS device (arm64_32), and those are relatively slow @@ -47,6 +48,7 @@ let testItems: [RawCollider] = { RawCollider(12, "ACC"), ] #endif +#endif return testItems }() diff --git a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift index e175b426..8c75cd95 100644 --- a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift +++ b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift @@ -380,7 +380,7 @@ class OrderedSetTests: CollectionTestCase { expectEqual(set[index], count) expectEqualElements(set[...size == 8 { /// Add even more flags and extra long combining sequences. This considerably increases test /// workload. (Not necessarily due to grapheme cluster length, but because test performance is @@ -78,6 +79,7 @@ let sampleString: String = { T̸h̴e̶ ̵p̷o̷w̶e̵r̷f̸u̷l̷ ̵p̴r̷o̷g̶r̷a̸m̸m̶i̸n̴g̴ ̷l̶a̴n̸g̵u̵a̶g̸e̶ ̸t̶h̴a̵t̵ ̶i̷s̶ ̵a̷l̴s̸o̷ ̵e̵a̷s̷y̴ ̵t̵o̷ ̷l̷e̶a̵r̴n̸.̵ """# } + #endif return str }() diff --git a/Tests/_CollectionsTestSupport/AssertionContexts/Assertions+Containers.swift b/Tests/_CollectionsTestSupport/AssertionContexts/Assertions+Containers.swift index e153de16..a556cd1a 100644 --- a/Tests/_CollectionsTestSupport/AssertionContexts/Assertions+Containers.swift +++ b/Tests/_CollectionsTestSupport/AssertionContexts/Assertions+Containers.swift @@ -19,7 +19,7 @@ import ContainersPreview #if compiler(>=6.2) /// Check if `left` and `right` contain equal elements in the same order. @available(SwiftStdlib 5.0, *) -public func expectContainerContents< +public func expectIterableContents< Element: Equatable, C2: Collection, >( @@ -27,7 +27,7 @@ public func expectContainerContents< equalTo right: C2, _ message: @autoclosure () -> String = "", trapping: Bool = false, - file: StaticString = #file, + file: StaticString = #filePath, line: UInt = #line ) { var i = 0 @@ -58,8 +58,8 @@ public func expectContainerContents< /// Check if `left` and `right` contain equal elements in the same order. @available(SwiftStdlib 5.0, *) -public func expectContainerContents< - E1: ~Copyable, +public func expectIterableContents< + E1, C2: Collection, >( _ left: borrowing Span, @@ -67,7 +67,32 @@ public func expectContainerContents< by areEquivalent: (borrowing E1, C2.Element) -> Bool, _ message: @autoclosure () -> String = "", trapping: Bool = false, - file: StaticString = #file, + file: StaticString = #filePath, + line: UInt = #line +) { + expectIterableContents( + left, + equivalentTo: right, + by: areEquivalent, + printer: { "\($0)" }, + message(), + trapping: trapping, + file: file, line: line) +} + +/// Check if `left` and `right` contain equal elements in the same order. +@available(SwiftStdlib 5.0, *) +public func expectIterableContents< + E1: ~Copyable, + C2: Collection, +>( + _ left: borrowing Span, + equivalentTo right: C2, + by areEquivalent: (borrowing E1, C2.Element) -> Bool, + printer: (borrowing E1) -> String, + _ message: @autoclosure () -> String = "", + trapping: Bool = false, + file: StaticString = #filePath, line: UInt = #line ) { var i = 0 @@ -96,20 +121,116 @@ public func expectContainerContents< } #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +/// Check if `left` contains lifetime tracked instances whose payloads equal +/// the elements in `right`. @available(SwiftStdlib 5.0, *) -public func expectContainersWithEquivalentElements< - C1: Container & ~Copyable & ~Escapable, - C2: Container & ~Copyable & ~Escapable +public func expectIterablePayloads< + Payload: Equatable, + E1: BorrowingSequence> & ~Copyable & ~Escapable, + C2: Collection, >( - _ left: borrowing C1, - _ right: borrowing C2, - by areEquivalent: (borrowing C1.Element, borrowing C2.Element) -> Bool, + _ left: borrowing E1, + equalTo right: C2, _ message: @autoclosure () -> String = "", trapping: Bool = false, - file: StaticString = #file, + file: StaticString = #filePath, line: UInt = #line ) { - if left.borrowingElementsEqual(right, by: areEquivalent) { return } + var it1 = left.makeBorrowingIterator() + var it2 = right.makeIterator() + var i = 0 + while true { + let next1 = it1.nextSpan(maximumCount: 1) + let next2 = it2.next() + switch (next1.isEmpty, next2) { + case (true, nil): + return + case (true, _?): + _expectFailure( + "Borrowing sequence is shorter than expected", + message, trapping: trapping, file: file, line: line) + return + case (false, nil): + _expectFailure( + "Borrowing sequence is longer than expected", + message, trapping: trapping, file: file, line: line) + return + case (false, let b?): + let a = next1[0].payload + guard a == b else { + _expectFailure( + "Element at offset \(i) '\(a)' is not equal to '\(b)'", + message, trapping: trapping, file: file, line: line) + return + } + } + i += 1 + } +} + +/// Check if `left` contains lifetime tracked instances whose payloads equal +/// the elements in `right`. +@available(SwiftStdlib 5.0, *) +public func expectIterablePayloads< + Payload: Equatable, + E1: BorrowingSequence> & ~Copyable & ~Escapable, + C2: Collection, +>( + _ left: borrowing E1, + equalTo right: C2, + _ message: @autoclosure () -> String = "", + trapping: Bool = false, + file: StaticString = #filePath, + line: UInt = #line +) { + var it1 = left.makeBorrowingIterator() + var it2 = right.makeIterator() + var i = 0 + while true { + let next1 = it1.nextSpan(maximumCount: 1) + let next2 = it2.next() + switch (next1.isEmpty, next2) { + case (true, nil): + return + case (true, _?): + _expectFailure( + "Borrowing sequence is shorter than expected", + message, trapping: trapping, file: file, line: line) + return + case (false, nil): + _expectFailure( + "Borrowing sequence is longer than expected", + message, trapping: trapping, file: file, line: line) + return + case (false, let b?): + let a = next1[0].payload + guard a == b else { + _expectFailure( + "Element at offset \(i) '\(a)' is not equal to '\(b)'", + message, trapping: trapping, file: file, line: line) + return + } + } + i += 1 + } +} +#endif + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +@available(SwiftStdlib 5.0, *) +public func expectIterablesWithEquivalentElements< + S1: BorrowingSequence & ~Copyable & ~Escapable, + S2: BorrowingSequence & ~Copyable & ~Escapable +>( + _ left: borrowing S1, + _ right: borrowing S2, + by areEquivalent: (borrowing S1.Element, borrowing S2.Element) -> Bool, + _ message: @autoclosure () -> String = "", + trapping: Bool = false, + file: StaticString = #filePath, + line: UInt = #line +) { + if left.elementsEqual(right, by: areEquivalent) { return } _expectFailure( "Containers do not have equivalent elements", message, trapping: trapping, file: file, line: line) @@ -117,19 +238,19 @@ public func expectContainersWithEquivalentElements< /// Check if `left` and `right` contain equal elements in the same order. @available(SwiftStdlib 5.0, *) -public func expectContainersWithEqualElements< +public func expectIterablesWithEqualElements< Element: Equatable, - C1: Container & ~Copyable & ~Escapable, - C2: Container & ~Copyable & ~Escapable, + S1: BorrowingSequence & ~Copyable & ~Escapable, + S2: BorrowingSequence & ~Copyable & ~Escapable, >( - _ left: borrowing C1, - _ right: borrowing C2, + _ left: borrowing S1, + _ right: borrowing S2, _ message: @autoclosure () -> String = "", trapping: Bool = false, - file: StaticString = #file, + file: StaticString = #filePath, line: UInt = #line ) { - if left.borrowingElementsEqual(right) { return } + if left.elementsEqual(right) { return } _expectFailure( "Containers do not have equal elements", message, trapping: trapping, file: file, line: line) @@ -137,19 +258,19 @@ public func expectContainersWithEqualElements< /// Check if `left` and `right` contain equal elements in the same order. @available(SwiftStdlib 5.0, *) -public func expectContainerContents< +public func expectIterableContents< Element: Equatable, - C1: Container & ~Copyable & ~Escapable, + S1: BorrowingSequence & ~Copyable & ~Escapable, C2: Collection, >( - _ left: borrowing C1, + _ left: borrowing S1, equalTo right: C2, _ message: @autoclosure () -> String = "", trapping: Bool = false, - file: StaticString = #file, + file: StaticString = #filePath, line: UInt = #line ) { - var it1 = left.startBorrowIteration() + var it1 = left.makeBorrowingIterator() var it2 = right.makeIterator() while true { let span = it1.nextSpan() @@ -179,19 +300,20 @@ public func expectContainerContents< /// Check if `left` and `right` contain equal elements in the same order. @available(SwiftStdlib 5.0, *) -public func expectContainerContents< - C1: Container & ~Copyable & ~Escapable, +public func expectIterableContents< + S1: BorrowingSequence & ~Copyable & ~Escapable, C2: Collection, >( - _ left: borrowing C1, + _ left: borrowing S1, equivalentTo right: C2, - by areEquivalent: (borrowing C1.Element, C2.Element) -> Bool, + by areEquivalent: (borrowing S1.Element, C2.Element) -> Bool, + printer: (borrowing S1.Element) -> String, _ message: @autoclosure () -> String = "", trapping: Bool = false, - file: StaticString = #file, + file: StaticString = #filePath, line: UInt = #line ) { - var it1 = left.startBorrowIteration() + var it1 = left.makeBorrowingIterator() var it2 = right.makeIterator() var offset = 0 while true { diff --git a/Tests/_CollectionsTestSupport/AssertionContexts/Assertions.swift b/Tests/_CollectionsTestSupport/AssertionContexts/Assertions.swift index 403991cc..8390202d 100644 --- a/Tests/_CollectionsTestSupport/AssertionContexts/Assertions.swift +++ b/Tests/_CollectionsTestSupport/AssertionContexts/Assertions.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift.org open source project // -// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors +// Copyright (c) 2014 - 2026 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information @@ -34,6 +34,7 @@ public func _expectFailure( file: StaticString, line: UInt ) { + guard TestContext.incrementFailureCount() else { return } let message = message() XCTFail( TestContext.currentTrace( @@ -158,6 +159,28 @@ public func expectEquivalent( message, trapping: trapping, file: file, line: line) } +#if compiler(>=6.2) +// FIXME: Remove when CustomStringConvertible starts supporting +// noncopyable/nonescapable types. +public func expectEquivalent< + A: ~Copyable & ~Escapable, + B +>( + _ left: borrowing A, _ right: borrowing B, + by areEquivalent: (borrowing A, borrowing B) -> Bool, + printer: (borrowing A) -> String, + _ message: @autoclosure () -> String = "", + trapping: Bool = false, + file: StaticString = #filePath, + line: UInt = #line +) { + if areEquivalent(left, right) { return } + _expectFailure( + "'\(printer(left))' is not equivalent to '\(right)'", + message, trapping: trapping, file: file, line: line) +} +#endif + public func expectEquivalent( _ left: A?, _ right: B?, by areEquivalent: (A, B) -> Bool, @@ -404,13 +427,13 @@ public func expectThrows( } } -public func expectThrows( +public func expectThrows( _ message: @autoclosure () -> String = "", trapping: Bool = false, file: StaticString = #filePath, line: UInt = #line, - body: () throws -> T, - errorHandler: (Error) -> Void = { _ in } + body: () throws(E) -> T, + errorHandler: (E) -> Void = { _ in } ) { do { let result = try body() diff --git a/Tests/_CollectionsTestSupport/AssertionContexts/TestContext.swift b/Tests/_CollectionsTestSupport/AssertionContexts/TestContext.swift index 3b39ef7d..22df2600 100644 --- a/Tests/_CollectionsTestSupport/AssertionContexts/TestContext.swift +++ b/Tests/_CollectionsTestSupport/AssertionContexts/TestContext.swift @@ -14,6 +14,7 @@ import XCTest public final class TestContext { internal var _nextStateId = 0 internal var _nextIndexId = 0 + internal var _failureCount = 0 /// Stack of labels with associated source positions. /// Useful for tracking failed cases in combinatorial tests. @@ -32,6 +33,10 @@ extension TestContext { } return current } + + /// Don't report more than this number of failures per test, to avoid + /// overwhelming Xcode's display engine. + public static var maximumFailureCount: Int { 100 } public static func pushNew() -> TestContext { let context = TestContext() @@ -40,12 +45,12 @@ extension TestContext { } public static func push(_ context: TestContext) { - precondition(_current == nil, "Can't nest test contexts") + precondition(_current == nil, "Cannot nest test contexts") _current = context } public static func pop(_ context: TestContext) { - precondition(_current === context, "Can't pop mismatching context") + precondition(_current === context, "Cannot pop mismatching context") _current = nil } } @@ -191,6 +196,16 @@ extension TestContext { for trace in _trace { result += " - \(trace.label)\n" } + if _failureCount == Self.maximumFailureCount { + result += "*** Failure limit reached; additional failures will be suppressed ***" + } + return result + } + + public static func incrementFailureCount() -> Bool { + guard let context = _current else { return true } + let result = context._failureCount < maximumFailureCount + context._failureCount += 1 return result } diff --git a/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift b/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift index 032ec094..e748975d 100644 --- a/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift +++ b/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift @@ -11,21 +11,25 @@ #if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW import XCTest +#if COLLECTIONS_SINGLE_MODULE +import Collections +#else import ContainersPreview +#endif @available(SwiftStdlib 5.0, *) @inlinable -public func checkContainer< - C: Container & ~Copyable & ~Escapable, - Expected: Sequence +public func checkIterable< + S: BorrowingSequence & ~Copyable & ~Escapable, + Expected: Sequence >( - _ container: borrowing C, + _ iterable: borrowing S, expectedContents: Expected, file: StaticString = #filePath, line: UInt = #line -) where C.Element: Equatable { - checkContainer( - container, +) where S.Element: Equatable { + checkIterable( + iterable, expectedContents: expectedContents, by: ==, file: file, line: line) @@ -33,32 +37,39 @@ public func checkContainer< @available(SwiftStdlib 5.0, *) @inlinable -public func checkContainer< - C: Container & ~Copyable & ~Escapable, - Expected: Sequence +public func checkIterable< + S: BorrowingSequence & ~Copyable & ~Escapable, + Expected: Sequence >( - _ container: borrowing C, + _ iterable: borrowing S, expectedContents: Expected, - by areEquivalent: (C.Element, C.Element) -> Bool, + by areEquivalent: (S.Element, S.Element) -> Bool, file: StaticString = #filePath, line: UInt = #line -) where C.Element: Equatable { - let entry = TestContext.current.push("checkContainer", file: file, line: line) +) where S.Element: Equatable { + let entry = TestContext.current.push("checkIterable", file: file, line: line) defer { TestContext.current.pop(entry) } let expectedContents = Array(expectedContents) - expectEqual(container.isEmpty, expectedContents.isEmpty) - let actualCount = container.count - expectEqual(actualCount, expectedContents.count) + + let estimatedCount = iterable.estimatedCount + switch estimatedCount { + case .exactly(let c): + expectEqual(c, expectedContents.count) + case .infinite: + expectFailure() + case .unknown: + break + } // Check that the spans seem plausibly sized and that the indices are monotonic. let spanShapes: [Range] = { var r: [Range] = [] var pos = 0 - var it = container.startBorrowIteration() + var it = iterable.makeBorrowingIterator() while true { let origPos = pos - let span = it.nextSpan(maximumCount: nil) + let span = it.nextSpan() pos += span.count if span.isEmpty { break @@ -68,16 +79,16 @@ public func checkContainer< return r }() expectEqual( - spanShapes.reduce(into: 0, { $0 += $1.count }), actualCount, + spanShapes.reduce(into: 0, { $0 += $1.count }), expectedContents.count, "Container's count does not match the sum of its spans") // Check that the spans have stable sizes and the expected contents. do { var pos = 0 - var it = container.startBorrowIteration() + var it = iterable.makeBorrowingIterator() var spanIndex = 0 while true { - let span = it.nextSpan(maximumCount: nil) + let span = it.nextSpan() if span.isEmpty { break } expectEqual( span.count, spanShapes[spanIndex].count, @@ -95,7 +106,7 @@ public func checkContainer< // Check that we can iterate one by one. do { var pos = 0 - var it = container.startBorrowIteration() + var it = iterable.makeBorrowingIterator() while true { let span = it.nextSpan(maximumCount: 1) if span.isEmpty { break } @@ -111,7 +122,7 @@ public func checkContainer< // Check that we can iterate with huge maximum counts do { var pos = 0 - var it = container.startBorrowIteration() + var it = iterable.makeBorrowingIterator() var spanIndex = 0 while true { let span = it.nextSpan(maximumCount: Int.max) diff --git a/Tests/_CollectionsTestSupport/MinimalTypes/CustomProducer.swift b/Tests/_CollectionsTestSupport/MinimalTypes/CustomProducer.swift new file mode 100644 index 00000000..75f367f9 --- /dev/null +++ b/Tests/_CollectionsTestSupport/MinimalTypes/CustomProducer.swift @@ -0,0 +1,48 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2025 - 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if COLLECTIONS_SINGLE_MODULE +import Collections +#else +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + +@available(SwiftStdlib 5.0, *) +package struct CustomProducer: ~Copyable { + package let underestimatedCount: Int + package let generator: () throws(ProducerError) -> Element? + + package init( + underestimatedCount: Int = 0, + generatingWith generator: borrowing @escaping () throws(ProducerError) -> Element? + ) { + self.underestimatedCount = underestimatedCount + self.generator = copy generator + } +} + +@available(SwiftStdlib 5.0, *) +extension CustomProducer: Producer where Element: ~Copyable { + package mutating func generate( + into target: inout OutputSpan + ) throws(ProducerError) -> Bool { + while !target.isFull { + guard let next = try generator() else { return false } + target.append(next) + } + return true + } +} + +#endif diff --git a/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift b/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift index b61709f8..bdb9168e 100644 --- a/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift +++ b/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift @@ -22,67 +22,163 @@ import ContainersPreview @available(SwiftStdlib 5.0, *) public struct StaccatoContainer: ~Copyable { internal let _contents: RigidArray - internal let _spanCounts: [Int] - internal let _modulus: Int + internal let _params: _StaccatoParameters public init(contents: consuming RigidArray, spanCounts: [Int]) { // FIXME: Make this take an arbitrary consumable container - precondition(!spanCounts.isEmpty && spanCounts.allSatisfy { $0 > 0 }) self._contents = contents - self._spanCounts = spanCounts - self._modulus = spanCounts.reduce(into: 0, { $0 += $1 }) + self._params = _StaccatoParameters( + count: _contents.count, spanCounts: spanCounts) } } @available(SwiftStdlib 5.0, *) -public struct _StaccatoBorrowIterator: BorrowIteratorProtocol, ~Escapable { - internal let _contents: Span +extension StaccatoContainer { + public init(contents: Array, spanCounts: [Int]) { + self._contents = RigidArray(copying: contents) + self._params = _StaccatoParameters( + count: _contents.count, spanCounts: spanCounts) + } +} + +@available(SwiftStdlib 5.0, *) +package struct _StaccatoParameters { + internal let _count: Int internal let _spanCounts: [Int] internal let _modulus: Int - internal var _offset: Int - @_lifetime(copy contents) - internal init(contents: Span, spanCounts: [Int]) { - self._contents = contents + internal init(count: Int, spanCounts: [Int]) { + precondition(!spanCounts.isEmpty && spanCounts.allSatisfy { $0 > 0 }) + self._count = count self._spanCounts = spanCounts self._modulus = spanCounts.reduce(into: 0, { $0 += $1 }) - self._offset = 0 } - func _spanCoordinates(atOffset offset: Int) -> (spanIndex: Int, spanOffset: Int) { - precondition(offset >= 0 && offset <= _contents.count) - var remainder = offset % _modulus + internal func endOffset( + fromOffset startOffset: Int, + maximumCount: Int + ) -> Int { + precondition(maximumCount > 0) + precondition(startOffset >= 0 && startOffset <= _count) + var cycleOffset = startOffset % _modulus var i = 0 while i < _spanCounts.count { let c = _spanCounts[i] - if remainder < c { break } - remainder -= c + if cycleOffset < c { break } + cycleOffset -= c i += 1 } - return (i, remainder) + let c = _spanCounts[i] + return Swift.min(_count, startOffset + Swift.min(c - cycleOffset, maximumCount)) + } +} + +@available(SwiftStdlib 5.0, *) +public struct _StaccatoBorrowingIterator: BorrowingIteratorProtocol, ~Escapable { + internal let _contents: Span + internal let _params: _StaccatoParameters + internal var _offset: Int + + @_lifetime(copy contents) + internal init(contents: Span, params: _StaccatoParameters) { + self._contents = contents + self._params = params + self._offset = 0 } @_lifetime(copy self) - public mutating func nextSpan(maximumCount: Int?) -> Span { - let (spanIndex, spanOffset) = _spanCoordinates(atOffset: _offset) - let c = _spanCounts[spanIndex] - spanOffset + public mutating func nextSpan(maximumCount: Int) -> Span { + let endOffset = _params.endOffset(fromOffset: _offset, maximumCount: maximumCount) let startOffset = _offset - let endOffset = Swift.min(startOffset + c, _contents.count) _offset = endOffset return _contents.extracting(startOffset ..< endOffset) - } } +@available(SwiftStdlib 5.0, *) +public struct _StaccatoIndex: Comparable { + var _offset: Int + init(_offset: Int) { + self._offset = _offset + } + + public static func ==(left: Self, right: Self) -> Bool { + left._offset == right._offset + } + + public static func <(left: Self, right: Self) -> Bool { + left._offset < right._offset + } +} + +@available(SwiftStdlib 5.0, *) +extension StaccatoContainer: BorrowingSequence where Element: ~Copyable { + public typealias BorrowingIterator = _StaccatoBorrowingIterator // FIXME rdar://150240032 + + public var estimatedCount: EstimatedCount { + .exactly(count) + } + + public func makeBorrowingIterator() -> BorrowingIterator { + BorrowingIterator(contents: _contents.span, params: _params) + } +} @available(SwiftStdlib 5.0, *) extension StaccatoContainer: Container where Element: ~Copyable { - public typealias BorrowIterator = _StaccatoBorrowIterator // FIXME rdar://150240032 + public typealias Index = _StaccatoIndex + public var isEmpty: Bool { _contents.isEmpty } public var count: Int { _contents.count } + + + package func _isValid(_ index: Index) -> Bool { + index._offset >= 0 && index._offset <= count + } - public func startBorrowIteration() -> BorrowIterator { - BorrowIterator(contents: _contents.span, spanCounts: _spanCounts) + public var startIndex: Index { Index(_offset: 0) } + public var endIndex: Index { Index(_offset: _contents.count) } + + public func index(after index: Index) -> Index { + precondition(index._offset >= 0 && index._offset < count) + return Index(_offset: index._offset + 1) + } + + public func index(before index: Index) -> Index { + precondition(index._offset > 0 && index._offset <= count) + return Index(_offset: index._offset - 1) + } + + public func index(_ index: Index, offsetBy n: Int) -> Index { + precondition(index._offset >= 0 && index._offset <= count) + let j = index._offset + n + precondition(j >= 0 && j <= count) + return Index(_offset: j) + } + + public func distance(from start: Index, to end: Index) -> Int { + precondition(_isValid(start) && _isValid(end)) + return end._offset - start._offset + } + + public func formIndex( + _ index: inout Index, offsetBy n: inout Int, limitedBy limit: Index + ) { + precondition(_isValid(index) && _isValid(limit)) + index._offset._advance(by: &n, limitedBy: limit._offset) + precondition(_isValid(index)) + } + + @_lifetime(borrow self) + public func nextSpan( + after index: inout Index, maximumCount: Int + ) -> Span { + precondition(_isValid(index)) + let startOffset = index._offset + let endOffset = _params.endOffset(fromOffset: index._offset, maximumCount: maximumCount) + print("\(startOffset) .-> \(endOffset)") + index._offset = endOffset + return _contents.span.extracting(startOffset ..< endOffset) } } #endif diff --git a/Tests/_CollectionsTestSupport/MinimalTypes/_MinimalCollectionCore.swift b/Tests/_CollectionsTestSupport/MinimalTypes/_MinimalCollectionCore.swift index 291095a3..1f743b45 100644 --- a/Tests/_CollectionsTestSupport/MinimalTypes/_MinimalCollectionCore.swift +++ b/Tests/_CollectionsTestSupport/MinimalTypes/_MinimalCollectionCore.swift @@ -124,7 +124,7 @@ extension _MinimalCollectionCore { func index(after index: MinimalIndex) -> MinimalIndex { assertValidIndex(index) expectTrue(index._offset < count, - "Can't advance beyond endIndex", + "Cannot advance beyond endIndex", trapping: true) return self.index(at: index._offset + 1) } @@ -132,7 +132,7 @@ extension _MinimalCollectionCore { func index(before index: MinimalIndex) -> MinimalIndex { assertValidIndex(index) expectTrue(index._offset > 0, - "Can't advance before startIndex", + "Cannot advance before startIndex", trapping: true) return self.index(at: index._offset - 1) } @@ -140,7 +140,7 @@ extension _MinimalCollectionCore { func formIndex(after index: inout MinimalIndex) { assertValidIndex(index) expectTrue(index._offset < count, - "Can't advance beyond endIndex", + "Cannot advance beyond endIndex", trapping: true) index._offset += 1 } @@ -148,7 +148,7 @@ extension _MinimalCollectionCore { func formIndex(before index: inout MinimalIndex) { assertValidIndex(index) expectTrue(index._offset > 0, - "Can't advance before startIndex", + "Cannot advance before startIndex", trapping: true) index._offset -= 1 } @@ -165,10 +165,10 @@ extension _MinimalCollectionCore { ) -> MinimalIndex { assertValidIndex(index) expectTrue(index._offset + n >= 0, - "Can't advance before startIndex", + "Cannot advance before startIndex", trapping: true) expectTrue(index._offset + n <= count, - "Can't advance after endIndex", + "Cannot advance after endIndex", trapping: true) return self.index(at: index._offset + n) } @@ -291,7 +291,7 @@ extension _MinimalCollectionCore { mutating func removeFirst() -> Element { expectTrue( count > 0, - "Can't remove first element of an empty collection", + "Cannot remove first element of an empty collection", trapping: true) ensureUniqueState() state.remove(count: 1, at: 0) @@ -301,11 +301,11 @@ extension _MinimalCollectionCore { mutating func removeFirst(_ n: Int) { expectTrue( n >= 0, - "Can't remove a negative number of elements", + "Cannot remove a negative number of elements", trapping: true) expectTrue( n <= count, - "Can't remove more elements than there are in the collection", + "Cannot remove more elements than there are in the collection", trapping: true) ensureUniqueState() state.remove(count: n, at: 0) @@ -315,7 +315,7 @@ extension _MinimalCollectionCore { public mutating func _customRemoveLast() -> Element? { expectTrue( !isEmpty, - "Can't remove last element of an empty collection", + "Cannot remove last element of an empty collection", trapping: true) ensureUniqueState() state.remove(count: 1, at: state.count) @@ -325,11 +325,11 @@ extension _MinimalCollectionCore { public mutating func _customRemoveLast(_ n: Int) -> Bool { expectTrue( n >= 0, - "Can't remove a negative number of elements", + "Cannot remove a negative number of elements", trapping: true) expectTrue( count >= n, - "Can't remove more elements than there are in the collection", + "Cannot remove more elements than there are in the collection", trapping: true) elements.removeLast(n) ensureUniqueState() diff --git a/Tests/_CollectionsTestSupport/Utilities/LifetimeTracked.swift b/Tests/_CollectionsTestSupport/Utilities/LifetimeTracked.swift index b17dbef8..0c7ec3b5 100644 --- a/Tests/_CollectionsTestSupport/Utilities/LifetimeTracked.swift +++ b/Tests/_CollectionsTestSupport/Utilities/LifetimeTracked.swift @@ -32,7 +32,7 @@ public class LifetimeTracked { public let payload: Payload public init(_ payload: Payload, for tracker: LifetimeTracker) { - tracker.instances += 1 + tracker._instances += 1 tracker._nextSerialNumber += 1 self.tracker = tracker self.serialNumber = tracker._nextSerialNumber @@ -41,7 +41,7 @@ public class LifetimeTracked { deinit { precondition(serialNumber != 0, "Double deinit") - tracker.instances -= 1 + tracker._instances -= 1 serialNumber = -serialNumber } } diff --git a/Tests/_CollectionsTestSupport/Utilities/LifetimeTrackedStruct.swift b/Tests/_CollectionsTestSupport/Utilities/LifetimeTrackedStruct.swift index b1b32aae..6c961f98 100644 --- a/Tests/_CollectionsTestSupport/Utilities/LifetimeTrackedStruct.swift +++ b/Tests/_CollectionsTestSupport/Utilities/LifetimeTrackedStruct.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift.org open source project // -// Copyright (c) 2025 Apple Inc. and the Swift project authors +// Copyright (c) 2025 - 2026 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information @@ -23,22 +23,74 @@ /// } /// } /// } +@frozen public struct LifetimeTrackedStruct: ~Copyable { public let tracker: LifetimeTracker + + @usableFromInline internal var serialNumber: Int = 0 + public var payload: Payload + @inlinable public init(_ payload: consuming Payload, for tracker: LifetimeTracker) { - tracker.instances += 1 + tracker._instances += 1 tracker._nextSerialNumber += 1 self.tracker = tracker self.serialNumber = tracker._nextSerialNumber self.payload = payload } + public init(copying payload: Payload, for tracker: LifetimeTracker) + where Payload: Copyable + { + tracker._instances += 1 + tracker._nextSerialNumber += 1 + self.tracker = tracker + self.serialNumber = tracker._nextSerialNumber + self.payload = payload + } + + @inlinable deinit { precondition(serialNumber != 0, "Double deinit") - tracker.instances -= 1 + tracker._instances -= 1 + // Can't mutate in deinit yet + // serialNumber = -serialNumber + } +} + +#if compiler(>=6.2) +extension LifetimeTrackedStruct: TestPrintable where Payload: TestPrintable & ~Copyable { + public var testDescription: String { + return "\(payload.testDescription)" + } +} +#endif + +extension LifetimeTrackedStruct/*: Equatable*/ where Payload: Equatable /*& ~Copyable*/ { + public static func == (left: borrowing Self, right: borrowing Self) -> Bool { + return left.payload == right.payload + } +} + +extension LifetimeTrackedStruct/*: Hashable*/ where Payload: Hashable /*& ~Copyable*/ { + public func _rawHashValue(seed: Int) -> Int { + payload._rawHashValue(seed: seed) + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(payload) + } + + public var hashValue: Int { + payload.hashValue + } +} + +extension LifetimeTrackedStruct/*: Comparable*/ where Payload: Comparable /*& ~Copyable*/ { + public static func < (left: borrowing Self, right: borrowing Self) -> Bool { + return left.payload < right.payload } } diff --git a/Tests/_CollectionsTestSupport/Utilities/LifetimeTracker.swift b/Tests/_CollectionsTestSupport/Utilities/LifetimeTracker.swift index a938d3c2..af68d59f 100644 --- a/Tests/_CollectionsTestSupport/Utilities/LifetimeTracker.swift +++ b/Tests/_CollectionsTestSupport/Utilities/LifetimeTracker.swift @@ -10,6 +10,14 @@ // //===----------------------------------------------------------------------===// +#if COLLECTIONS_SINGLE_MODULE +import Collections +#else +import InternalCollectionsUtilities +import ContainersPreview +import BasicContainers +#endif + /// Tracks the life times of `LifetimeTracked` instances, providing a method /// to validate checkpoints where no instances should exist. /// @@ -18,14 +26,20 @@ /// from multiple concurrent threads (or reentrantly) will lead to /// exclusivity violations and therefore undefined behavior. public class LifetimeTracker { - public internal(set) var instances = 0 - var _nextSerialNumber = 0 + @usableFromInline + package var _instances = 0 + + @usableFromInline + package var _nextSerialNumber = 0 public init() {} deinit { check() } + + @inlinable + public var instances: Int { _instances } public func check(file: StaticString = #filePath, line: UInt = #line) { expectEqual(instances, 0, @@ -47,6 +61,22 @@ public class LifetimeTracker { return items.map { LifetimeTracked($0, for: self) } } +#if compiler(>=6.2) + @available(SwiftStdlib 5.0, *) + public func structInstances( + count: Int, + generator: (Int) -> Element + ) -> RigidArray> { + var i = 0 + return RigidArray>(capacity: count) { span in + while i < count, !span.isFull { + span.append(LifetimeTrackedStruct(copying: generator(i), for: self)) + i += 1 + } + } + } +#endif + public func instances( for items: S, by transform: (S.Element) -> T ) -> [LifetimeTracked] { diff --git a/Xcode/Collections.xcodeproj/project.pbxproj b/Xcode/Collections.xcodeproj/project.pbxproj index 97c610ec..b24fe715 100644 --- a/Xcode/Collections.xcodeproj/project.pbxproj +++ b/Xcode/Collections.xcodeproj/project.pbxproj @@ -7,9 +7,64 @@ objects = { /* Begin PBXBuildFile section */ - 7D48BCD12E51524200D7F6F7 /* InputSpan.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCCB2E51524200D7F6F7 /* InputSpan.swift */; }; - 7D48BCD32E51524200D7F6F7 /* Box.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCC82E51524200D7F6F7 /* Box.swift */; }; - 7D48BCD62E51524200D7F6F7 /* Shared.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCCD2E51524200D7F6F7 /* Shared.swift */; }; + 7D2A77262F27F1D1005780C7 /* Span+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77252F27F1D1005780C7 /* Span+Extras.swift */; }; + 7D2A77382F27F1E4005780C7 /* BorrowingSequence+Utilities.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A772D2F27F1E4005780C7 /* BorrowingSequence+Utilities.swift */; }; + 7D2A77392F27F1E4005780C7 /* Box.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77332F27F1E4005780C7 /* Box.swift */; }; + 7D2A773A2F27F1E4005780C7 /* Drain.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A772F2F27F1E4005780C7 /* Drain.swift */; }; + 7D2A773B2F27F1E4005780C7 /* Container.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A772E2F27F1E4005780C7 /* Container.swift */; }; + 7D2A773C2F27F1E4005780C7 /* TemporaryAllocation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77282F27F1E4005780C7 /* TemporaryAllocation.swift */; }; + 7D2A773D2F27F1E4005780C7 /* BorrowingSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A772B2F27F1E4005780C7 /* BorrowingSequence.swift */; }; + 7D2A773E2F27F1E4005780C7 /* BorrowingSequence+Standard Conformances.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A772C2F27F1E4005780C7 /* BorrowingSequence+Standard Conformances.swift */; }; + 7D2A773F2F27F1E4005780C7 /* Borrow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77322F27F1E4005780C7 /* Borrow.swift */; }; + 7D2A77402F27F1E4005780C7 /* BorrowingIteratorProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A772A2F27F1E4005780C7 /* BorrowingIteratorProtocol.swift */; }; + 7D2A77412F27F1E4005780C7 /* Inout.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77342F27F1E4005780C7 /* Inout.swift */; }; + 7D2A77422F27F1E4005780C7 /* OutputSpan+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77272F27F1E4005780C7 /* OutputSpan+Extras.swift */; }; + 7D2A77432F27F1E4005780C7 /* Shared.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77362F27F1E4005780C7 /* Shared.swift */; }; + 7D2A77442F27F1E4005780C7 /* InputSpan.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77352F27F1E4005780C7 /* InputSpan.swift */; }; + 7D2A77452F27F1E4005780C7 /* Producer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77302F27F1E4005780C7 /* Producer.swift */; }; + 7D2A77492F27F271005780C7 /* CustomProducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77482F27F271005780C7 /* CustomProducer.swift */; }; + 7D2A774D2F27F285005780C7 /* RigidDequeCrashTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A774A2F27F285005780C7 /* RigidDequeCrashTests.swift */; }; + 7D2A774E2F27F285005780C7 /* UniqueDequeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A774C2F27F285005780C7 /* UniqueDequeTests.swift */; }; + 7D2A774F2F27F285005780C7 /* RigidDequeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A774B2F27F285005780C7 /* RigidDequeTests.swift */; }; + 7D2A77782F27F2BF005780C7 /* Deque._Storage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77552F27F2BF005780C7 /* Deque._Storage.swift */; }; + 7D2A77792F27F2BF005780C7 /* RigidDeque+Prepend.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77682F27F2BF005780C7 /* RigidDeque+Prepend.swift */; }; + 7D2A777A2F27F2BF005780C7 /* UniqueDeque+Consumption.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A776F2F27F2BF005780C7 /* UniqueDeque+Consumption.swift */; }; + 7D2A777B2F27F2BF005780C7 /* _UnsafeDequeHandle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77502F27F2BF005780C7 /* _UnsafeDequeHandle.swift */; }; + 7D2A777C2F27F2BF005780C7 /* _UnsafeDequeSegments.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77512F27F2BF005780C7 /* _UnsafeDequeSegments.swift */; }; + 7D2A777D2F27F2BF005780C7 /* RigidDeque+Append.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77622F27F2BF005780C7 /* RigidDeque+Append.swift */; }; + 7D2A777E2F27F2BF005780C7 /* Deque+Hashable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A775E2F27F2BF005780C7 /* Deque+Hashable.swift */; }; + 7D2A777F2F27F2BF005780C7 /* RigidDeque+Container.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77642F27F2BF005780C7 /* RigidDeque+Container.swift */; }; + 7D2A77802F27F2BF005780C7 /* Deque.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77542F27F2BF005780C7 /* Deque.swift */; }; + 7D2A77812F27F2BF005780C7 /* UniqueDeque+Append.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A776E2F27F2BF005780C7 /* UniqueDeque+Append.swift */; }; + 7D2A77822F27F2BF005780C7 /* UniqueDeque+Initializers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77722F27F2BF005780C7 /* UniqueDeque+Initializers.swift */; }; + 7D2A77832F27F2BF005780C7 /* Deque+Equatable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A775B2F27F2BF005780C7 /* Deque+Equatable.swift */; }; + 7D2A77842F27F2BF005780C7 /* UniqueDeque+Container.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77702F27F2BF005780C7 /* UniqueDeque+Container.swift */; }; + 7D2A77852F27F2BF005780C7 /* RigidDeque+Initializers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77662F27F2BF005780C7 /* RigidDeque+Initializers.swift */; }; + 7D2A77862F27F2BF005780C7 /* RigidDeque+Consumption.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77632F27F2BF005780C7 /* RigidDeque+Consumption.swift */; }; + 7D2A77872F27F2BF005780C7 /* Deque._UnsafeHandle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77562F27F2BF005780C7 /* Deque._UnsafeHandle.swift */; }; + 7D2A77882F27F2BF005780C7 /* Deque+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A775D2F27F2BF005780C7 /* Deque+Extras.swift */; }; + 7D2A77892F27F2BF005780C7 /* UniqueDeque+Removals.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77752F27F2BF005780C7 /* UniqueDeque+Removals.swift */; }; + 7D2A778A2F27F2BF005780C7 /* UniqueDeque+Insertions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77732F27F2BF005780C7 /* UniqueDeque+Insertions.swift */; }; + 7D2A778B2F27F2BF005780C7 /* UniqueDeque+Replacements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77762F27F2BF005780C7 /* UniqueDeque+Replacements.swift */; }; + 7D2A778C2F27F2BF005780C7 /* UniqueDeque+Prepend.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77742F27F2BF005780C7 /* UniqueDeque+Prepend.swift */; }; + 7D2A778D2F27F2BF005780C7 /* UniqueDeque.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A776D2F27F2BF005780C7 /* UniqueDeque.swift */; }; + 7D2A778E2F27F2BF005780C7 /* RigidDeque.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77612F27F2BF005780C7 /* RigidDeque.swift */; }; + 7D2A778F2F27F2BF005780C7 /* Deque+CustomReflectable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77592F27F2BF005780C7 /* Deque+CustomReflectable.swift */; }; + 7D2A77902F27F2BF005780C7 /* RigidDeque+Insertions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77672F27F2BF005780C7 /* RigidDeque+Insertions.swift */; }; + 7D2A77912F27F2BF005780C7 /* RigidDeque+Removals.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77692F27F2BF005780C7 /* RigidDeque+Removals.swift */; }; + 7D2A77922F27F2BF005780C7 /* _DequeBuffer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77522F27F2BF005780C7 /* _DequeBuffer.swift */; }; + 7D2A77932F27F2BF005780C7 /* _DequeBufferHeader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77532F27F2BF005780C7 /* _DequeBufferHeader.swift */; }; + 7D2A77942F27F2BF005780C7 /* Deque+Collection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77582F27F2BF005780C7 /* Deque+Collection.swift */; }; + 7D2A77952F27F2BF005780C7 /* Deque+Codable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77572F27F2BF005780C7 /* Deque+Codable.swift */; }; + 7D2A77962F27F2BF005780C7 /* RigidDeque+Experimental.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77652F27F2BF005780C7 /* RigidDeque+Experimental.swift */; }; + 7D2A77972F27F2BF005780C7 /* Deque+Testing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A775F2F27F2BF005780C7 /* Deque+Testing.swift */; }; + 7D2A77982F27F2BF005780C7 /* RigidDeque+Replacements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A776A2F27F2BF005780C7 /* RigidDeque+Replacements.swift */; }; + 7D2A77992F27F2BF005780C7 /* Deque+Descriptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A775A2F27F2BF005780C7 /* Deque+Descriptions.swift */; }; + 7D2A779A2F27F2BF005780C7 /* RigidDeque+Testing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A776B2F27F2BF005780C7 /* RigidDeque+Testing.swift */; }; + 7D2A779B2F27F2BF005780C7 /* UniqueDeque+Experimental.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77712F27F2BF005780C7 /* UniqueDeque+Experimental.swift */; }; + 7D2A779C2F27F2BF005780C7 /* Deque+ExpressibleByArrayLiteral.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A775C2F27F2BF005780C7 /* Deque+ExpressibleByArrayLiteral.swift */; }; + 7D2A779F2F27F367005780C7 /* InoutTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A779E2F27F367005780C7 /* InoutTests.swift */; }; + 7D2A77A02F27F367005780C7 /* BorrowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A779D2F27F367005780C7 /* BorrowTests.swift */; }; 7D48BCDC2E51554900D7F6F7 /* ClassBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCDB2E51554900D7F6F7 /* ClassBox.swift */; }; 7D48BCDF2E51558700D7F6F7 /* TestPrintable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCDD2E51558700D7F6F7 /* TestPrintable.swift */; }; 7D48BCE02E51558700D7F6F7 /* LifetimeTrackedStruct.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCDE2E51558700D7F6F7 /* LifetimeTrackedStruct.swift */; }; @@ -17,23 +72,20 @@ 7D48BCF02E51597200D7F6F7 /* Assertions+Containers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCEF2E51597200D7F6F7 /* Assertions+Containers.swift */; }; 7D48BCF22E51599200D7F6F7 /* CheckContainer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCF12E51599200D7F6F7 /* CheckContainer.swift */; }; 7D48BCF42E5159A300D7F6F7 /* StaccatoContainer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCF32E5159A300D7F6F7 /* StaccatoContainer.swift */; }; - 7D6FEE0F2E877870007C1B86 /* RefTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D6FEE0E2E877870007C1B86 /* RefTests.swift */; }; - 7D6FEE102E877870007C1B86 /* MutTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D6FEE0D2E877870007C1B86 /* MutTests.swift */; }; - 7D6FEE162E8778CF007C1B86 /* Mut.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D6FEE142E8778CF007C1B86 /* Mut.swift */; }; - 7D6FEE172E8778CF007C1B86 /* BorrowIteratorProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D6FEE112E8778CF007C1B86 /* BorrowIteratorProtocol.swift */; }; - 7D6FEE182E8778CF007C1B86 /* Container+Utilities.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D6FEE132E8778CF007C1B86 /* Container+Utilities.swift */; }; - 7D6FEE192E8778CF007C1B86 /* Ref.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D6FEE152E8778CF007C1B86 /* Ref.swift */; }; - 7D6FEE1A2E8778CF007C1B86 /* Container.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D6FEE122E8778CF007C1B86 /* Container.swift */; }; - 7D6FEE252E8778F3007C1B86 /* UniqueArray+Append.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D6FEE202E8778F3007C1B86 /* UniqueArray+Append.swift */; }; - 7D6FEE262E8778F3007C1B86 /* RigidArray+Removals.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D6FEE1E2E8778F3007C1B86 /* RigidArray+Removals.swift */; }; - 7D6FEE272E8778F3007C1B86 /* UniqueArray+Removals.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D6FEE232E8778F3007C1B86 /* UniqueArray+Removals.swift */; }; - 7D6FEE282E8778F3007C1B86 /* RigidArray+Replacements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D6FEE1F2E8778F3007C1B86 /* RigidArray+Replacements.swift */; }; - 7D6FEE292E8778F3007C1B86 /* UniqueArray+Replacements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D6FEE242E8778F3007C1B86 /* UniqueArray+Replacements.swift */; }; - 7D6FEE2A2E8778F3007C1B86 /* RigidArray+Append.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D6FEE1B2E8778F3007C1B86 /* RigidArray+Append.swift */; }; - 7D6FEE2B2E8778F3007C1B86 /* RigidArray+Initializers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D6FEE1C2E8778F3007C1B86 /* RigidArray+Initializers.swift */; }; - 7D6FEE2C2E8778F3007C1B86 /* UniqueArray+Insertions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D6FEE222E8778F3007C1B86 /* UniqueArray+Insertions.swift */; }; - 7D6FEE2D2E8778F3007C1B86 /* RigidArray+Insertions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D6FEE1D2E8778F3007C1B86 /* RigidArray+Insertions.swift */; }; - 7D6FEE2E2E8778F3007C1B86 /* UniqueArray+Initializers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D6FEE212E8778F3007C1B86 /* UniqueArray+Initializers.swift */; }; + 7D57A2B82F33FF48002543BD /* RigidArray+Consumption.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D57A2B72F33FF48002543BD /* RigidArray+Consumption.swift */; }; + 7D57A2BA2F340B58002543BD /* UniqueArray+Consumption.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D57A2B92F340B53002543BD /* UniqueArray+Consumption.swift */; }; + 7D57A2BE2F342DEE002543BD /* UniqueArray+Descriptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D57A2BB2F342DEE002543BD /* UniqueArray+Descriptions.swift */; }; + 7D57A2BF2F342DEE002543BD /* UniqueArray+Hashable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D57A2BD2F342DEE002543BD /* UniqueArray+Hashable.swift */; }; + 7D57A2C02F342DEE002543BD /* UniqueArray+Equatable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D57A2BC2F342DEE002543BD /* UniqueArray+Equatable.swift */; }; + 7D57A2C42F342F30002543BD /* RigidDeque+Equatable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D57A2C22F342F30002543BD /* RigidDeque+Equatable.swift */; }; + 7D57A2C52F342F30002543BD /* RigidDeque+Hashable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D57A2C32F342F30002543BD /* RigidDeque+Hashable.swift */; }; + 7D57A2C62F342F30002543BD /* RigidDeque+Descriptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D57A2C12F342F30002543BD /* RigidDeque+Descriptions.swift */; }; + 7D57A2CA2F342F43002543BD /* UniqueDeque+Descriptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D57A2C72F342F43002543BD /* UniqueDeque+Descriptions.swift */; }; + 7D57A2CB2F342F43002543BD /* UniqueDeque+Equatable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D57A2C82F342F43002543BD /* UniqueDeque+Equatable.swift */; }; + 7D57A2CC2F342F43002543BD /* UniqueDeque+Hashable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D57A2C92F342F43002543BD /* UniqueDeque+Hashable.swift */; }; + 7D57A2CE2F343CA9002543BD /* ContainerAlgorithms.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D57A2CD2F343CA2002543BD /* ContainerAlgorithms.swift */; }; + 7D57A2D02F353946002543BD /* RigidArray+Deprecated.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D57A2CF2F35393E002543BD /* RigidArray+Deprecated.swift */; }; + 7D57A2D22F353CA5002543BD /* UniqueArray+Deprecated.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D57A2D12F353CA1002543BD /* UniqueArray+Deprecated.swift */; }; 7D9748D42E9748930098631A /* BigString+Chunk+UTF16.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9748D32E9748930098631A /* BigString+Chunk+UTF16.swift */; }; 7D9748D52E9748930098631A /* BigString+Chunk+UnicodeScalar.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9748D12E9748930098631A /* BigString+Chunk+UnicodeScalar.swift */; }; 7D9748D62E9748930098631A /* BigString+Chunk+Character.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9748CF2E9748930098631A /* BigString+Chunk+Character.swift */; }; @@ -44,6 +96,25 @@ 7D9B859929E4F74400B291CD /* BitArray+LosslessStringConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9B859329E4F74400B291CD /* BitArray+LosslessStringConvertible.swift */; }; 7D9B859A29E4F74400B291CD /* BitArray+RandomBits.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9B859429E4F74400B291CD /* BitArray+RandomBits.swift */; }; 7D9B859B29E4F74400B291CD /* BitArray+ExpressibleByStringLiteral.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9B859529E4F74400B291CD /* BitArray+ExpressibleByStringLiteral.swift */; }; + 7DA23F462F329A2300E4C03A /* RigidArray+Experimental.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DA23F382F329A2300E4C03A /* RigidArray+Experimental.swift */; }; + 7DA23F472F329A2300E4C03A /* UniqueArray.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DA23F3E2F329A2300E4C03A /* UniqueArray.swift */; }; + 7DA23F482F329A2300E4C03A /* RigidArray+Replacements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DA23F3C2F329A2300E4C03A /* RigidArray+Replacements.swift */; }; + 7DA23F492F329A2300E4C03A /* RigidArray+Container.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DA23F372F329A2300E4C03A /* RigidArray+Container.swift */; }; + 7DA23F4A2F329A2300E4C03A /* UniqueArray+Replacements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DA23F442F329A2300E4C03A /* UniqueArray+Replacements.swift */; }; + 7DA23F4B2F329A2300E4C03A /* UniqueArray+Removals.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DA23F432F329A2300E4C03A /* UniqueArray+Removals.swift */; }; + 7DA23F4C2F329A2300E4C03A /* RigidArray+Append.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DA23F362F329A2300E4C03A /* RigidArray+Append.swift */; }; + 7DA23F4D2F329A2300E4C03A /* RigidArray+Removals.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DA23F3B2F329A2300E4C03A /* RigidArray+Removals.swift */; }; + 7DA23F4E2F329A2300E4C03A /* UniqueArray+Initializers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DA23F412F329A2300E4C03A /* UniqueArray+Initializers.swift */; }; + 7DA23F4F2F329A2300E4C03A /* RigidArray+Initializers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DA23F392F329A2300E4C03A /* RigidArray+Initializers.swift */; }; + 7DA23F502F329A2300E4C03A /* RigidArray+Insertions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DA23F3A2F329A2300E4C03A /* RigidArray+Insertions.swift */; }; + 7DA23F512F329A2300E4C03A /* UniqueArray+Append.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DA23F3F2F329A2300E4C03A /* UniqueArray+Append.swift */; }; + 7DA23F522F329A2300E4C03A /* UniqueArray+Experimental.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DA23F402F329A2300E4C03A /* UniqueArray+Experimental.swift */; }; + 7DA23F532F329A2300E4C03A /* UniqueArray+Insertions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DA23F422F329A2300E4C03A /* UniqueArray+Insertions.swift */; }; + 7DA23F542F329A2300E4C03A /* RigidArray.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DA23F352F329A2300E4C03A /* RigidArray.swift */; }; + 7DA23F562F329E9000E4C03A /* UniqueArray+Container.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DA23F552F329E8A00E4C03A /* UniqueArray+Container.swift */; }; + 7DA23F582F32C66300E4C03A /* RigidArray+Equatable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DA23F572F32C65900E4C03A /* RigidArray+Equatable.swift */; }; + 7DA23F5A2F32C68300E4C03A /* RigidArray+Hashable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DA23F592F32C67D00E4C03A /* RigidArray+Hashable.swift */; }; + 7DA23F5C2F32C69100E4C03A /* RigidArray+Descriptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DA23F5B2F32C68B00E4C03A /* RigidArray+Descriptions.swift */; }; 7DAD899E2E8B09C300DD5786 /* UInt+first and last set bit.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DAD899C2E8B09C300DD5786 /* UInt+first and last set bit.swift */; }; 7DAD899F2E8B09C300DD5786 /* UInt+reversed.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DAD899D2E8B09C300DD5786 /* UInt+reversed.swift */; }; 7DAD89A02E8B09C300DD5786 /* FixedWidthInteger+roundUpToPowerOfTwo.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DAD899A2E8B09C300DD5786 /* FixedWidthInteger+roundUpToPowerOfTwo.swift */; }; @@ -59,6 +130,7 @@ 7DAD89B52E8B09EC00DD5786 /* Debugging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DAD89A82E8B09EC00DD5786 /* Debugging.swift */; }; 7DAD89B62E8B09EC00DD5786 /* UnsafeMutableRawBufferPointer+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DAD89AE2E8B09EC00DD5786 /* UnsafeMutableRawBufferPointer+Extras.swift */; }; 7DAD89B72E8B09EC00DD5786 /* UnsafeRawBufferPointer+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DAD89AF2E8B09EC00DD5786 /* UnsafeRawBufferPointer+Extras.swift */; }; + 7DE448452F2D3705005853A7 /* BinaryInteger extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE448442F2D36F9005853A7 /* BinaryInteger extensions.swift */; }; 7DE91B2F29CA6721004483EB /* Collections.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7DE91B2629CA6721004483EB /* Collections.framework */; }; 7DE9200D29CA70F3004483EB /* OrderedDictionary+Equatable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E7529CA70F3004483EB /* OrderedDictionary+Equatable.swift */; }; 7DE9200E29CA70F3004483EB /* OrderedDictionary+ExpressibleByDictionaryLiteral.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E7629CA70F3004483EB /* OrderedDictionary+ExpressibleByDictionaryLiteral.swift */; }; @@ -121,22 +193,7 @@ 7DE9204729CA70F3004483EB /* _HashTable+Testing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EB229CA70F3004483EB /* _HashTable+Testing.swift */; }; 7DE9204829CA70F3004483EB /* _HashTable+CustomStringConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EB329CA70F3004483EB /* _HashTable+CustomStringConvertible.swift */; }; 7DE9204929CA70F3004483EB /* _HashTable+BucketIterator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EB429CA70F3004483EB /* _HashTable+BucketIterator.swift */; }; - 7DE9204B29CA70F3004483EB /* _DequeBuffer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EB729CA70F3004483EB /* _DequeBuffer.swift */; }; - 7DE9204C29CA70F3004483EB /* Deque+Collection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EB829CA70F3004483EB /* Deque+Collection.swift */; }; - 7DE9204E29CA70F3004483EB /* Deque+CustomReflectable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EBA29CA70F3004483EB /* Deque+CustomReflectable.swift */; }; - 7DE9204F29CA70F3004483EB /* Deque.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EBB29CA70F3004483EB /* Deque.swift */; }; 7DE9205029CA70F3004483EB /* _DequeSlot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EBC29CA70F3004483EB /* _DequeSlot.swift */; }; - 7DE9205129CA70F3004483EB /* Deque+Hashable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EBD29CA70F3004483EB /* Deque+Hashable.swift */; }; - 7DE9205229CA70F3004483EB /* _UnsafeWrappedBuffer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EBE29CA70F3004483EB /* _UnsafeWrappedBuffer.swift */; }; - 7DE9205329CA70F3004483EB /* _DequeBufferHeader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EBF29CA70F3004483EB /* _DequeBufferHeader.swift */; }; - 7DE9205529CA70F3004483EB /* Deque+Codable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EC129CA70F3004483EB /* Deque+Codable.swift */; }; - 7DE9205629CA70F3004483EB /* Deque+Testing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EC229CA70F3004483EB /* Deque+Testing.swift */; }; - 7DE9205829CA70F3004483EB /* Deque._UnsafeHandle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EC429CA70F3004483EB /* Deque._UnsafeHandle.swift */; }; - 7DE9205929CA70F3004483EB /* Deque+Descriptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EC529CA70F3004483EB /* Deque+Descriptions.swift */; }; - 7DE9205A29CA70F3004483EB /* Deque+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EC629CA70F3004483EB /* Deque+Extras.swift */; }; - 7DE9205B29CA70F3004483EB /* Deque+ExpressibleByArrayLiteral.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EC729CA70F3004483EB /* Deque+ExpressibleByArrayLiteral.swift */; }; - 7DE9205C29CA70F3004483EB /* Deque+Equatable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EC829CA70F3004483EB /* Deque+Equatable.swift */; }; - 7DE9205D29CA70F4004483EB /* Deque._Storage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EC929CA70F3004483EB /* Deque._Storage.swift */; }; 7DE9205E29CA70F4004483EB /* BigString+Metrics.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91ECD29CA70F3004483EB /* BigString+Metrics.swift */; }; 7DE9205F29CA70F4004483EB /* BigString+Index.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91ECE29CA70F3004483EB /* BigString+Index.swift */; }; 7DE9206029CA70F4004483EB /* BigString+Summary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91ECF29CA70F3004483EB /* BigString+Summary.swift */; }; @@ -431,11 +488,6 @@ 7DEBDB9029CCE44A00ADC226 /* TestContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB2229CCE43600ADC226 /* TestContext.swift */; }; 7DEBDB9129CCE44A00ADC226 /* CollectionTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB2429CCE43600ADC226 /* CollectionTestCase.swift */; }; 7DEBDB9229CCE44A00ADC226 /* StringConvertibleValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB2B29CCE43600ADC226 /* StringConvertibleValue.swift */; }; - 7DEBDB9D29CCE73D00ADC226 /* Collections.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F7B29CA70F3004483EB /* Collections.swift */; }; - A93AC2152E7C841700A824DF /* RigidArray.swift in Sources */ = {isa = PBXBuildFile; fileRef = A93AC2102E7C841700A824DF /* RigidArray.swift */; }; - A93AC2162E7C841700A824DF /* UniqueArray.swift in Sources */ = {isa = PBXBuildFile; fileRef = A93AC2122E7C841700A824DF /* UniqueArray.swift */; }; - A93AC2172E7C841700A824DF /* RigidArray+Experimental.swift in Sources */ = {isa = PBXBuildFile; fileRef = A93AC2112E7C841700A824DF /* RigidArray+Experimental.swift */; }; - A93AC2182E7C841700A824DF /* UniqueArray+Experimental.swift in Sources */ = {isa = PBXBuildFile; fileRef = A93AC2132E7C841700A824DF /* UniqueArray+Experimental.swift */; }; A93AC21E2E7C845300A824DF /* UniqueArrayTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A93AC21C2E7C845300A824DF /* UniqueArrayTests.swift */; }; A93AC21F2E7C845300A824DF /* ArrayLayout.swift in Sources */ = {isa = PBXBuildFile; fileRef = A93AC21A2E7C845300A824DF /* ArrayLayout.swift */; }; A93AC2202E7C845300A824DF /* RigidArrayTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A93AC21B2E7C845300A824DF /* RigidArrayTests.swift */; }; @@ -456,10 +508,65 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ - 7D48BCC82E51524200D7F6F7 /* Box.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Box.swift; sourceTree = ""; }; + 7D2A77252F27F1D1005780C7 /* Span+Extras.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Span+Extras.swift"; sourceTree = ""; }; + 7D2A77272F27F1E4005780C7 /* OutputSpan+Extras.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "OutputSpan+Extras.swift"; sourceTree = ""; }; + 7D2A77282F27F1E4005780C7 /* TemporaryAllocation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TemporaryAllocation.swift; sourceTree = ""; }; + 7D2A772A2F27F1E4005780C7 /* BorrowingIteratorProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BorrowingIteratorProtocol.swift; sourceTree = ""; }; + 7D2A772B2F27F1E4005780C7 /* BorrowingSequence.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BorrowingSequence.swift; sourceTree = ""; }; + 7D2A772C2F27F1E4005780C7 /* BorrowingSequence+Standard Conformances.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BorrowingSequence+Standard Conformances.swift"; sourceTree = ""; }; + 7D2A772D2F27F1E4005780C7 /* BorrowingSequence+Utilities.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BorrowingSequence+Utilities.swift"; sourceTree = ""; }; + 7D2A772E2F27F1E4005780C7 /* Container.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Container.swift; sourceTree = ""; }; + 7D2A772F2F27F1E4005780C7 /* Drain.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Drain.swift; sourceTree = ""; }; + 7D2A77302F27F1E4005780C7 /* Producer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Producer.swift; sourceTree = ""; }; + 7D2A77322F27F1E4005780C7 /* Borrow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Borrow.swift; sourceTree = ""; }; + 7D2A77332F27F1E4005780C7 /* Box.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Box.swift; sourceTree = ""; }; + 7D2A77342F27F1E4005780C7 /* Inout.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Inout.swift; sourceTree = ""; }; + 7D2A77352F27F1E4005780C7 /* InputSpan.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InputSpan.swift; sourceTree = ""; }; + 7D2A77362F27F1E4005780C7 /* Shared.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Shared.swift; sourceTree = ""; }; + 7D2A77482F27F271005780C7 /* CustomProducer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomProducer.swift; sourceTree = ""; }; + 7D2A774A2F27F285005780C7 /* RigidDequeCrashTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RigidDequeCrashTests.swift; sourceTree = ""; }; + 7D2A774B2F27F285005780C7 /* RigidDequeTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RigidDequeTests.swift; sourceTree = ""; }; + 7D2A774C2F27F285005780C7 /* UniqueDequeTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UniqueDequeTests.swift; sourceTree = ""; }; + 7D2A77502F27F2BF005780C7 /* _UnsafeDequeHandle.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = _UnsafeDequeHandle.swift; sourceTree = ""; }; + 7D2A77512F27F2BF005780C7 /* _UnsafeDequeSegments.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = _UnsafeDequeSegments.swift; sourceTree = ""; }; + 7D2A77522F27F2BF005780C7 /* _DequeBuffer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = _DequeBuffer.swift; sourceTree = ""; }; + 7D2A77532F27F2BF005780C7 /* _DequeBufferHeader.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = _DequeBufferHeader.swift; sourceTree = ""; }; + 7D2A77542F27F2BF005780C7 /* Deque.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Deque.swift; sourceTree = ""; }; + 7D2A77552F27F2BF005780C7 /* Deque._Storage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Deque._Storage.swift; sourceTree = ""; }; + 7D2A77562F27F2BF005780C7 /* Deque._UnsafeHandle.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Deque._UnsafeHandle.swift; sourceTree = ""; }; + 7D2A77572F27F2BF005780C7 /* Deque+Codable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Deque+Codable.swift"; sourceTree = ""; }; + 7D2A77582F27F2BF005780C7 /* Deque+Collection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Deque+Collection.swift"; sourceTree = ""; }; + 7D2A77592F27F2BF005780C7 /* Deque+CustomReflectable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Deque+CustomReflectable.swift"; sourceTree = ""; }; + 7D2A775A2F27F2BF005780C7 /* Deque+Descriptions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Deque+Descriptions.swift"; sourceTree = ""; }; + 7D2A775B2F27F2BF005780C7 /* Deque+Equatable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Deque+Equatable.swift"; sourceTree = ""; }; + 7D2A775C2F27F2BF005780C7 /* Deque+ExpressibleByArrayLiteral.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Deque+ExpressibleByArrayLiteral.swift"; sourceTree = ""; }; + 7D2A775D2F27F2BF005780C7 /* Deque+Extras.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Deque+Extras.swift"; sourceTree = ""; }; + 7D2A775E2F27F2BF005780C7 /* Deque+Hashable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Deque+Hashable.swift"; sourceTree = ""; }; + 7D2A775F2F27F2BF005780C7 /* Deque+Testing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Deque+Testing.swift"; sourceTree = ""; }; + 7D2A77612F27F2BF005780C7 /* RigidDeque.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RigidDeque.swift; sourceTree = ""; }; + 7D2A77622F27F2BF005780C7 /* RigidDeque+Append.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidDeque+Append.swift"; sourceTree = ""; }; + 7D2A77632F27F2BF005780C7 /* RigidDeque+Consumption.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidDeque+Consumption.swift"; sourceTree = ""; }; + 7D2A77642F27F2BF005780C7 /* RigidDeque+Container.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidDeque+Container.swift"; sourceTree = ""; }; + 7D2A77652F27F2BF005780C7 /* RigidDeque+Experimental.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidDeque+Experimental.swift"; sourceTree = ""; }; + 7D2A77662F27F2BF005780C7 /* RigidDeque+Initializers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidDeque+Initializers.swift"; sourceTree = ""; }; + 7D2A77672F27F2BF005780C7 /* RigidDeque+Insertions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidDeque+Insertions.swift"; sourceTree = ""; }; + 7D2A77682F27F2BF005780C7 /* RigidDeque+Prepend.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidDeque+Prepend.swift"; sourceTree = ""; }; + 7D2A77692F27F2BF005780C7 /* RigidDeque+Removals.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidDeque+Removals.swift"; sourceTree = ""; }; + 7D2A776A2F27F2BF005780C7 /* RigidDeque+Replacements.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidDeque+Replacements.swift"; sourceTree = ""; }; + 7D2A776B2F27F2BF005780C7 /* RigidDeque+Testing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidDeque+Testing.swift"; sourceTree = ""; }; + 7D2A776D2F27F2BF005780C7 /* UniqueDeque.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UniqueDeque.swift; sourceTree = ""; }; + 7D2A776E2F27F2BF005780C7 /* UniqueDeque+Append.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueDeque+Append.swift"; sourceTree = ""; }; + 7D2A776F2F27F2BF005780C7 /* UniqueDeque+Consumption.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueDeque+Consumption.swift"; sourceTree = ""; }; + 7D2A77702F27F2BF005780C7 /* UniqueDeque+Container.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueDeque+Container.swift"; sourceTree = ""; }; + 7D2A77712F27F2BF005780C7 /* UniqueDeque+Experimental.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueDeque+Experimental.swift"; sourceTree = ""; }; + 7D2A77722F27F2BF005780C7 /* UniqueDeque+Initializers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueDeque+Initializers.swift"; sourceTree = ""; }; + 7D2A77732F27F2BF005780C7 /* UniqueDeque+Insertions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueDeque+Insertions.swift"; sourceTree = ""; }; + 7D2A77742F27F2BF005780C7 /* UniqueDeque+Prepend.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueDeque+Prepend.swift"; sourceTree = ""; }; + 7D2A77752F27F2BF005780C7 /* UniqueDeque+Removals.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueDeque+Removals.swift"; sourceTree = ""; }; + 7D2A77762F27F2BF005780C7 /* UniqueDeque+Replacements.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueDeque+Replacements.swift"; sourceTree = ""; }; + 7D2A779D2F27F367005780C7 /* BorrowTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BorrowTests.swift; sourceTree = ""; }; + 7D2A779E2F27F367005780C7 /* InoutTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InoutTests.swift; sourceTree = ""; }; 7D48BCC92E51524200D7F6F7 /* CMakeLists.txt */ = {isa = PBXFileReference; lastKnownFileType = text; path = CMakeLists.txt; sourceTree = ""; }; - 7D48BCCB2E51524200D7F6F7 /* InputSpan.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InputSpan.swift; sourceTree = ""; }; - 7D48BCCD2E51524200D7F6F7 /* Shared.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Shared.swift; sourceTree = ""; }; 7D48BCDB2E51554900D7F6F7 /* ClassBox.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClassBox.swift; sourceTree = ""; }; 7D48BCDD2E51558700D7F6F7 /* TestPrintable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TestPrintable.swift; sourceTree = ""; }; 7D48BCDE2E51558700D7F6F7 /* LifetimeTrackedStruct.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LifetimeTrackedStruct.swift; sourceTree = ""; }; @@ -468,26 +575,23 @@ 7D48BCF12E51599200D7F6F7 /* CheckContainer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CheckContainer.swift; sourceTree = ""; }; 7D48BCF32E5159A300D7F6F7 /* StaccatoContainer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StaccatoContainer.swift; sourceTree = ""; }; 7D48BCF52E51651900D7F6F7 /* Package@swift-6.0.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = "Package@swift-6.0.swift"; path = "../Package@swift-6.0.swift"; sourceTree = SOURCE_ROOT; }; + 7D57A2B72F33FF48002543BD /* RigidArray+Consumption.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidArray+Consumption.swift"; sourceTree = ""; }; + 7D57A2B92F340B53002543BD /* UniqueArray+Consumption.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueArray+Consumption.swift"; sourceTree = ""; }; + 7D57A2BB2F342DEE002543BD /* UniqueArray+Descriptions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueArray+Descriptions.swift"; sourceTree = ""; }; + 7D57A2BC2F342DEE002543BD /* UniqueArray+Equatable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueArray+Equatable.swift"; sourceTree = ""; }; + 7D57A2BD2F342DEE002543BD /* UniqueArray+Hashable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueArray+Hashable.swift"; sourceTree = ""; }; + 7D57A2C12F342F30002543BD /* RigidDeque+Descriptions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidDeque+Descriptions.swift"; sourceTree = ""; }; + 7D57A2C22F342F30002543BD /* RigidDeque+Equatable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidDeque+Equatable.swift"; sourceTree = ""; }; + 7D57A2C32F342F30002543BD /* RigidDeque+Hashable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidDeque+Hashable.swift"; sourceTree = ""; }; + 7D57A2C72F342F43002543BD /* UniqueDeque+Descriptions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueDeque+Descriptions.swift"; sourceTree = ""; }; + 7D57A2C82F342F43002543BD /* UniqueDeque+Equatable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueDeque+Equatable.swift"; sourceTree = ""; }; + 7D57A2C92F342F43002543BD /* UniqueDeque+Hashable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueDeque+Hashable.swift"; sourceTree = ""; }; + 7D57A2CD2F343CA2002543BD /* ContainerAlgorithms.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContainerAlgorithms.swift; sourceTree = ""; }; + 7D57A2CF2F35393E002543BD /* RigidArray+Deprecated.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidArray+Deprecated.swift"; sourceTree = ""; }; + 7D57A2D12F353CA1002543BD /* UniqueArray+Deprecated.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueArray+Deprecated.swift"; sourceTree = ""; }; 7D5A64D229CCE8CC00CB2595 /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; 7D5A64D329CCEE9A00CB2595 /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; 7D5A64D829CCF0FE00CB2595 /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; - 7D6FEE0D2E877870007C1B86 /* MutTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MutTests.swift; sourceTree = ""; }; - 7D6FEE0E2E877870007C1B86 /* RefTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RefTests.swift; sourceTree = ""; }; - 7D6FEE112E8778CF007C1B86 /* BorrowIteratorProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BorrowIteratorProtocol.swift; sourceTree = ""; }; - 7D6FEE122E8778CF007C1B86 /* Container.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Container.swift; sourceTree = ""; }; - 7D6FEE132E8778CF007C1B86 /* Container+Utilities.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Container+Utilities.swift"; sourceTree = ""; }; - 7D6FEE142E8778CF007C1B86 /* Mut.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Mut.swift; sourceTree = ""; }; - 7D6FEE152E8778CF007C1B86 /* Ref.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Ref.swift; sourceTree = ""; }; - 7D6FEE1B2E8778F3007C1B86 /* RigidArray+Append.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidArray+Append.swift"; sourceTree = ""; }; - 7D6FEE1C2E8778F3007C1B86 /* RigidArray+Initializers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidArray+Initializers.swift"; sourceTree = ""; }; - 7D6FEE1D2E8778F3007C1B86 /* RigidArray+Insertions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidArray+Insertions.swift"; sourceTree = ""; }; - 7D6FEE1E2E8778F3007C1B86 /* RigidArray+Removals.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidArray+Removals.swift"; sourceTree = ""; }; - 7D6FEE1F2E8778F3007C1B86 /* RigidArray+Replacements.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidArray+Replacements.swift"; sourceTree = ""; }; - 7D6FEE202E8778F3007C1B86 /* UniqueArray+Append.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueArray+Append.swift"; sourceTree = ""; }; - 7D6FEE212E8778F3007C1B86 /* UniqueArray+Initializers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueArray+Initializers.swift"; sourceTree = ""; }; - 7D6FEE222E8778F3007C1B86 /* UniqueArray+Insertions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueArray+Insertions.swift"; sourceTree = ""; }; - 7D6FEE232E8778F3007C1B86 /* UniqueArray+Removals.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueArray+Removals.swift"; sourceTree = ""; }; - 7D6FEE242E8778F3007C1B86 /* UniqueArray+Replacements.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueArray+Replacements.swift"; sourceTree = ""; }; 7D6FEE2F2E8880F6007C1B86 /* BasicContainers.docc */ = {isa = PBXFileReference; lastKnownFileType = folder.documentationcatalog; path = BasicContainers.docc; sourceTree = ""; }; 7D6FEE312E88A4B9007C1B86 /* ContainersPreview.docc */ = {isa = PBXFileReference; lastKnownFileType = folder.documentationcatalog; path = ContainersPreview.docc; sourceTree = ""; }; 7D9748CF2E9748930098631A /* BigString+Chunk+Character.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BigString+Chunk+Character.swift"; sourceTree = ""; }; @@ -501,6 +605,25 @@ 7D9B859429E4F74400B291CD /* BitArray+RandomBits.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+RandomBits.swift"; sourceTree = ""; }; 7D9B859529E4F74400B291CD /* BitArray+ExpressibleByStringLiteral.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+ExpressibleByStringLiteral.swift"; sourceTree = ""; }; 7D9B859C29E4F77D00B291CD /* Collections.xctestplan */ = {isa = PBXFileReference; lastKnownFileType = text; path = Collections.xctestplan; sourceTree = ""; }; + 7DA23F352F329A2300E4C03A /* RigidArray.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RigidArray.swift; sourceTree = ""; }; + 7DA23F362F329A2300E4C03A /* RigidArray+Append.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidArray+Append.swift"; sourceTree = ""; }; + 7DA23F372F329A2300E4C03A /* RigidArray+Container.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidArray+Container.swift"; sourceTree = ""; }; + 7DA23F382F329A2300E4C03A /* RigidArray+Experimental.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidArray+Experimental.swift"; sourceTree = ""; }; + 7DA23F392F329A2300E4C03A /* RigidArray+Initializers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidArray+Initializers.swift"; sourceTree = ""; }; + 7DA23F3A2F329A2300E4C03A /* RigidArray+Insertions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidArray+Insertions.swift"; sourceTree = ""; }; + 7DA23F3B2F329A2300E4C03A /* RigidArray+Removals.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidArray+Removals.swift"; sourceTree = ""; }; + 7DA23F3C2F329A2300E4C03A /* RigidArray+Replacements.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidArray+Replacements.swift"; sourceTree = ""; }; + 7DA23F3E2F329A2300E4C03A /* UniqueArray.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UniqueArray.swift; sourceTree = ""; }; + 7DA23F3F2F329A2300E4C03A /* UniqueArray+Append.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueArray+Append.swift"; sourceTree = ""; }; + 7DA23F402F329A2300E4C03A /* UniqueArray+Experimental.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueArray+Experimental.swift"; sourceTree = ""; }; + 7DA23F412F329A2300E4C03A /* UniqueArray+Initializers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueArray+Initializers.swift"; sourceTree = ""; }; + 7DA23F422F329A2300E4C03A /* UniqueArray+Insertions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueArray+Insertions.swift"; sourceTree = ""; }; + 7DA23F432F329A2300E4C03A /* UniqueArray+Removals.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueArray+Removals.swift"; sourceTree = ""; }; + 7DA23F442F329A2300E4C03A /* UniqueArray+Replacements.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueArray+Replacements.swift"; sourceTree = ""; }; + 7DA23F552F329E8A00E4C03A /* UniqueArray+Container.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueArray+Container.swift"; sourceTree = ""; }; + 7DA23F572F32C65900E4C03A /* RigidArray+Equatable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidArray+Equatable.swift"; sourceTree = ""; }; + 7DA23F592F32C67D00E4C03A /* RigidArray+Hashable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidArray+Hashable.swift"; sourceTree = ""; }; + 7DA23F5B2F32C68B00E4C03A /* RigidArray+Descriptions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidArray+Descriptions.swift"; sourceTree = ""; }; 7DAD899A2E8B09C300DD5786 /* FixedWidthInteger+roundUpToPowerOfTwo.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FixedWidthInteger+roundUpToPowerOfTwo.swift"; sourceTree = ""; }; 7DAD899B2E8B09C300DD5786 /* Integer rank.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Integer rank.swift"; sourceTree = ""; }; 7DAD899C2E8B09C300DD5786 /* UInt+first and last set bit.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UInt+first and last set bit.swift"; sourceTree = ""; }; @@ -516,6 +639,12 @@ 7DAD89AD2E8B09EC00DD5786 /* UnsafeMutableBufferPointer+Extras.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UnsafeMutableBufferPointer+Extras.swift"; sourceTree = ""; }; 7DAD89AE2E8B09EC00DD5786 /* UnsafeMutableRawBufferPointer+Extras.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UnsafeMutableRawBufferPointer+Extras.swift"; sourceTree = ""; }; 7DAD89AF2E8B09EC00DD5786 /* UnsafeRawBufferPointer+Extras.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UnsafeRawBufferPointer+Extras.swift"; sourceTree = ""; }; + 7DE448442F2D36F9005853A7 /* BinaryInteger extensions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BinaryInteger extensions.swift"; sourceTree = ""; }; + 7DE448462F2D3940005853A7 /* BitCollections reexports.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BitCollections reexports.swift"; sourceTree = ""; }; + 7DE448472F2D3984005853A7 /* DequeModule reexports.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DequeModule reexports.swift"; sourceTree = ""; }; + 7DE448482F2D39E9005853A7 /* HashTreeCollections reexports.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "HashTreeCollections reexports.swift"; sourceTree = ""; }; + 7DE448492F2D3B48005853A7 /* HeapModule reexports.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "HeapModule reexports.swift"; sourceTree = ""; }; + 7DE4484A2F2D3B74005853A7 /* OrderedCollections reexports.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "OrderedCollections reexports.swift"; sourceTree = ""; }; 7DE91B2629CA6721004483EB /* Collections.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Collections.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 7DE91B2E29CA6721004483EB /* CollectionsTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = CollectionsTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 7DE91E7229CA70F3004483EB /* OrderedCollections.docc */ = {isa = PBXFileReference; lastKnownFileType = folder.documentationcatalog; path = OrderedCollections.docc; sourceTree = ""; }; @@ -582,24 +711,9 @@ 7DE91EB329CA70F3004483EB /* _HashTable+CustomStringConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "_HashTable+CustomStringConvertible.swift"; sourceTree = ""; }; 7DE91EB429CA70F3004483EB /* _HashTable+BucketIterator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "_HashTable+BucketIterator.swift"; sourceTree = ""; }; 7DE91EB529CA70F3004483EB /* CMakeLists.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = CMakeLists.txt; sourceTree = ""; }; - 7DE91EB729CA70F3004483EB /* _DequeBuffer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _DequeBuffer.swift; sourceTree = ""; }; - 7DE91EB829CA70F3004483EB /* Deque+Collection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Deque+Collection.swift"; sourceTree = ""; }; 7DE91EB929CA70F3004483EB /* CMakeLists.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = CMakeLists.txt; sourceTree = ""; }; - 7DE91EBA29CA70F3004483EB /* Deque+CustomReflectable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Deque+CustomReflectable.swift"; sourceTree = ""; }; - 7DE91EBB29CA70F3004483EB /* Deque.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Deque.swift; sourceTree = ""; }; 7DE91EBC29CA70F3004483EB /* _DequeSlot.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _DequeSlot.swift; sourceTree = ""; }; - 7DE91EBD29CA70F3004483EB /* Deque+Hashable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Deque+Hashable.swift"; sourceTree = ""; }; - 7DE91EBE29CA70F3004483EB /* _UnsafeWrappedBuffer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _UnsafeWrappedBuffer.swift; sourceTree = ""; }; - 7DE91EBF29CA70F3004483EB /* _DequeBufferHeader.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _DequeBufferHeader.swift; sourceTree = ""; }; - 7DE91EC129CA70F3004483EB /* Deque+Codable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Deque+Codable.swift"; sourceTree = ""; }; - 7DE91EC229CA70F3004483EB /* Deque+Testing.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Deque+Testing.swift"; sourceTree = ""; }; 7DE91EC329CA70F3004483EB /* DequeModule.docc */ = {isa = PBXFileReference; lastKnownFileType = folder.documentationcatalog; path = DequeModule.docc; sourceTree = ""; }; - 7DE91EC429CA70F3004483EB /* Deque._UnsafeHandle.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Deque._UnsafeHandle.swift; sourceTree = ""; }; - 7DE91EC529CA70F3004483EB /* Deque+Descriptions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Deque+Descriptions.swift"; sourceTree = ""; }; - 7DE91EC629CA70F3004483EB /* Deque+Extras.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Deque+Extras.swift"; sourceTree = ""; }; - 7DE91EC729CA70F3004483EB /* Deque+ExpressibleByArrayLiteral.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Deque+ExpressibleByArrayLiteral.swift"; sourceTree = ""; }; - 7DE91EC829CA70F3004483EB /* Deque+Equatable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Deque+Equatable.swift"; sourceTree = ""; }; - 7DE91EC929CA70F3004483EB /* Deque._Storage.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Deque._Storage.swift; sourceTree = ""; }; 7DE91ECD29CA70F3004483EB /* BigString+Metrics.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+Metrics.swift"; sourceTree = ""; }; 7DE91ECE29CA70F3004483EB /* BigString+Index.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+Index.swift"; sourceTree = ""; }; 7DE91ECF29CA70F3004483EB /* BigString+Summary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+Summary.swift"; sourceTree = ""; }; @@ -733,7 +847,6 @@ 7DE91F7629CA70F3004483EB /* BitArray+Equatable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+Equatable.swift"; sourceTree = ""; }; 7DE91F7829CA70F3004483EB /* BitArray+Testing.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+Testing.swift"; sourceTree = ""; }; 7DE91F7A29CA70F3004483EB /* CMakeLists.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = CMakeLists.txt; sourceTree = ""; }; - 7DE91F7B29CA70F3004483EB /* Collections.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Collections.swift; sourceTree = ""; }; 7DE91F7C29CA70F3004483EB /* Collections.docc */ = {isa = PBXFileReference; lastKnownFileType = folder.documentationcatalog; path = Collections.docc; sourceTree = ""; }; 7DE91FA829CA70F3004483EB /* CMakeLists.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = CMakeLists.txt; sourceTree = ""; }; 7DE91FA929CA70F3004483EB /* HashTreeCollections.docc */ = {isa = PBXFileReference; lastKnownFileType = folder.documentationcatalog; path = HashTreeCollections.docc; sourceTree = ""; }; @@ -917,10 +1030,6 @@ 7DEBDB9829CCE4A600ADC226 /* Shared.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Shared.xcconfig; sourceTree = ""; }; 7DEBDB9929CCE4A600ADC226 /* Collections.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Collections.xcconfig; sourceTree = ""; }; A93AC20F2E7C841700A824DF /* CMakeLists.txt */ = {isa = PBXFileReference; lastKnownFileType = text; path = CMakeLists.txt; sourceTree = ""; }; - A93AC2102E7C841700A824DF /* RigidArray.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RigidArray.swift; sourceTree = ""; }; - A93AC2112E7C841700A824DF /* RigidArray+Experimental.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidArray+Experimental.swift"; sourceTree = ""; }; - A93AC2122E7C841700A824DF /* UniqueArray.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UniqueArray.swift; sourceTree = ""; }; - A93AC2132E7C841700A824DF /* UniqueArray+Experimental.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueArray+Experimental.swift"; sourceTree = ""; }; A93AC21A2E7C845300A824DF /* ArrayLayout.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ArrayLayout.swift; sourceTree = ""; }; A93AC21B2E7C845300A824DF /* RigidArrayTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RigidArrayTests.swift; sourceTree = ""; }; A93AC21C2E7C845300A824DF /* UniqueArrayTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UniqueArrayTests.swift; sourceTree = ""; }; @@ -950,18 +1059,111 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 7D2A77292F27F1E4005780C7 /* Extensions */ = { + isa = PBXGroup; + children = ( + 7D2A77272F27F1E4005780C7 /* OutputSpan+Extras.swift */, + 7D2A77282F27F1E4005780C7 /* TemporaryAllocation.swift */, + ); + path = Extensions; + sourceTree = ""; + }; + 7D2A77312F27F1E4005780C7 /* Protocols */ = { + isa = PBXGroup; + children = ( + 7D2A772A2F27F1E4005780C7 /* BorrowingIteratorProtocol.swift */, + 7D2A772B2F27F1E4005780C7 /* BorrowingSequence.swift */, + 7D2A772C2F27F1E4005780C7 /* BorrowingSequence+Standard Conformances.swift */, + 7D2A772D2F27F1E4005780C7 /* BorrowingSequence+Utilities.swift */, + 7D2A772E2F27F1E4005780C7 /* Container.swift */, + 7D57A2CD2F343CA2002543BD /* ContainerAlgorithms.swift */, + 7D2A772F2F27F1E4005780C7 /* Drain.swift */, + 7D2A77302F27F1E4005780C7 /* Producer.swift */, + ); + path = Protocols; + sourceTree = ""; + }; + 7D2A77372F27F1E4005780C7 /* Types */ = { + isa = PBXGroup; + children = ( + 7D2A77322F27F1E4005780C7 /* Borrow.swift */, + 7D2A77332F27F1E4005780C7 /* Box.swift */, + 7D2A77342F27F1E4005780C7 /* Inout.swift */, + 7D2A77352F27F1E4005780C7 /* InputSpan.swift */, + 7D2A77362F27F1E4005780C7 /* Shared.swift */, + ); + path = Types; + sourceTree = ""; + }; + 7D2A77602F27F2BF005780C7 /* Deque */ = { + isa = PBXGroup; + children = ( + 7D2A77522F27F2BF005780C7 /* _DequeBuffer.swift */, + 7D2A77532F27F2BF005780C7 /* _DequeBufferHeader.swift */, + 7D2A77542F27F2BF005780C7 /* Deque.swift */, + 7D2A77552F27F2BF005780C7 /* Deque._Storage.swift */, + 7D2A77562F27F2BF005780C7 /* Deque._UnsafeHandle.swift */, + 7D2A77572F27F2BF005780C7 /* Deque+Codable.swift */, + 7D2A77582F27F2BF005780C7 /* Deque+Collection.swift */, + 7D2A77592F27F2BF005780C7 /* Deque+CustomReflectable.swift */, + 7D2A775A2F27F2BF005780C7 /* Deque+Descriptions.swift */, + 7D2A775B2F27F2BF005780C7 /* Deque+Equatable.swift */, + 7D2A775C2F27F2BF005780C7 /* Deque+ExpressibleByArrayLiteral.swift */, + 7D2A775D2F27F2BF005780C7 /* Deque+Extras.swift */, + 7D2A775E2F27F2BF005780C7 /* Deque+Hashable.swift */, + 7D2A775F2F27F2BF005780C7 /* Deque+Testing.swift */, + ); + path = Deque; + sourceTree = ""; + }; + 7D2A776C2F27F2BF005780C7 /* RigidDeque */ = { + isa = PBXGroup; + children = ( + 7D2A77612F27F2BF005780C7 /* RigidDeque.swift */, + 7D2A77622F27F2BF005780C7 /* RigidDeque+Append.swift */, + 7D2A77632F27F2BF005780C7 /* RigidDeque+Consumption.swift */, + 7D2A77642F27F2BF005780C7 /* RigidDeque+Container.swift */, + 7D57A2C12F342F30002543BD /* RigidDeque+Descriptions.swift */, + 7D57A2C22F342F30002543BD /* RigidDeque+Equatable.swift */, + 7D2A77652F27F2BF005780C7 /* RigidDeque+Experimental.swift */, + 7D57A2C32F342F30002543BD /* RigidDeque+Hashable.swift */, + 7D2A77662F27F2BF005780C7 /* RigidDeque+Initializers.swift */, + 7D2A77672F27F2BF005780C7 /* RigidDeque+Insertions.swift */, + 7D2A77682F27F2BF005780C7 /* RigidDeque+Prepend.swift */, + 7D2A77692F27F2BF005780C7 /* RigidDeque+Removals.swift */, + 7D2A776A2F27F2BF005780C7 /* RigidDeque+Replacements.swift */, + 7D2A776B2F27F2BF005780C7 /* RigidDeque+Testing.swift */, + ); + path = RigidDeque; + sourceTree = ""; + }; + 7D2A77772F27F2BF005780C7 /* UniqueDeque */ = { + isa = PBXGroup; + children = ( + 7D2A776D2F27F2BF005780C7 /* UniqueDeque.swift */, + 7D2A776E2F27F2BF005780C7 /* UniqueDeque+Append.swift */, + 7D2A776F2F27F2BF005780C7 /* UniqueDeque+Consumption.swift */, + 7D2A77702F27F2BF005780C7 /* UniqueDeque+Container.swift */, + 7D57A2C72F342F43002543BD /* UniqueDeque+Descriptions.swift */, + 7D57A2C82F342F43002543BD /* UniqueDeque+Equatable.swift */, + 7D2A77712F27F2BF005780C7 /* UniqueDeque+Experimental.swift */, + 7D57A2C92F342F43002543BD /* UniqueDeque+Hashable.swift */, + 7D2A77722F27F2BF005780C7 /* UniqueDeque+Initializers.swift */, + 7D2A77732F27F2BF005780C7 /* UniqueDeque+Insertions.swift */, + 7D2A77742F27F2BF005780C7 /* UniqueDeque+Prepend.swift */, + 7D2A77752F27F2BF005780C7 /* UniqueDeque+Removals.swift */, + 7D2A77762F27F2BF005780C7 /* UniqueDeque+Replacements.swift */, + ); + path = UniqueDeque; + sourceTree = ""; + }; 7D48BCCE2E51524200D7F6F7 /* ContainersPreview */ = { isa = PBXGroup; children = ( - 7D6FEE112E8778CF007C1B86 /* BorrowIteratorProtocol.swift */, - 7D48BCC82E51524200D7F6F7 /* Box.swift */, + 7D2A77292F27F1E4005780C7 /* Extensions */, + 7D2A77312F27F1E4005780C7 /* Protocols */, + 7D2A77372F27F1E4005780C7 /* Types */, 7D48BCC92E51524200D7F6F7 /* CMakeLists.txt */, - 7D6FEE122E8778CF007C1B86 /* Container.swift */, - 7D6FEE132E8778CF007C1B86 /* Container+Utilities.swift */, - 7D48BCCB2E51524200D7F6F7 /* InputSpan.swift */, - 7D6FEE142E8778CF007C1B86 /* Mut.swift */, - 7D6FEE152E8778CF007C1B86 /* Ref.swift */, - 7D48BCCD2E51524200D7F6F7 /* Shared.swift */, 7D6FEE312E88A4B9007C1B86 /* ContainersPreview.docc */, ); path = ContainersPreview; @@ -970,13 +1172,53 @@ 7D48BCE82E5158A100D7F6F7 /* ContainersTests */ = { isa = PBXGroup; children = ( - 7D6FEE0D2E877870007C1B86 /* MutTests.swift */, - 7D6FEE0E2E877870007C1B86 /* RefTests.swift */, + 7D2A779D2F27F367005780C7 /* BorrowTests.swift */, + 7D2A779E2F27F367005780C7 /* InoutTests.swift */, 7D48BCE62E5158A100D7F6F7 /* BoxTests.swift */, ); path = ContainersTests; sourceTree = ""; }; + 7DA23F3D2F329A2300E4C03A /* RigidArray */ = { + isa = PBXGroup; + children = ( + 7DA23F352F329A2300E4C03A /* RigidArray.swift */, + 7DA23F362F329A2300E4C03A /* RigidArray+Append.swift */, + 7D57A2B72F33FF48002543BD /* RigidArray+Consumption.swift */, + 7DA23F372F329A2300E4C03A /* RigidArray+Container.swift */, + 7DA23F5B2F32C68B00E4C03A /* RigidArray+Descriptions.swift */, + 7DA23F572F32C65900E4C03A /* RigidArray+Equatable.swift */, + 7DA23F382F329A2300E4C03A /* RigidArray+Experimental.swift */, + 7DA23F592F32C67D00E4C03A /* RigidArray+Hashable.swift */, + 7DA23F392F329A2300E4C03A /* RigidArray+Initializers.swift */, + 7DA23F3A2F329A2300E4C03A /* RigidArray+Insertions.swift */, + 7DA23F3B2F329A2300E4C03A /* RigidArray+Removals.swift */, + 7DA23F3C2F329A2300E4C03A /* RigidArray+Replacements.swift */, + 7D57A2CF2F35393E002543BD /* RigidArray+Deprecated.swift */, + ); + path = RigidArray; + sourceTree = ""; + }; + 7DA23F452F329A2300E4C03A /* UniqueArray */ = { + isa = PBXGroup; + children = ( + 7DA23F3E2F329A2300E4C03A /* UniqueArray.swift */, + 7DA23F3F2F329A2300E4C03A /* UniqueArray+Append.swift */, + 7D57A2B92F340B53002543BD /* UniqueArray+Consumption.swift */, + 7DA23F552F329E8A00E4C03A /* UniqueArray+Container.swift */, + 7D57A2BB2F342DEE002543BD /* UniqueArray+Descriptions.swift */, + 7D57A2BC2F342DEE002543BD /* UniqueArray+Equatable.swift */, + 7DA23F402F329A2300E4C03A /* UniqueArray+Experimental.swift */, + 7D57A2BD2F342DEE002543BD /* UniqueArray+Hashable.swift */, + 7DA23F412F329A2300E4C03A /* UniqueArray+Initializers.swift */, + 7DA23F422F329A2300E4C03A /* UniqueArray+Insertions.swift */, + 7DA23F432F329A2300E4C03A /* UniqueArray+Removals.swift */, + 7DA23F442F329A2300E4C03A /* UniqueArray+Replacements.swift */, + 7D57A2D12F353CA1002543BD /* UniqueArray+Deprecated.swift */, + ); + path = UniqueArray; + sourceTree = ""; + }; 7DE91B1C29CA6721004483EB = { isa = PBXGroup; children = ( @@ -1008,11 +1250,11 @@ 7DE91E7029CA70F3004483EB /* Sources */ = { isa = PBXGroup; children = ( + 7DE91F7929CA70F3004483EB /* Collections */, A93AC2142E7C841700A824DF /* BasicContainers */, 7DE91F2229CA70F3004483EB /* InternalCollectionsUtilities */, 7D48BCCE2E51524200D7F6F7 /* ContainersPreview */, 7DE91F3929CA70F3004483EB /* BitCollections */, - 7DE91F7929CA70F3004483EB /* Collections */, 7DE91EB629CA70F3004483EB /* DequeModule */, 7DE91FA729CA70F3004483EB /* HashTreeCollections */, 7DE9200229CA70F3004483EB /* HeapModule */, @@ -1130,22 +1372,12 @@ 7DE91EB629CA70F3004483EB /* DequeModule */ = { isa = PBXGroup; children = ( - 7DE91EB729CA70F3004483EB /* _DequeBuffer.swift */, - 7DE91EBF29CA70F3004483EB /* _DequeBufferHeader.swift */, + 7D2A77602F27F2BF005780C7 /* Deque */, + 7D2A776C2F27F2BF005780C7 /* RigidDeque */, + 7D2A77772F27F2BF005780C7 /* UniqueDeque */, 7DE91EBC29CA70F3004483EB /* _DequeSlot.swift */, - 7DE91EBE29CA70F3004483EB /* _UnsafeWrappedBuffer.swift */, - 7DE91EC929CA70F3004483EB /* Deque._Storage.swift */, - 7DE91EC429CA70F3004483EB /* Deque._UnsafeHandle.swift */, - 7DE91EBB29CA70F3004483EB /* Deque.swift */, - 7DE91EC129CA70F3004483EB /* Deque+Codable.swift */, - 7DE91EB829CA70F3004483EB /* Deque+Collection.swift */, - 7DE91EBA29CA70F3004483EB /* Deque+CustomReflectable.swift */, - 7DE91EC529CA70F3004483EB /* Deque+Descriptions.swift */, - 7DE91EC829CA70F3004483EB /* Deque+Equatable.swift */, - 7DE91EC729CA70F3004483EB /* Deque+ExpressibleByArrayLiteral.swift */, - 7DE91EC629CA70F3004483EB /* Deque+Extras.swift */, - 7DE91EBD29CA70F3004483EB /* Deque+Hashable.swift */, - 7DE91EC229CA70F3004483EB /* Deque+Testing.swift */, + 7D2A77502F27F2BF005780C7 /* _UnsafeDequeHandle.swift */, + 7D2A77512F27F2BF005780C7 /* _UnsafeDequeSegments.swift */, 7DE91EC329CA70F3004483EB /* DequeModule.docc */, 7DE91EB929CA70F3004483EB /* CMakeLists.txt */, ); @@ -1337,6 +1569,7 @@ 7DAD89A92E8B09EC00DD5786 /* Descriptions.swift */, 7DAD89AA2E8B09EC00DD5786 /* LifetimeOverride.swift */, 7DAD89AB2E8B09EC00DD5786 /* RandomAccessCollection+Offsets.swift */, + 7D2A77252F27F1D1005780C7 /* Span+Extras.swift */, 7DAD89AC2E8B09EC00DD5786 /* UnsafeBufferPointer+Extras.swift */, 7DAD89AD2E8B09EC00DD5786 /* UnsafeMutableBufferPointer+Extras.swift */, 7DAD89AE2E8B09EC00DD5786 /* UnsafeMutableRawBufferPointer+Extras.swift */, @@ -1433,6 +1666,7 @@ 7DE91F7029CA70F3004483EB /* BitArray+RangeReplaceableCollection.swift */, 7D9B859129E4F74400B291CD /* BitArray+Shifts.swift */, 7DE91F7829CA70F3004483EB /* BitArray+Testing.swift */, + 7DE448442F2D36F9005853A7 /* BinaryInteger extensions.swift */, ); path = BitArray; sourceTree = ""; @@ -1440,9 +1674,13 @@ 7DE91F7929CA70F3004483EB /* Collections */ = { isa = PBXGroup; children = ( - 7DE91F7B29CA70F3004483EB /* Collections.swift */, - 7DE91F7C29CA70F3004483EB /* Collections.docc */, + 7DE448462F2D3940005853A7 /* BitCollections reexports.swift */, + 7DE448472F2D3984005853A7 /* DequeModule reexports.swift */, + 7DE448482F2D39E9005853A7 /* HashTreeCollections reexports.swift */, + 7DE448492F2D3B48005853A7 /* HeapModule reexports.swift */, + 7DE4484A2F2D3B74005853A7 /* OrderedCollections reexports.swift */, 7DE91F7A29CA70F3004483EB /* CMakeLists.txt */, + 7DE91F7C29CA70F3004483EB /* Collections.docc */, ); path = Collections; sourceTree = ""; @@ -1718,6 +1956,9 @@ 7DE921F829CA8576004483EB /* DequeTests.swift */, 7DE921F929CA8576004483EB /* MutableCollectionTests.swift */, 7DE921F729CA8576004483EB /* RangeReplaceableCollectionTests.swift */, + 7D2A774A2F27F285005780C7 /* RigidDequeCrashTests.swift */, + 7D2A774B2F27F285005780C7 /* RigidDequeTests.swift */, + 7D2A774C2F27F285005780C7 /* UniqueDequeTests.swift */, ); path = DequeTests; sourceTree = ""; @@ -1807,6 +2048,7 @@ children = ( 7DEBDB3B29CCE43600ADC226 /* _CollectionState.swift */, 7DEBDB4629CCE43600ADC226 /* _MinimalCollectionCore.swift */, + 7D2A77482F27F271005780C7 /* CustomProducer.swift */, 7DEBDB4029CCE43600ADC226 /* MinimalBidirectionalCollection.swift */, 7DEBDB4829CCE43600ADC226 /* MinimalCollection.swift */, 7DEBDB4729CCE43600ADC226 /* MinimalDecoder.swift */, @@ -1840,20 +2082,8 @@ isa = PBXGroup; children = ( A93AC20F2E7C841700A824DF /* CMakeLists.txt */, - A93AC2102E7C841700A824DF /* RigidArray.swift */, - 7D6FEE1B2E8778F3007C1B86 /* RigidArray+Append.swift */, - A93AC2112E7C841700A824DF /* RigidArray+Experimental.swift */, - 7D6FEE1C2E8778F3007C1B86 /* RigidArray+Initializers.swift */, - 7D6FEE1D2E8778F3007C1B86 /* RigidArray+Insertions.swift */, - 7D6FEE1E2E8778F3007C1B86 /* RigidArray+Removals.swift */, - 7D6FEE1F2E8778F3007C1B86 /* RigidArray+Replacements.swift */, - A93AC2122E7C841700A824DF /* UniqueArray.swift */, - 7D6FEE202E8778F3007C1B86 /* UniqueArray+Append.swift */, - A93AC2132E7C841700A824DF /* UniqueArray+Experimental.swift */, - 7D6FEE212E8778F3007C1B86 /* UniqueArray+Initializers.swift */, - 7D6FEE222E8778F3007C1B86 /* UniqueArray+Insertions.swift */, - 7D6FEE232E8778F3007C1B86 /* UniqueArray+Removals.swift */, - 7D6FEE242E8778F3007C1B86 /* UniqueArray+Replacements.swift */, + 7DA23F3D2F329A2300E4C03A /* RigidArray */, + 7DA23F452F329A2300E4C03A /* UniqueArray */, 7D6FEE2F2E8880F6007C1B86 /* BasicContainers.docc */, ); path = BasicContainers; @@ -1999,7 +2229,6 @@ 7DE920F129CA70F4004483EB /* BitArray+Initializers.swift in Sources */, 7DE9214529CA70F4004483EB /* _HashNode+Structural symmetricDifference.swift in Sources */, 7DE9201029CA70F3004483EB /* OrderedDictionary+Deprecations.swift in Sources */, - 7DE9205929CA70F3004483EB /* Deque+Descriptions.swift in Sources */, 7DE9212729CA70F4004483EB /* TreeSet+Equatable.swift in Sources */, 7DE9213429CA70F4004483EB /* TreeSet+ExpressibleByArrayLiteral.swift in Sources */, 7DE9209729CA70F4004483EB /* _RopePath.swift in Sources */, @@ -2010,11 +2239,47 @@ 7DE920C029CA70F4004483EB /* BitSet+SetAlgebra conformance.swift in Sources */, 7DE9203C29CA70F3004483EB /* OrderedSet+Partial SetAlgebra formSymmetricDifference.swift in Sources */, 7DE9209029CA70F4004483EB /* Rope.swift in Sources */, - 7D6FEE162E8778CF007C1B86 /* Mut.swift in Sources */, - 7D6FEE172E8778CF007C1B86 /* BorrowIteratorProtocol.swift in Sources */, - 7D6FEE182E8778CF007C1B86 /* Container+Utilities.swift in Sources */, - 7D6FEE192E8778CF007C1B86 /* Ref.swift in Sources */, - 7D6FEE1A2E8778CF007C1B86 /* Container.swift in Sources */, + 7D2A77782F27F2BF005780C7 /* Deque._Storage.swift in Sources */, + 7D2A77792F27F2BF005780C7 /* RigidDeque+Prepend.swift in Sources */, + 7D2A777A2F27F2BF005780C7 /* UniqueDeque+Consumption.swift in Sources */, + 7D2A777B2F27F2BF005780C7 /* _UnsafeDequeHandle.swift in Sources */, + 7D2A777C2F27F2BF005780C7 /* _UnsafeDequeSegments.swift in Sources */, + 7D2A777D2F27F2BF005780C7 /* RigidDeque+Append.swift in Sources */, + 7D2A777E2F27F2BF005780C7 /* Deque+Hashable.swift in Sources */, + 7D2A777F2F27F2BF005780C7 /* RigidDeque+Container.swift in Sources */, + 7D2A77802F27F2BF005780C7 /* Deque.swift in Sources */, + 7D2A77812F27F2BF005780C7 /* UniqueDeque+Append.swift in Sources */, + 7D2A77822F27F2BF005780C7 /* UniqueDeque+Initializers.swift in Sources */, + 7D2A77832F27F2BF005780C7 /* Deque+Equatable.swift in Sources */, + 7D2A77842F27F2BF005780C7 /* UniqueDeque+Container.swift in Sources */, + 7D2A77852F27F2BF005780C7 /* RigidDeque+Initializers.swift in Sources */, + 7D2A77862F27F2BF005780C7 /* RigidDeque+Consumption.swift in Sources */, + 7D2A77872F27F2BF005780C7 /* Deque._UnsafeHandle.swift in Sources */, + 7DA23F5C2F32C69100E4C03A /* RigidArray+Descriptions.swift in Sources */, + 7D2A77882F27F2BF005780C7 /* Deque+Extras.swift in Sources */, + 7D2A77892F27F2BF005780C7 /* UniqueDeque+Removals.swift in Sources */, + 7D2A778A2F27F2BF005780C7 /* UniqueDeque+Insertions.swift in Sources */, + 7D2A778B2F27F2BF005780C7 /* UniqueDeque+Replacements.swift in Sources */, + 7D2A778C2F27F2BF005780C7 /* UniqueDeque+Prepend.swift in Sources */, + 7D2A778D2F27F2BF005780C7 /* UniqueDeque.swift in Sources */, + 7D2A778E2F27F2BF005780C7 /* RigidDeque.swift in Sources */, + 7D2A778F2F27F2BF005780C7 /* Deque+CustomReflectable.swift in Sources */, + 7D2A77902F27F2BF005780C7 /* RigidDeque+Insertions.swift in Sources */, + 7D2A77912F27F2BF005780C7 /* RigidDeque+Removals.swift in Sources */, + 7D2A77922F27F2BF005780C7 /* _DequeBuffer.swift in Sources */, + 7D57A2BE2F342DEE002543BD /* UniqueArray+Descriptions.swift in Sources */, + 7D57A2BF2F342DEE002543BD /* UniqueArray+Hashable.swift in Sources */, + 7D57A2C02F342DEE002543BD /* UniqueArray+Equatable.swift in Sources */, + 7D2A77932F27F2BF005780C7 /* _DequeBufferHeader.swift in Sources */, + 7D2A77942F27F2BF005780C7 /* Deque+Collection.swift in Sources */, + 7D2A77952F27F2BF005780C7 /* Deque+Codable.swift in Sources */, + 7D2A77962F27F2BF005780C7 /* RigidDeque+Experimental.swift in Sources */, + 7D2A77972F27F2BF005780C7 /* Deque+Testing.swift in Sources */, + 7D2A77982F27F2BF005780C7 /* RigidDeque+Replacements.swift in Sources */, + 7D2A77992F27F2BF005780C7 /* Deque+Descriptions.swift in Sources */, + 7D2A779A2F27F2BF005780C7 /* RigidDeque+Testing.swift in Sources */, + 7D2A779B2F27F2BF005780C7 /* UniqueDeque+Experimental.swift in Sources */, + 7D2A779C2F27F2BF005780C7 /* Deque+ExpressibleByArrayLiteral.swift in Sources */, 7DE9213B29CA70F4004483EB /* TreeSet+Hashable.swift in Sources */, 7DE9200D29CA70F3004483EB /* OrderedDictionary+Equatable.swift in Sources */, 7DE9207C29CA70F4004483EB /* BigSubstring.swift in Sources */, @@ -2023,11 +2288,12 @@ 7DE9216229CA70F4004483EB /* _AncestorHashSlots.swift in Sources */, 7DE9216B29CA70F4004483EB /* TreeDictionary+Codable.swift in Sources */, 7DE9201A29CA70F3004483EB /* OrderedDictionary+Sendable.swift in Sources */, - 7DE9205D29CA70F4004483EB /* Deque._Storage.swift in Sources */, 7DE9203B29CA70F3004483EB /* OrderedSet+Partial SetAlgebra subtracting.swift in Sources */, 7DE9213A29CA70F4004483EB /* TreeSet.swift in Sources */, 7DE9213829CA70F4004483EB /* TreeSet+Filter.swift in Sources */, 7DE9206D29CA70F4004483EB /* BigString+Chunk+Description.swift in Sources */, + 7D57A2B82F33FF48002543BD /* RigidArray+Consumption.swift in Sources */, + 7DA23F582F32C66300E4C03A /* RigidArray+Equatable.swift in Sources */, 7DE9208A29CA70F4004483EB /* BigString+Comparable.swift in Sources */, 7DE9213629CA70F4004483EB /* TreeSet+SetAlgebra basics.swift in Sources */, 7DE9202C29CA70F3004483EB /* OrderedSet+Initializers.swift in Sources */, @@ -2041,11 +2307,11 @@ 7DE920BD29CA70F4004483EB /* BitSet+SetAlgebra symmetricDifference.swift in Sources */, 7DE9208229CA70F4004483EB /* BigString+BidirectionalCollection.swift in Sources */, 7DE9203E29CA70F3004483EB /* OrderedSet+Partial SetAlgebra subtract.swift in Sources */, + 7D57A2CE2F343CA9002543BD /* ContainerAlgorithms.swift in Sources */, 7DE9216929CA70F4004483EB /* TreeDictionary+Filter.swift in Sources */, 7DE9203129CA70F3004483EB /* OrderedSet+Partial MutableCollection.swift in Sources */, 7DE9209B29CA70F4004483EB /* Rope+Split.swift in Sources */, 7DE9206629CA70F4004483EB /* BigString+Debugging.swift in Sources */, - 7DE9205229CA70F3004483EB /* _UnsafeWrappedBuffer.swift in Sources */, 7DE9201129CA70F3004483EB /* OrderedDictionary+Initializers.swift in Sources */, 7DE9212B29CA70F4004483EB /* TreeSet+SetAlgebra subtracting.swift in Sources */, 7DE920F629CA70F4004483EB /* BitArray+Equatable.swift in Sources */, @@ -2072,17 +2338,9 @@ 7DE9212A29CA70F4004483EB /* TreeSet+Extras.swift in Sources */, 7DE9209A29CA70F4004483EB /* Rope+Append.swift in Sources */, 7DE9203F29CA70F3004483EB /* OrderedSet+Partial SetAlgebra isDisjoint.swift in Sources */, - A93AC2152E7C841700A824DF /* RigidArray.swift in Sources */, - A93AC2162E7C841700A824DF /* UniqueArray.swift in Sources */, - A93AC2172E7C841700A824DF /* RigidArray+Experimental.swift in Sources */, - A93AC2182E7C841700A824DF /* UniqueArray+Experimental.swift in Sources */, - 7D48BCD12E51524200D7F6F7 /* InputSpan.swift in Sources */, - 7D48BCD32E51524200D7F6F7 /* Box.swift in Sources */, - 7D48BCD62E51524200D7F6F7 /* Shared.swift in Sources */, 7DE9208629CA70F4004483EB /* BigString+LosslessStringConvertible.swift in Sources */, 7DE9204329CA70F3004483EB /* _HashTable+Bucket.swift in Sources */, 7DE9216A29CA70F4004483EB /* TreeDictionary.swift in Sources */, - 7DEBDB9D29CCE73D00ADC226 /* Collections.swift in Sources */, 7DE9215C29CA70F4004483EB /* _Bitmap.swift in Sources */, 7DE9207029CA70F4004483EB /* BigString+Chunk+RopeElement.swift in Sources */, 7DE9213729CA70F4004483EB /* TreeSet+Sequence.swift in Sources */, @@ -2105,6 +2363,7 @@ 7DE9215329CA70F4004483EB /* _HashNode+Invariants.swift in Sources */, 7DE9209629CA70F4004483EB /* Rope+Builder.swift in Sources */, 7DE9215129CA70F4004483EB /* _HashNode+Subtree Modify.swift in Sources */, + 7DA23F562F329E9000E4C03A /* UniqueArray+Container.swift in Sources */, 7DE9204729CA70F3004483EB /* _HashTable+Testing.swift in Sources */, 7DE920E929CA70F4004483EB /* BitArray+Invariants.swift in Sources */, 7DE9215429CA70F4004483EB /* _HashNode+UnsafeHandle.swift in Sources */, @@ -2127,7 +2386,6 @@ 7DE9207D29CA70F4004483EB /* BigSubstring+UTF16View.swift in Sources */, 7DE9217229CA70F4004483EB /* TreeDictionary+Sendable.swift in Sources */, 7DE9207729CA70F4004483EB /* Range+BigString.swift in Sources */, - 7DE9204B29CA70F3004483EB /* _DequeBuffer.swift in Sources */, 7DE920DF29CA70F4004483EB /* Slice+Utilities.swift in Sources */, 7DE9215729CA70F4004483EB /* _RawHashNode.swift in Sources */, 7DE9209529CA70F4004483EB /* RopeSummary.swift in Sources */, @@ -2156,6 +2414,7 @@ 7DE9201929CA70F3004483EB /* OrderedDictionary+Values.swift in Sources */, 7DE9213929CA70F4004483EB /* TreeSet+SetAlgebra Initializers.swift in Sources */, 7DE9217729CA70F4004483EB /* TreeDictionary+Keys.swift in Sources */, + 7D57A2BA2F340B58002543BD /* UniqueArray+Consumption.swift in Sources */, 7DE920DA29CA70F4004483EB /* BitSet._UnsafeHandle.swift in Sources */, 7DE920D129CA70F4004483EB /* BitSet.Index.swift in Sources */, 7DAD899E2E8B09C300DD5786 /* UInt+first and last set bit.swift in Sources */, @@ -2165,7 +2424,6 @@ 7DE9207429CA70F4004483EB /* BigString+ReplaceSubrange.swift in Sources */, 7DE920DC29CA70F4004483EB /* BitSet+Invariants.swift in Sources */, 7DE9216729CA70F4004483EB /* TreeDictionary+Equatable.swift in Sources */, - 7DE9204C29CA70F3004483EB /* Deque+Collection.swift in Sources */, 7DE9201F29CA70F3004483EB /* OrderedSet+RandomAccessCollection.swift in Sources */, 7DE9202E29CA70F3004483EB /* OrderedSet+UnorderedView.swift in Sources */, 7DE9215F29CA70F4004483EB /* _UnsafePath.swift in Sources */, @@ -2179,6 +2437,9 @@ 7DE9203629CA70F3004483EB /* OrderedSet+ReserveCapacity.swift in Sources */, 7DE9208D29CA70F4004483EB /* Rope+Debugging.swift in Sources */, 7DE9208829CA70F4004483EB /* BigString+ExpressibleByStringLiteral.swift in Sources */, + 7D57A2C42F342F30002543BD /* RigidDeque+Equatable.swift in Sources */, + 7D57A2C52F342F30002543BD /* RigidDeque+Hashable.swift in Sources */, + 7D57A2C62F342F30002543BD /* RigidDeque+Descriptions.swift in Sources */, 7DE9202329CA70F3004483EB /* OrderedSet+UnstableInternals.swift in Sources */, 7DE9208529CA70F4004483EB /* BigString+TextOutputStream.swift in Sources */, 7DE9212829CA70F4004483EB /* TreeSet+SetAlgebra intersection.swift in Sources */, @@ -2202,8 +2463,22 @@ 7DE9217B29CA70F4004483EB /* Heap+Invariants.swift in Sources */, 7DE9212F29CA70F4004483EB /* TreeSet+SetAlgebra formIntersection.swift in Sources */, 7DE920A329CA70F4004483EB /* Rope+Index.swift in Sources */, + 7DA23F462F329A2300E4C03A /* RigidArray+Experimental.swift in Sources */, + 7DA23F472F329A2300E4C03A /* UniqueArray.swift in Sources */, + 7DA23F482F329A2300E4C03A /* RigidArray+Replacements.swift in Sources */, + 7DA23F492F329A2300E4C03A /* RigidArray+Container.swift in Sources */, + 7DA23F4A2F329A2300E4C03A /* UniqueArray+Replacements.swift in Sources */, + 7DA23F4B2F329A2300E4C03A /* UniqueArray+Removals.swift in Sources */, + 7DA23F4C2F329A2300E4C03A /* RigidArray+Append.swift in Sources */, + 7DA23F4D2F329A2300E4C03A /* RigidArray+Removals.swift in Sources */, + 7DA23F4E2F329A2300E4C03A /* UniqueArray+Initializers.swift in Sources */, + 7DA23F4F2F329A2300E4C03A /* RigidArray+Initializers.swift in Sources */, + 7DA23F502F329A2300E4C03A /* RigidArray+Insertions.swift in Sources */, + 7DA23F512F329A2300E4C03A /* UniqueArray+Append.swift in Sources */, + 7DA23F522F329A2300E4C03A /* UniqueArray+Experimental.swift in Sources */, + 7DA23F532F329A2300E4C03A /* UniqueArray+Insertions.swift in Sources */, + 7DA23F542F329A2300E4C03A /* RigidArray.swift in Sources */, 7DE9207329CA70F4004483EB /* BigString+RemoveSubrange.swift in Sources */, - 7DE9205829CA70F3004483EB /* Deque._UnsafeHandle.swift in Sources */, 7DE9213529CA70F4004483EB /* TreeSet+SetAlgebra symmetricDifference.swift in Sources */, 7DE920D429CA70F4004483EB /* BitSet+SetAlgebra union.swift in Sources */, 7DE920C329CA70F4004483EB /* BitSet+SetAlgebra formUnion.swift in Sources */, @@ -2221,9 +2496,27 @@ 7DE9213D29CA70F4004483EB /* TreeSet+SetAlgebra isSubset.swift in Sources */, 7DE9203029CA70F3004483EB /* OrderedSet+SubSequence.swift in Sources */, 7DE9215529CA70F4004483EB /* _RawHashNode+UnsafeHandle.swift in Sources */, + 7D2A77382F27F1E4005780C7 /* BorrowingSequence+Utilities.swift in Sources */, + 7D2A77392F27F1E4005780C7 /* Box.swift in Sources */, + 7D2A773A2F27F1E4005780C7 /* Drain.swift in Sources */, + 7D2A773B2F27F1E4005780C7 /* Container.swift in Sources */, + 7D2A773C2F27F1E4005780C7 /* TemporaryAllocation.swift in Sources */, + 7D2A773D2F27F1E4005780C7 /* BorrowingSequence.swift in Sources */, + 7D2A773E2F27F1E4005780C7 /* BorrowingSequence+Standard Conformances.swift in Sources */, + 7D2A773F2F27F1E4005780C7 /* Borrow.swift in Sources */, + 7D57A2D02F353946002543BD /* RigidArray+Deprecated.swift in Sources */, + 7D2A77402F27F1E4005780C7 /* BorrowingIteratorProtocol.swift in Sources */, + 7D2A77412F27F1E4005780C7 /* Inout.swift in Sources */, + 7D2A77422F27F1E4005780C7 /* OutputSpan+Extras.swift in Sources */, + 7D2A77432F27F1E4005780C7 /* Shared.swift in Sources */, + 7D2A77442F27F1E4005780C7 /* InputSpan.swift in Sources */, + 7D2A77452F27F1E4005780C7 /* Producer.swift in Sources */, 7DE9209429CA70F4004483EB /* Rope+_UnmanagedLeaf.swift in Sources */, 7DE9208429CA70F4004483EB /* BigString+Equatable.swift in Sources */, 7DE9203729CA70F3004483EB /* OrderedSet+Partial SetAlgebra union.swift in Sources */, + 7D57A2CA2F342F43002543BD /* UniqueDeque+Descriptions.swift in Sources */, + 7D57A2CB2F342F43002543BD /* UniqueDeque+Equatable.swift in Sources */, + 7D57A2CC2F342F43002543BD /* UniqueDeque+Hashable.swift in Sources */, 7DE9215229CA70F4004483EB /* _HashNode+Builder.swift in Sources */, 7DE9212929CA70F4004483EB /* TreeSet+SetAlgebra formUnion.swift in Sources */, 7DE920C129CA70F4004483EB /* BitSet+SetAlgebra subtract.swift in Sources */, @@ -2234,6 +2527,7 @@ 7DE9208029CA70F4004483EB /* BigString+Hashing.swift in Sources */, 7DE920F829CA70F4004483EB /* BitArray+Testing.swift in Sources */, 7DE920D629CA70F4004483EB /* BitSet+Equatable.swift in Sources */, + 7D57A2D22F353CA5002543BD /* UniqueArray+Deprecated.swift in Sources */, 7DE9217A29CA70F4004483EB /* Heap+Descriptions.swift in Sources */, 7DE9216429CA70F4004483EB /* _HashNode.swift in Sources */, 7DAD89A52E8B09D900DD5786 /* _UnsafeBitSet+_Word.swift in Sources */, @@ -2244,13 +2538,11 @@ 7DE9201329CA70F3004483EB /* OrderedDictionary+CustomReflectable.swift in Sources */, 7DE9201C29CA70F3004483EB /* OrderedDictionary+Partial MutableCollection.swift in Sources */, 7DE9202729CA70F3004483EB /* OrderedSet+Insertions.swift in Sources */, - 7DE9205B29CA70F3004483EB /* Deque+ExpressibleByArrayLiteral.swift in Sources */, 7DE9208729CA70F4004483EB /* BigString+Sequence.swift in Sources */, 7DE9202229CA70F3004483EB /* OrderedSet+Diffing.swift in Sources */, 7DE920CA29CA70F4004483EB /* BitSet+CustomStringConvertible.swift in Sources */, 7DE9212E29CA70F4004483EB /* TreeSet+SetAlgebra isStrictSuperset.swift in Sources */, 7DE920A829CA70F4004483EB /* String.Index+ABI.swift in Sources */, - 7DE9204F29CA70F3004483EB /* Deque.swift in Sources */, 7DE9214129CA70F4004483EB /* _HashNode+Initializers.swift in Sources */, 7D9B859929E4F74400B291CD /* BitArray+LosslessStringConvertible.swift in Sources */, 7DE9202D29CA70F3004483EB /* OrderedSet.swift in Sources */, @@ -2262,8 +2554,6 @@ 7DE9214929CA70F4004483EB /* _HashNode+Structural isEqualSet.swift in Sources */, 7DE9206729CA70F4004483EB /* BigString+Builder.swift in Sources */, 7DE9208B29CA70F4004483EB /* RopeMetric.swift in Sources */, - 7DE9205A29CA70F3004483EB /* Deque+Extras.swift in Sources */, - 7DE9205129CA70F3004483EB /* Deque+Hashable.swift in Sources */, 7DE9209929CA70F4004483EB /* Rope+Extract.swift in Sources */, 7DE9202629CA70F3004483EB /* OrderedSet+Partial SetAlgebra isStrictSubset.swift in Sources */, 7DE920E729CA70F4004483EB /* BitArray+CustomReflectable.swift in Sources */, @@ -2271,24 +2561,12 @@ 7DE9209D29CA70F4004483EB /* Rope+Insert.swift in Sources */, 7DE9214329CA70F4004483EB /* _HashNode+Subtree Removals.swift in Sources */, 7DE9207929CA70F4004483EB /* BigString+UnicodeScalarView.swift in Sources */, - 7DE9205329CA70F3004483EB /* _DequeBufferHeader.swift in Sources */, 7DE9202429CA70F3004483EB /* OrderedSet+Invariants.swift in Sources */, - 7D6FEE252E8778F3007C1B86 /* UniqueArray+Append.swift in Sources */, - 7D6FEE262E8778F3007C1B86 /* RigidArray+Removals.swift in Sources */, - 7D6FEE272E8778F3007C1B86 /* UniqueArray+Removals.swift in Sources */, - 7D6FEE282E8778F3007C1B86 /* RigidArray+Replacements.swift in Sources */, - 7D6FEE292E8778F3007C1B86 /* UniqueArray+Replacements.swift in Sources */, - 7D6FEE2A2E8778F3007C1B86 /* RigidArray+Append.swift in Sources */, - 7D6FEE2B2E8778F3007C1B86 /* RigidArray+Initializers.swift in Sources */, - 7D6FEE2C2E8778F3007C1B86 /* UniqueArray+Insertions.swift in Sources */, - 7D6FEE2D2E8778F3007C1B86 /* RigidArray+Insertions.swift in Sources */, - 7D6FEE2E2E8778F3007C1B86 /* UniqueArray+Initializers.swift in Sources */, 7DE920A729CA70F4004483EB /* _CharacterRecognizer.swift in Sources */, 7DE920A429CA70F4004483EB /* Rope+Sequence.swift in Sources */, 7DE9201829CA70F3004483EB /* OrderedDictionary+Invariants.swift in Sources */, 7DE920CD29CA70F4004483EB /* BitSet+CustomDebugStringConvertible.swift in Sources */, 7DE9212529CA70F4004483EB /* TreeSet+SetAlgebra isStrictSubset.swift in Sources */, - 7DE9205C29CA70F3004483EB /* Deque+Equatable.swift in Sources */, 7DE9209229CA70F4004483EB /* Rope+_Storage.swift in Sources */, 7DE9203929CA70F3004483EB /* OrderedSet+Partial RangeReplaceableCollection.swift in Sources */, 7DE9206329CA70F4004483EB /* BigString+Contents.swift in Sources */, @@ -2299,18 +2577,20 @@ 7DE9215929CA70F4004483EB /* _HashNode+Structural isSubset.swift in Sources */, 7DE920C629CA70F4004483EB /* BitSet+SetAlgebra formSymmetricDifference.swift in Sources */, 7DE9202129CA70F3004483EB /* OrderedSet+Partial SetAlgebra isEqualSet.swift in Sources */, - 7DE9205529CA70F3004483EB /* Deque+Codable.swift in Sources */, 7DE9206029CA70F4004483EB /* BigString+Summary.swift in Sources */, 7DE9203829CA70F3004483EB /* OrderedSet+Partial SetAlgebra formIntersection.swift in Sources */, 7DE9207629CA70F4004483EB /* BigString+Initializers.swift in Sources */, 7DE9206129CA70F4004483EB /* BigString.swift in Sources */, 7DE9215A29CA70F4004483EB /* _HashNode+Structural subtracting.swift in Sources */, 7DE9217E29CA70F4004483EB /* Heap+ExpressibleByArrayLiteral.swift in Sources */, + 7DE448452F2D3705005853A7 /* BinaryInteger extensions.swift in Sources */, + 7DA23F5A2F32C68300E4C03A /* RigidArray+Hashable.swift in Sources */, 7DE9204029CA70F3004483EB /* OrderedSet+Partial SetAlgebra isStrictSuperset.swift in Sources */, 7DE920BF29CA70F4004483EB /* BitSet+Codable.swift in Sources */, 7DE9203329CA70F3004483EB /* OrderedSet+Testing.swift in Sources */, 7DE9212429CA70F4004483EB /* TreeSet+Descriptions.swift in Sources */, 7DE9217129CA70F4004483EB /* TreeDictionary+Values.swift in Sources */, + 7D2A77262F27F1D1005780C7 /* Span+Extras.swift in Sources */, 7DE920D029CA70F4004483EB /* BitSet+SetAlgebra isSubset.swift in Sources */, 7DE920C829CA70F4004483EB /* BitSet+SetAlgebra isEqualSet.swift in Sources */, 7DE9215B29CA70F4004483EB /* _HashNode+Structural mapValues.swift in Sources */, @@ -2337,13 +2617,11 @@ 7DE9206C29CA70F4004483EB /* BigString+Chunk.swift in Sources */, 7DE920F329CA70F4004483EB /* BitArray+Copy.swift in Sources */, 7DE9214029CA70F4004483EB /* _Hash.swift in Sources */, - 7DE9205629CA70F3004483EB /* Deque+Testing.swift in Sources */, 7DE9209329CA70F4004483EB /* Rope+Invariants.swift in Sources */, 7DE920EE29CA70F4004483EB /* BitArray+ExpressibleByArrayLiteral.swift in Sources */, 7DE9214C29CA70F4004483EB /* _HashNode+Primitive Insertions.swift in Sources */, 7DE920BE29CA70F4004483EB /* BitSet+SetAlgebra formIntersection.swift in Sources */, 7DE9217329CA70F4004483EB /* TreeDictionary+Merge.swift in Sources */, - 7DE9204E29CA70F3004483EB /* Deque+CustomReflectable.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -2388,8 +2666,6 @@ 7DE9221E29CA8576004483EB /* MutableCollectionTests.swift in Sources */, 7DE9221529CA8576004483EB /* RandomAccessCollection+Extras.swift in Sources */, 7DEBDB7929CCE44A00ADC226 /* LifetimeTracked.swift in Sources */, - 7D6FEE0F2E877870007C1B86 /* RefTests.swift in Sources */, - 7D6FEE102E877870007C1B86 /* MutTests.swift in Sources */, 7DE921FC29CA8576004483EB /* IndexRangeCollectionTests.swift in Sources */, 7DE9221229CA8576004483EB /* OrderedDictionary+Elements Tests.swift in Sources */, 7DEBDB7629CCE44A00ADC226 /* MinimalIndex.swift in Sources */, @@ -2416,6 +2692,9 @@ 7DEBDB8329CCE44A00ADC226 /* CheckHashable.swift in Sources */, 7DE921FF29CA8576004483EB /* Utilities.swift in Sources */, 7DEBDB8F29CCE44A00ADC226 /* CheckEquatable.swift in Sources */, + 7D2A774D2F27F285005780C7 /* RigidDequeCrashTests.swift in Sources */, + 7D2A774E2F27F285005780C7 /* UniqueDequeTests.swift in Sources */, + 7D2A774F2F27F285005780C7 /* RigidDequeTests.swift in Sources */, 7DEBDB7729CCE44A00ADC226 /* HashableBox.swift in Sources */, 7DE9220E29CA8576004483EB /* SampleStrings.swift in Sources */, 7D48BCEE2E5158A100D7F6F7 /* BoxTests.swift in Sources */, @@ -2435,8 +2714,11 @@ 7DE9220129CA8576004483EB /* TreeDictionary.Keys Tests.swift in Sources */, 7DE9220729CA8576004483EB /* BitSet.Counted Tests.swift in Sources */, 7DE9220F29CA8576004483EB /* OrderedDictionary Tests.swift in Sources */, + 7D2A779F2F27F367005780C7 /* InoutTests.swift in Sources */, + 7D2A77A02F27F367005780C7 /* BorrowTests.swift in Sources */, 7D48BCDF2E51558700D7F6F7 /* TestPrintable.swift in Sources */, 7D48BCE02E51558700D7F6F7 /* LifetimeTrackedStruct.swift in Sources */, + 7D2A77492F27F271005780C7 /* CustomProducer.swift in Sources */, 7DE9221029CA8576004483EB /* OrderedDictionary Utils.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; diff --git a/Xcode/Shared.xcconfig b/Xcode/Shared.xcconfig index bcedd132..c447ce81 100644 --- a/Xcode/Shared.xcconfig +++ b/Xcode/Shared.xcconfig @@ -33,7 +33,7 @@ OTHER_SWIFT_FLAGS = $(inherited) \ ONLY_ACTIVE_ARCH[config=Debug] = YES SWIFT_ACTIVE_COMPILATION_CONDITIONS = $(inherited) COLLECTIONS_SINGLE_MODULE -SWIFT_ACTIVE_COMPILATION_CONDITIONS[config=Debug] = $(inherited) COLLECTIONS_INTERNAL_CHECKS DEBUG +SWIFT_ACTIVE_COMPILATION_CONDITIONS[config=Debug] = $(inherited) DEBUG //COLLECTIONS_INTERNAL_CHECKS SWIFT_COMPILATION_MODE[config=Release] = wholemodule SWIFT_COMPILATION_MODE[config=Debug] = singlefile