mirror of
https://github.com/apple/swift-collections
synced 2026-11-26 04:47:48 +00:00
Merge branch 'main' into enable_android_sdk_checks
This commit is contained in:
164 files changed
+18046
-1972
No files matched your search
@@ -0,0 +1,6 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
@@ -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
|
||||
|
||||
@@ -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<intptr_t> constructor from buffer",
|
||||
"VecDeque<isize> constructor from buffer",
|
||||
"Deque<Int> init from unsafe buffer"
|
||||
]
|
||||
},
|
||||
@@ -225,10 +226,12 @@
|
||||
"title": "sequential iteration",
|
||||
"tasks": [
|
||||
"std::deque<intptr_t> sequential iteration",
|
||||
"VecDeque<isize> sequential iteration",
|
||||
"Deque<Int> sequential iteration (contiguous, iterator)",
|
||||
"Deque<Int> sequential iteration (contiguous, indices)",
|
||||
"Deque<Int> sequential iteration (discontiguous, iterator)",
|
||||
"Deque<Int> sequential iteration (discontiguous, indices)"
|
||||
"Deque<Int> sequential iteration (discontiguous, indices)",
|
||||
"UniqueDeque<Int> sequential iteration"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -246,8 +249,19 @@
|
||||
"title": "append individual integers",
|
||||
"tasks": [
|
||||
"std::deque<intptr_t> push_back",
|
||||
"VecDeque<isize> push_back",
|
||||
"Deque<Int> append",
|
||||
"Deque<Int> append, reserving capacity"
|
||||
"UniqueDeque<Int> append"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "chart",
|
||||
"title": "append individual integers, reserving capacity",
|
||||
"tasks": [
|
||||
"VecDeque<isize> push_back, reserving capacity",
|
||||
"Deque<Int> append, reserving capacity",
|
||||
"RigidDeque<Int> append, reserving capacity",
|
||||
"UniqueDeque<Int> append, reserving capacity"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -255,8 +269,19 @@
|
||||
"title": "prepend individual integers",
|
||||
"tasks": [
|
||||
"std::deque<intptr_t> push_front",
|
||||
"VecDeque<isize> push_front",
|
||||
"Deque<Int> prepend",
|
||||
"Deque<Int> prepend, reserving capacity"
|
||||
"UniqueDeque<Int> prepend"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "chart",
|
||||
"title": "prepend individual integers, reserving capacity",
|
||||
"tasks": [
|
||||
"VecDeque<isize> push_front, reserving capacity",
|
||||
"Deque<Int> prepend, reserving capacity",
|
||||
"RigidDeque<Int> prepend, reserving capacity",
|
||||
"UniqueDeque<Int> prepend, reserving capacity"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -264,7 +289,9 @@
|
||||
"title": "random insertions",
|
||||
"tasks": [
|
||||
"std::deque<intptr_t> random insertions",
|
||||
"Deque<Int> random insertions"
|
||||
"VecDeque<isize> random insertions",
|
||||
"Deque<Int> random insertions",
|
||||
"UniqueDeque<Int> random insertions"
|
||||
]
|
||||
},
|
||||
{
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
},
|
||||
{
|
||||
|
||||
@@ -12,6 +12,27 @@
|
||||
|
||||
import PackageDescription
|
||||
|
||||
let availabilityMacros: KeyValuePairs<String, String> = [
|
||||
"SwiftStdlib 5.0": "macOS 10.14.4, iOS 12.2, watchOS 5.2, tvOS 12.2",
|
||||
"SwiftStdlib 5.1": "macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0",
|
||||
"SwiftStdlib 5.6": "macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4",
|
||||
"SwiftStdlib 5.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",
|
||||
|
||||
@@ -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]
|
||||
)]
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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 {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -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<Int>) {}
|
||||
|
||||
@inline(never)
|
||||
fileprivate func appendReserveCapacity(_ input: UnsafeBufferPointer<Int>) {
|
||||
var deque = RigidDeque<Int>(capacity: input.count)
|
||||
for i in input {
|
||||
deque.append(i)
|
||||
}
|
||||
blackHole(deque)
|
||||
}
|
||||
|
||||
@inline(never)
|
||||
fileprivate func prependReserveCapacity(_ input: UnsafeBufferPointer<Int>) {
|
||||
var deque = RigidDeque<Int>(capacity: input.count)
|
||||
for i in input {
|
||||
deque.prepend(i)
|
||||
}
|
||||
blackHole(deque)
|
||||
}
|
||||
|
||||
extension Benchmark {
|
||||
public mutating func addRigidDequeBenchmarks() {
|
||||
self.addSimple(
|
||||
title: "RigidDeque<Int> append, reserving capacity",
|
||||
input: [Int].self
|
||||
) { input in
|
||||
input.withUnsafeBufferPointer {
|
||||
appendReserveCapacity($0)
|
||||
}
|
||||
}
|
||||
|
||||
self.addSimple(
|
||||
title: "RigidDeque<Int> prepend, reserving capacity",
|
||||
input: [Int].self
|
||||
) { input in
|
||||
input.withUnsafeBufferPointer {
|
||||
prependReserveCapacity($0)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -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>?, _: Int)
|
||||
|
||||
@_extern(c, "rust_vecdeque_append_integers")
|
||||
func rust_vecdeque_append_integers(_: UnsafePointer<Int>?, _: Int)
|
||||
|
||||
@_extern(c, "rust_vecdeque_append_integers_with_capacity")
|
||||
func rust_vecdeque_append_integers_with_capacity(_: UnsafePointer<Int>?, _: Int)
|
||||
|
||||
@_extern(c, "rust_vecdeque_prepend_integers")
|
||||
func rust_vecdeque_prepend_integers(_: UnsafePointer<Int>?, _: Int)
|
||||
|
||||
@_extern(c, "rust_vecdeque_prepend_integers_with_capacity")
|
||||
func rust_vecdeque_prepend_integers_with_capacity(_: UnsafePointer<Int>?, _: Int)
|
||||
|
||||
@_extern(c, "rust_vecdeque_random_insertions")
|
||||
func rust_vecdeque_random_insertions(_: UnsafePointer<Int>?, _: 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<isize> push_back from integer range",
|
||||
input: Int.self
|
||||
) { count in
|
||||
rust_vecdeque_from_int_range(count)
|
||||
}
|
||||
|
||||
self.addSimple(
|
||||
title: "VecDeque<isize> 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<isize> push_back",
|
||||
input: [Int].self
|
||||
) { input in
|
||||
input.withUnsafeBufferPointer { buffer in
|
||||
rust_vecdeque_append_integers(buffer.baseAddress, buffer.count)
|
||||
}
|
||||
}
|
||||
|
||||
self.addSimple(
|
||||
title: "VecDeque<isize> 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<isize> push_front",
|
||||
input: [Int].self
|
||||
) { input in
|
||||
input.withUnsafeBufferPointer { buffer in
|
||||
rust_vecdeque_prepend_integers(buffer.baseAddress, buffer.count)
|
||||
}
|
||||
}
|
||||
|
||||
self.addSimple(
|
||||
title: "VecDeque<isize> 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<isize> random insertions",
|
||||
input: Insertions.self
|
||||
) { insertions in
|
||||
insertions.values.withUnsafeBufferPointer { buffer in
|
||||
rust_vecdeque_random_insertions(buffer.baseAddress, buffer.count)
|
||||
}
|
||||
}
|
||||
|
||||
self.add(
|
||||
title: "VecDeque<isize> sequential iteration",
|
||||
input: [Int].self
|
||||
) { input in
|
||||
let deque = RustDeque(input)
|
||||
return { timer in
|
||||
rust_vecdeque_iterate(deque.ptr)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<Int>) {}
|
||||
|
||||
@inline(never)
|
||||
fileprivate func append(_ input: UnsafeBufferPointer<Int>) {
|
||||
var deque = UniqueDeque<Int>()
|
||||
for i in input {
|
||||
deque.append(i)
|
||||
}
|
||||
blackHole(deque)
|
||||
}
|
||||
|
||||
@inline(never)
|
||||
fileprivate func appendReserveCapacity(_ input: UnsafeBufferPointer<Int>) {
|
||||
var deque = UniqueDeque<Int>(capacity: input.count)
|
||||
for i in input {
|
||||
deque.append(i)
|
||||
}
|
||||
blackHole(deque)
|
||||
}
|
||||
|
||||
@inline(never)
|
||||
fileprivate func prepend(_ input: UnsafeBufferPointer<Int>) {
|
||||
var deque = UniqueDeque<Int>()
|
||||
for i in input {
|
||||
deque.prepend(i)
|
||||
}
|
||||
blackHole(deque)
|
||||
}
|
||||
|
||||
@inline(never)
|
||||
fileprivate func prependReserveCapacity(_ input: UnsafeBufferPointer<Int>) {
|
||||
var deque = UniqueDeque<Int>(capacity: input.count)
|
||||
for i in input {
|
||||
deque.prepend(i)
|
||||
}
|
||||
blackHole(deque)
|
||||
}
|
||||
|
||||
@inline(never)
|
||||
fileprivate func randomInsertions(_ insertions: UnsafeBufferPointer<Int>) {
|
||||
var deque = UniqueDeque<Int>()
|
||||
for i in insertions.indices {
|
||||
deque.insert(i, at: insertions[i])
|
||||
}
|
||||
blackHole(deque)
|
||||
}
|
||||
|
||||
@inline(never)
|
||||
fileprivate func sequentialIteration(_ deque: borrowing UniqueDeque<Int>) {
|
||||
for i in deque.indices {
|
||||
blackHole(deque[i])
|
||||
}
|
||||
}
|
||||
|
||||
extension Benchmark {
|
||||
public mutating func addUniqueDequeBenchmarks() {
|
||||
self.addSimple(
|
||||
title: "UniqueDeque<Int> append",
|
||||
input: [Int].self
|
||||
) { input in
|
||||
input.withUnsafeBufferPointer {
|
||||
append($0)
|
||||
}
|
||||
}
|
||||
|
||||
self.addSimple(
|
||||
title: "UniqueDeque<Int> append, reserving capacity",
|
||||
input: [Int].self
|
||||
) { input in
|
||||
input.withUnsafeBufferPointer {
|
||||
appendReserveCapacity($0)
|
||||
}
|
||||
}
|
||||
|
||||
self.addSimple(
|
||||
title: "UniqueDeque<Int> prepend",
|
||||
input: [Int].self
|
||||
) { input in
|
||||
input.withUnsafeBufferPointer {
|
||||
prepend($0)
|
||||
}
|
||||
}
|
||||
|
||||
self.addSimple(
|
||||
title: "UniqueDeque<Int> prepend, reserving capacity",
|
||||
input: [Int].self
|
||||
) { input in
|
||||
input.withUnsafeBufferPointer {
|
||||
prependReserveCapacity($0)
|
||||
}
|
||||
}
|
||||
|
||||
self.addSimple(
|
||||
title: "UniqueDeque<Int> random insertions",
|
||||
input: Insertions.self
|
||||
) { insertions in
|
||||
insertions.values.withUnsafeBufferPointer {
|
||||
randomInsertions($0)
|
||||
}
|
||||
}
|
||||
|
||||
self.add(
|
||||
title: "UniqueDeque<Int> sequential iteration",
|
||||
input: [Int].self
|
||||
) { input in
|
||||
let deque = UniqueDeque(copying: input)
|
||||
return { timer in
|
||||
sequentialIteration(deque)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<isize> {
|
||||
let layout = Layout::new::<VecDeque<isize>>();
|
||||
let allocated = alloc(layout) as *mut VecDeque<isize>;
|
||||
|
||||
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<isize>) {
|
||||
ptr.drop_in_place();
|
||||
dealloc(ptr as *mut u8, Layout::new::<VecDeque<isize>>());
|
||||
}
|
||||
|
||||
#[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<isize>;
|
||||
|
||||
for e in &*deque_ptr {
|
||||
black_box(e);
|
||||
}
|
||||
}
|
||||
Whitespace-only changes.
@@ -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()
|
||||
|
||||
+12
-10
@@ -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<Trait> = [
|
||||
.default(
|
||||
enabledTraits: [
|
||||
@@ -35,7 +35,6 @@ let _traits: Set<Trait> = [
|
||||
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<Trait> = [
|
||||
//
|
||||
// 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<String, String> = [
|
||||
@@ -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
|
||||
)
|
||||
@@ -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<String, String> = [
|
||||
@@ -273,7 +276,7 @@ let targets: [CustomTarget] = [
|
||||
.target(
|
||||
kind: .exported,
|
||||
name: "DequeModule",
|
||||
dependencies: ["InternalCollectionsUtilities"],
|
||||
dependencies: ["ContainersPreview", "InternalCollectionsUtilities"],
|
||||
exclude: ["CMakeLists.txt"]),
|
||||
.target(
|
||||
kind: .test,
|
||||
|
||||
@@ -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<Element>`][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<Element>`][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<Element>`][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<Key, Value>`][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
|
||||
|
||||
|
||||
@@ -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"
|
||||
)
|
||||
+46
-46
@@ -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<E: Error, Result: ~Copyable>(
|
||||
count: Int,
|
||||
initializingWith body: (inout OutputSpan<Element>) 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<E: Error>(
|
||||
addingCount newItemCount: Int,
|
||||
initializingWith initializer: (inout OutputSpan<Element>) 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<Element>
|
||||
) {
|
||||
// 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<Element> & ~Copyable & ~Escapable
|
||||
Source: BorrowingSequence<Element> & ~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<Element> & ~Copyable & ~Escapable
|
||||
Source: BorrowingSequence<Element> & ~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<Element> & Sequence<Element>
|
||||
Source: BorrowingSequence<Element> & Sequence<Element>
|
||||
>(copying newElements: Source) {
|
||||
_append(copyingContainer: newElements)
|
||||
_append(copying: newElements)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -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<Int>,
|
||||
consumingWith consumer: (inout InputSpan<Element>) -> Void
|
||||
) {
|
||||
_checkValidBounds(subrange)
|
||||
guard !subrange.isEmpty else {
|
||||
var span = InputSpan<Element>()
|
||||
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<R: RangeExpression<Index>>(
|
||||
_ subrange: R,
|
||||
consumingWith consumer: (inout InputSpan<Element>) -> 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<Element>) -> 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<Element>) -> Void
|
||||
) {
|
||||
precondition(
|
||||
n >= 0 && n <= _count,
|
||||
"Count of elements to consume is out of bounds")
|
||||
self.consume(_count &- n ..< _count, consumingWith: consumer)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -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<Element>.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<Int> { 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<Int>) {
|
||||
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<Element> {
|
||||
_checkItemIndex(index)
|
||||
let p = _storage.baseAddress.unsafelyUnwrapped.advanced(by: index)
|
||||
return UnsafePointer(p)
|
||||
}
|
||||
|
||||
@inlinable @inline(__always)
|
||||
internal mutating func _mutablePtr(
|
||||
to index: Int
|
||||
) -> UnsafeMutablePointer<Element> {
|
||||
_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<Int>
|
||||
/// 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<Element> {
|
||||
_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
|
||||
|
||||
@@ -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<E: Error, Result: ~Copyable>(
|
||||
count: Int,
|
||||
initializingWith initializer: (inout OutputSpan<Element>) 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<Result: ~Copyable>(
|
||||
count: Int,
|
||||
at index: Int,
|
||||
initializingWith body: (inout OutputSpan<Element>) -> 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<Result: ~Copyable>(
|
||||
_ subrange: Range<Int>,
|
||||
newCount: Int,
|
||||
initializingWith body: (inout OutputSpan<Element>) -> 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<Int>,
|
||||
moving newElements: UnsafeMutableBufferPointer<Element>,
|
||||
) {
|
||||
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<Int>,
|
||||
moving items: inout OutputSpan<Element>
|
||||
) {
|
||||
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<Int>,
|
||||
moving newElements: inout RigidArray<Element>,
|
||||
) {
|
||||
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<Int>, newItemCount: Int
|
||||
) -> UnsafeMutableBufferPointer<Element> {
|
||||
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<Int>,
|
||||
copying newElements: UnsafeBufferPointer<Element>
|
||||
) {
|
||||
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<Int>,
|
||||
copying newElements: UnsafeMutableBufferPointer<Element>
|
||||
) {
|
||||
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<Int>,
|
||||
copying newElements: Span<Element>
|
||||
) {
|
||||
self.replace(removing: subrange, copying: newElements)
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
@usableFromInline
|
||||
internal mutating func _replaceSubrange(
|
||||
_ subrange: Range<Int>,
|
||||
copyingCollection newElements: __owned some Collection<Element>,
|
||||
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<Int>,
|
||||
copying newElements: __owned some Collection<Element>
|
||||
) {
|
||||
self.replace(removing: subrange, copying: newElements)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -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
|
||||
@@ -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
|
||||
+2
-2
@@ -22,7 +22,7 @@ extension RigidArray where Element: ~Copyable {
|
||||
@inlinable
|
||||
@_lifetime(borrow self)
|
||||
public func borrowElement(at index: Int) -> Borrow<Element> {
|
||||
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<Element> {
|
||||
precondition(index >= 0 && index < _count)
|
||||
_checkItemIndex(index)
|
||||
return unsafe Mut(
|
||||
unsafeAddress: _storage.baseAddress.unsafelyUnwrapped.advanced(by: index),
|
||||
mutating: &self
|
||||
@@ -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
|
||||
+64
-19
@@ -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<E: Error>(
|
||||
capacity: Int,
|
||||
initializingWith body: (inout OutputSpan<Element>) throws(E) -> Void
|
||||
initializingWith initializer: (inout OutputSpan<Element>) 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<Source: Container<Element> & ~Copyable & ~Escapable>(
|
||||
capacity: Int? = nil,
|
||||
public init<Source: BorrowingSequence<Element> & ~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<Source: BorrowingSequence<Element> & Sequence<Element>>(
|
||||
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<Source: Container<Element> & Sequence<Element>>(
|
||||
public init(
|
||||
capacity: Int? = nil,
|
||||
copying contents: Source
|
||||
copying span: Span<Element>
|
||||
) {
|
||||
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:)
|
||||
+84
-70
@@ -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<Int>(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<Result: ~Copyable>(
|
||||
count: Int,
|
||||
/// - Complexity: O(`self.count` + `newItemCount`) in addition to the complexity
|
||||
/// of the callback invocations.
|
||||
@_alwaysEmitIntoClient
|
||||
@inline(__always)
|
||||
public mutating func insert<E: Error>(
|
||||
addingCount newItemCount: Int,
|
||||
at index: Int,
|
||||
initializingWith body: (inout OutputSpan<Element>) -> 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<Element>) 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<Element>,
|
||||
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<Element>,
|
||||
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<Element>, 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<Element>,
|
||||
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<Element>, 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<Element> & ~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<Element>,
|
||||
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.
|
||||
+21
-101
@@ -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<Int>) {
|
||||
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<Element> {
|
||||
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<Element> {
|
||||
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<E: Error, Result: ~Copyable>(
|
||||
_ bounds: Range<Int>,
|
||||
consumingWith body: (inout InputSpan<Element>) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
precondition(
|
||||
bounds.lowerBound >= 0 && bounds.upperBound <= _count,
|
||||
"Subrange out of bounds")
|
||||
guard !bounds.isEmpty else {
|
||||
var span = InputSpan<Element>()
|
||||
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
|
||||
+271
-125
@@ -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<Result: ~Copyable>(
|
||||
_ subrange: Range<Int>,
|
||||
newCount: Int,
|
||||
initializingWith body: (inout OutputSpan<Element>) -> 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<E: Error>(
|
||||
removing subrange: Range<Int>,
|
||||
addingCount newItemCount: Int,
|
||||
initializingWith initializer: (inout OutputSpan<Element>) 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<E: Error>(
|
||||
removing subrange: Range<Int>,
|
||||
addingCount newItemCount: Int,
|
||||
initializingWith initializer: (inout OutputSpan<Element>) 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<E: Error>(
|
||||
removing subrange: Range<Int>,
|
||||
consumingWith consumer: (inout InputSpan<Element>) -> Void,
|
||||
addingCount newItemCount: Int,
|
||||
initializingWith initializer: (inout OutputSpan<Element>) 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<E: Error>(
|
||||
removing subrange: Range<Int>,
|
||||
consumingWith consumer: (inout InputSpan<Element>) -> Void,
|
||||
addingCount newItemCount: Int,
|
||||
initializingWith initializer: (inout OutputSpan<Element>) 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<Int>,
|
||||
public mutating func replace(
|
||||
removing subrange: Range<Int>,
|
||||
moving newElements: UnsafeMutableBufferPointer<Element>,
|
||||
) {
|
||||
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<Int>,
|
||||
public mutating func replace(
|
||||
removing subrange: Range<Int>,
|
||||
moving items: inout InputSpan<Element>
|
||||
) {
|
||||
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<Int>,
|
||||
public mutating func replace(
|
||||
removing subrange: Range<Int>,
|
||||
moving items: inout OutputSpan<Element>
|
||||
) {
|
||||
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<Int>,
|
||||
public mutating func replace(
|
||||
removing subrange: Range<Int>,
|
||||
moving newElements: inout RigidArray<Element>,
|
||||
) {
|
||||
// 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<Int>,
|
||||
public mutating func replace(
|
||||
removing subrange: Range<Int>,
|
||||
consuming newElements: consuming RigidArray<Element>,
|
||||
) {
|
||||
// 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<Int>,
|
||||
public mutating func replace(
|
||||
removing subrange: Range<Int>,
|
||||
copying newElements: UnsafeBufferPointer<Element>
|
||||
) {
|
||||
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<Int>,
|
||||
public mutating func replace(
|
||||
removing subrange: Range<Int>,
|
||||
copying newElements: UnsafeMutableBufferPointer<Element>
|
||||
) {
|
||||
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<Int>,
|
||||
public mutating func replace(
|
||||
removing subrange: Range<Int>,
|
||||
copying newElements: Span<Element>
|
||||
) {
|
||||
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<Element> & ~Copyable & ~Escapable
|
||||
>(
|
||||
_ subrange: Range<Int>,
|
||||
copyingContainer newElements: borrowing C,
|
||||
removing subrange: Range<Int>,
|
||||
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<Int>,
|
||||
internal mutating func _replace(
|
||||
removing subrange: Range<Int>,
|
||||
copyingCollection newElements: __owned some Collection<Element>,
|
||||
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<Element> & ~Copyable & ~Escapable
|
||||
>(
|
||||
_ subrange: Range<Int>,
|
||||
removing subrange: Range<Int>,
|
||||
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<Int>,
|
||||
public mutating func replace(
|
||||
removing subrange: Range<Int>,
|
||||
copying newElements: __owned some Collection<Element>
|
||||
) {
|
||||
_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<Element> & Collection<Element>
|
||||
>(
|
||||
_ subrange: Range<Int>,
|
||||
removing subrange: Range<Int>,
|
||||
copying newElements: C
|
||||
) {
|
||||
_replaceSubrange(
|
||||
subrange, copyingContainer: newElements, newCount: newElements.count)
|
||||
_replace(
|
||||
removing: subrange,
|
||||
copyingContainer: newElements,
|
||||
newCount: newElements.count)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
+27
-166
@@ -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<Element: ~Copyable>: ~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<Element>, 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<Element>
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@inline(__always)
|
||||
public func startBorrowIteration() -> Span<Element> {
|
||||
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<Int> { unsafe Range(uncheckedBounds: (0, count)) }
|
||||
}
|
||||
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
extension RigidArray where Element: ~Copyable {
|
||||
@inlinable @inline(__always)
|
||||
internal func _ptr(to index: Int) -> UnsafePointer<Element> {
|
||||
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<Element> {
|
||||
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<Element>(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<Int>, withNewCount newCount: Int
|
||||
internal mutating func _resizeGap(
|
||||
in subrange: Range<Int>, to newItemCount: Int
|
||||
) -> UnsafeMutableBufferPointer<Element> {
|
||||
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)
|
||||
}
|
||||
}
|
||||
+60
-35
@@ -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<E: Error, Result: ~Copyable>(
|
||||
count: Int,
|
||||
initializingWith body: (inout OutputSpan<Element>) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
_ensureFreeCapacity(count)
|
||||
return try _storage.append(count: count, initializingWith: body)
|
||||
public mutating func append<E: Error>(
|
||||
addingCount newItemCount: Int,
|
||||
initializingWith initializer: (inout OutputSpan<Element>) 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<Element> & ~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<Element> & ~Copyable & ~Escapable
|
||||
Source: BorrowingSequence<Element> & ~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<Element> & Sequence<Element>
|
||||
Source: BorrowingSequence<Element> & Sequence<Element>
|
||||
>(copying newElements: Source) {
|
||||
_ensureFreeCapacity(newElements.count)
|
||||
_storage._append(copyingContainer: newElements)
|
||||
self._append(copying: newElements)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -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<Int>,
|
||||
consumingWith consumer: (inout InputSpan<Element>) -> 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<R: RangeExpression<Index>>(
|
||||
_ subrange: R,
|
||||
consumingWith consumer: (inout InputSpan<Element>) -> 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<Element>) -> 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<Element>) -> Void
|
||||
) {
|
||||
_storage.consumeLast(n, consumingWith: consumer)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -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<Element>.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<Int> { _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<Int>
|
||||
/// 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<Element> {
|
||||
_storage.nextSpan(after: &index, maximumCount: maximumCount)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -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<E: Error, Result: ~Copyable>(
|
||||
count: Int,
|
||||
initializingWith initializer: (inout OutputSpan<Element>) 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<Result: ~Copyable>(
|
||||
count: Int,
|
||||
at index: Int,
|
||||
initializingWith body: (inout OutputSpan<Element>) -> 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<Result: ~Copyable>(
|
||||
_ subrange: Range<Int>,
|
||||
newCount: Int,
|
||||
initializingWith body: (inout OutputSpan<Element>) -> 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<Int>,
|
||||
moving newElements: UnsafeMutableBufferPointer<Element>,
|
||||
) {
|
||||
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<Int>,
|
||||
moving items: inout OutputSpan<Element>
|
||||
) {
|
||||
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<Int>,
|
||||
moving newElements: inout RigidArray<Element>,
|
||||
) {
|
||||
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<Int>,
|
||||
consuming newElements: consuming RigidArray<Element>,
|
||||
) {
|
||||
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<Int>,
|
||||
copying newElements: UnsafeBufferPointer<Element>
|
||||
) {
|
||||
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<Int>,
|
||||
copying newElements: UnsafeMutableBufferPointer<Element>
|
||||
) {
|
||||
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<Int>,
|
||||
copying newElements: Span<Element>
|
||||
) {
|
||||
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<Int>,
|
||||
copying newElements: __owned some Collection<Element>
|
||||
) {
|
||||
self.replace(removing: subrange, copying: newElements)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -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
|
||||
@@ -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
|
||||
File renamed without changes.
@@ -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
|
||||
+39
-7
@@ -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<Source: Container<Element> & ~Copyable & ~Escapable>(
|
||||
public init<Source: BorrowingSequence<Element> & ~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<Source: Container<Element> & Sequence<Element>>(
|
||||
public init<Source: BorrowingSequence<Element> & Sequence<Element>>(
|
||||
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<Element>
|
||||
) {
|
||||
self.init(capacity: capacity ?? span.count)
|
||||
self.append(copying: span)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
+38
-24
@@ -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<Int>()
|
||||
/// 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<Result: ~Copyable>(
|
||||
count: Int,
|
||||
@_alwaysEmitIntoClient
|
||||
@inline(__always)
|
||||
public mutating func insert<E: Error>(
|
||||
addingCount newItemCount: Int,
|
||||
at index: Int,
|
||||
initializingWith body: (inout OutputSpan<Element>) -> 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<Element>) 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.
|
||||
-53
@@ -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<Element> {
|
||||
_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<Element> {
|
||||
_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<E: Error, Result: ~Copyable>(
|
||||
_ bounds: Range<Int>,
|
||||
consumingWith body: (inout InputSpan<Element>) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
try _storage.consumeSubrange(bounds, consumingWith: body)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
+156
-68
@@ -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<Result: ~Copyable>(
|
||||
_ subrange: Range<Int>,
|
||||
newCount: Int,
|
||||
initializingWith body: (inout OutputSpan<Element>) -> 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<E: Error>(
|
||||
removing subrange: Range<Int>,
|
||||
addingCount newItemCount: Int,
|
||||
initializingWith initializer: (inout OutputSpan<Element>) 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<E: Error>(
|
||||
removing subrange: Range<Int>,
|
||||
consumingWith consumer: (inout InputSpan<Element>) -> Void,
|
||||
addingCount newItemCount: Int,
|
||||
initializingWith initializer: (inout OutputSpan<Element>) 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<Int>,
|
||||
public mutating func replace(
|
||||
removing subrange: Range<Int>,
|
||||
moving newElements: UnsafeMutableBufferPointer<Element>,
|
||||
) {
|
||||
// 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<Int>,
|
||||
public mutating func replace(
|
||||
removing subrange: Range<Int>,
|
||||
moving items: inout InputSpan<Element>
|
||||
) {
|
||||
// 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<Int>,
|
||||
public mutating func replace(
|
||||
removing subrange: Range<Int>,
|
||||
moving items: inout OutputSpan<Element>
|
||||
) {
|
||||
// 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<Int>,
|
||||
public mutating func replace(
|
||||
removing subrange: Range<Int>,
|
||||
moving newElements: inout RigidArray<Element>,
|
||||
) {
|
||||
// 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<Int>,
|
||||
public mutating func replace(
|
||||
removing subrange: Range<Int>,
|
||||
consuming newElements: consuming RigidArray<Element>,
|
||||
) {
|
||||
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<Int>,
|
||||
public mutating func replace(
|
||||
removing subrange: Range<Int>,
|
||||
copying newElements: UnsafeBufferPointer<Element>
|
||||
) {
|
||||
// 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<Int>,
|
||||
public mutating func replace(
|
||||
removing subrange: Range<Int>,
|
||||
copying newElements: UnsafeMutableBufferPointer<Element>
|
||||
) {
|
||||
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<Int>,
|
||||
public mutating func replace(
|
||||
removing subrange: Range<Int>,
|
||||
copying newElements: Span<Element>
|
||||
) {
|
||||
// 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<Element> & ~Copyable & ~Escapable
|
||||
>(
|
||||
_ subrange: Range<Int>,
|
||||
removing subrange: Range<Int>,
|
||||
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<Int>,
|
||||
public mutating func replace(
|
||||
removing subrange: Range<Int>,
|
||||
copying newElements: __owned some Collection<Element>
|
||||
) {
|
||||
// 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
|
||||
}
|
||||
+26
-131
@@ -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<Element: ~Copyable>: ~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<Element: ~Copyable>: ~Copyable {
|
||||
@usableFromInline
|
||||
internal var _storage: RigidArray<Element>
|
||||
|
||||
/// 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<Element>) {
|
||||
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<Element>.BorrowIterator
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@inline(__always)
|
||||
public func startBorrowIteration() -> Span<Element> {
|
||||
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<Int> { _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
|
||||
@@ -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<T: BinaryInteger>(
|
||||
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<T: BinaryInteger>(to type: T.Type) -> T {
|
||||
self._convert(to: T.self).value
|
||||
}
|
||||
|
||||
@inlinable
|
||||
package func _convertExactly<T: BinaryInteger>(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<T: BinaryInteger>(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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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
|
||||
@@ -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})
|
||||
|
||||
+4
-8
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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<Element>: ~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<Element>
|
||||
|
||||
@_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<Element> {
|
||||
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<Element> {
|
||||
let c = maximumCount ?? self.count
|
||||
let result = self.extracting(first: c)
|
||||
self = self.extracting(droppingFirst: c)
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -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"
|
||||
)
|
||||
@@ -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<Element>
|
||||
) -> 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<Element>, Span<Other.Element>) 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<Element> & ~Copyable & ~Escapable
|
||||
>(
|
||||
_ other: borrowing Other,
|
||||
) -> Bool {
|
||||
self.borrowingElementsEqual(other, by: ==)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -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<Element: ~Copyable, E: Error, R: ~Copyable>(
|
||||
of type: Element.Type,
|
||||
capacity: Int,
|
||||
_ body: (inout OutputSpan<Element>) 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<Element>
|
||||
) {
|
||||
// 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<Element>) {
|
||||
// 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<Element>) {
|
||||
// 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<Element>) {
|
||||
// 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<Element>) {
|
||||
// FIXME: This needs to be in the stdlib.
|
||||
source.withUnsafeBufferPointer { buffer in
|
||||
self._append(copying: buffer)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -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<T>) throws(E) -> R
|
||||
) throws(E) -> R {
|
||||
#if compiler(>=6.3)
|
||||
try withUnsafeTemporaryAllocation(of: type, capacity: capacity, body)
|
||||
#else
|
||||
let r: Result<R, E> = withUnsafeTemporaryAllocation(
|
||||
of: T.self, capacity: capacity
|
||||
) { buffer in
|
||||
return Result(catching: { () throws(E) in try body(buffer) })
|
||||
}
|
||||
return try r.get()
|
||||
#endif
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -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<Element>: ~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<Element>?
|
||||
|
||||
/// 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<Element>
|
||||
|
||||
/// 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<Element> {
|
||||
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<Element>? {
|
||||
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<Element> {
|
||||
// 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<Element>) {
|
||||
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<Element> {
|
||||
_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<Element> {
|
||||
//???
|
||||
}
|
||||
}
|
||||
#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<Element> {
|
||||
//???
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -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<Element> {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
extension MutableSpan: BorrowingSequence where Element: ~Copyable {
|
||||
public typealias BorrowingIterator = Span<Element>.BorrowingIterator
|
||||
|
||||
@inlinable
|
||||
public var estimatedCount: EstimatedCount {
|
||||
.exactly(count)
|
||||
}
|
||||
|
||||
@_lifetime(borrow self)
|
||||
@inlinable
|
||||
public func makeBorrowingIterator() -> Span<Element> {
|
||||
self.span
|
||||
}
|
||||
}
|
||||
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
extension OutputSpan: BorrowingSequence where Element: ~Copyable {
|
||||
public typealias BorrowingIterator = Span<Element>.BorrowingIterator
|
||||
|
||||
@inlinable
|
||||
public var estimatedCount: EstimatedCount {
|
||||
.exactly(count)
|
||||
}
|
||||
|
||||
@_lifetime(borrow self)
|
||||
@inlinable
|
||||
public func makeBorrowingIterator() -> Span<Element> {
|
||||
self.span
|
||||
}
|
||||
}
|
||||
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
extension InputSpan: BorrowingSequence where Element: ~Copyable {
|
||||
public typealias BorrowingIterator = Span<Element>.BorrowingIterator
|
||||
|
||||
@inlinable
|
||||
public var estimatedCount: EstimatedCount {
|
||||
.exactly(count)
|
||||
}
|
||||
|
||||
@_lifetime(borrow self)
|
||||
@inlinable
|
||||
public func makeBorrowingIterator() -> Span<Element> {
|
||||
self.span
|
||||
}
|
||||
}
|
||||
|
||||
@available(SwiftStdlib 6.2, *)
|
||||
extension Array: BorrowingSequence {
|
||||
public typealias BorrowingIterator = Span<Element>.BorrowingIterator
|
||||
|
||||
@inlinable
|
||||
public var estimatedCount: EstimatedCount {
|
||||
.exactly(count)
|
||||
}
|
||||
|
||||
@_lifetime(borrow self)
|
||||
@inlinable
|
||||
public func makeBorrowingIterator() -> Span<Element> {
|
||||
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<Bound>) {
|
||||
self._current = .init(repeating: base.lowerBound)
|
||||
self._end = base.upperBound
|
||||
self._progress = false
|
||||
}
|
||||
@inlinable
|
||||
@_lifetime(&self)
|
||||
public mutating func nextSpan(maximumCount: Int) -> Span<Bound> {
|
||||
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<Bound>) {
|
||||
self._current = .init(repeating: base.lowerBound)
|
||||
self._last = base.upperBound
|
||||
self._progress = false
|
||||
}
|
||||
@inlinable
|
||||
@_lifetime(&self)
|
||||
public mutating func nextSpan(maximumCount: Int) -> Span<Bound> {
|
||||
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
|
||||
@@ -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<Element>
|
||||
) -> 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<Element> & ~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<Element> & ~Copyable & ~Escapable
|
||||
>(
|
||||
_ other: borrowing Other,
|
||||
) -> Bool where Element: Equatable {
|
||||
var it1 = self.makeBorrowingIterator()
|
||||
var it2 = other.makeBorrowingIterator()
|
||||
var a = Span<Element>()
|
||||
var b = Span<Element>()
|
||||
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<Element>, Span<Other.Element>) throws(E) -> Bool
|
||||
) throws(E) -> Int {
|
||||
var it1 = self.makeBorrowingIterator()
|
||||
var it2 = other.makeBorrowingIterator()
|
||||
var a = Span<Element>()
|
||||
var b = Span<Other.Element>()
|
||||
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
|
||||
+78
-14
@@ -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<Element>: ~Copyable, ~Escapable {
|
||||
associatedtype Element: ~Copyable /*& ~Escapable*/
|
||||
associatedtype BorrowIterator: BorrowIteratorProtocol<Element> & ~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<Element>: ~Copyable, ~Escapable {
|
||||
associatedtype Element: ~Copyable
|
||||
associatedtype BorrowingIterator: BorrowingIteratorProtocol<Element> & ~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<E: Error>(
|
||||
_ 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<Result: ~Copyable, E: Error>(
|
||||
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 }
|
||||
@@ -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<Element>: 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<Int>
|
||||
/// 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<Element>
|
||||
|
||||
// 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<Element> {
|
||||
nextSpan(after: &index, maximumCount: Int.max)
|
||||
}
|
||||
|
||||
// @inlinable
|
||||
// @_lifetime(borrow self)
|
||||
// public func nextSpan(after index: inout Index, maximumCount: Int) -> Span<Element> {
|
||||
// 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<Base> // 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.Element> {
|
||||
_base[].nextSpan(after: &self._position, maximumCount: maximumCount)
|
||||
}
|
||||
}
|
||||
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
extension Container
|
||||
where
|
||||
Self: ~Copyable /*FIXME: & ~Escapable*/,
|
||||
BorrowingIterator == ContainerIterator<Self>
|
||||
{
|
||||
@_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
|
||||
}
|
||||
|
||||
@@ -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<Other: Container & ~Copyable & ~Escapable, E: Error>(
|
||||
with other: borrowing Other,
|
||||
by process: (Span<Element>, Span<Other.Element>) 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<Element> = .init()
|
||||
var b: Span<Other.Element> = .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
|
||||
@@ -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<Element>: 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<Element>
|
||||
// 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<E: Error, R: ~Copyable>(
|
||||
// _ body: (inout InputSpan<Element>) 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<Element> {
|
||||
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<Element>
|
||||
) 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
|
||||
@@ -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<Element>: ~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<Element>
|
||||
) 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
|
||||
@@ -12,17 +12,25 @@
|
||||
#if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
|
||||
import Builtin
|
||||
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
@frozen
|
||||
@safe
|
||||
public struct Ref<T: ~Copyable>: Copyable, ~Escapable {
|
||||
public struct Borrow<Target: ~Copyable /* FIXME: ~Escapable */>: Copyable, ~Escapable {
|
||||
@usableFromInline
|
||||
package let _pointer: UnsafePointer<T>
|
||||
package let _pointer: UnsafePointer<Target>
|
||||
|
||||
#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<T: ~Copyable>: Copyable, ~Escapable {
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
public init<Owner: ~Copyable & ~Escapable>(
|
||||
unsafeAddress: UnsafePointer<T>,
|
||||
unsafeAddress: UnsafePointer<Target>,
|
||||
borrowing owner: borrowing Owner
|
||||
) {
|
||||
unsafe _pointer = unsafeAddress
|
||||
@@ -41,18 +49,35 @@ public struct Ref<T: ~Copyable>: Copyable, ~Escapable {
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
public init<Owner: ~Copyable & ~Escapable>(
|
||||
unsafeAddress: UnsafePointer<T>,
|
||||
unsafeAddress: UnsafePointer<Target>,
|
||||
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<Wrapped>? {
|
||||
if self == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
let pointer = unsafe UnsafePointer<Wrapped>(
|
||||
Builtin.unprotectedAddressOfBorrow(self)
|
||||
)
|
||||
|
||||
return unsafe Borrow(unsafeAddress: pointer, borrowing: self)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -94,8 +94,8 @@ extension Box where T: ~Copyable {
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
@_lifetime(immortal)
|
||||
public consuming func leak() -> Mut<T> {
|
||||
let result = unsafe Mut<T>(unsafeImmortalAddress: _pointer)
|
||||
public consuming func leak() -> Inout<T> {
|
||||
let result = unsafe Inout<T>(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<T> {
|
||||
unsafe Ref(unsafeAddress: UnsafePointer(_pointer), borrowing: self)
|
||||
public func borrow() -> Borrow<T> {
|
||||
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<T> {
|
||||
unsafe Mut(unsafeAddress: _pointer, mutating: &self)
|
||||
public mutating func mutate() -> Inout<T> {
|
||||
unsafe Inout(unsafeAddress: _pointer, mutating: &self)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -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<T>`, 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<Target>`, one must have exclusive access
|
||||
/// to the instance of `Target`. This is achieved through the 'inout' operator, '&'.
|
||||
@frozen
|
||||
@safe
|
||||
public struct Mut<T: ~Copyable>: ~Copyable, ~Escapable {
|
||||
public struct Inout<Target: ~Copyable /* FIXME: ~Escapable */>: ~Copyable, ~Escapable {
|
||||
@usableFromInline
|
||||
package let _pointer: UnsafeMutablePointer<T>
|
||||
package let _pointer: UnsafeMutablePointer<Target>
|
||||
|
||||
/// Initializes an instance of 'Mut' extending the exclusive access of the
|
||||
/// passed instance.
|
||||
@@ -30,8 +28,8 @@ public struct Mut<T: ~Copyable>: ~Copyable, ~Escapable {
|
||||
/// - Parameter instance: The desired instance to get a mutable reference to.
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
public init(_ instance: inout T) {
|
||||
unsafe _pointer = UnsafeMutablePointer<T>(Builtin.unprotectedAddressOf(&instance))
|
||||
public init(_ instance: inout Target) {
|
||||
unsafe _pointer = UnsafeMutablePointer<Target>(Builtin.unprotectedAddressOf(&instance))
|
||||
}
|
||||
|
||||
/// Unsafely initializes an instance of 'Mut' using the given 'unsafeAddress'
|
||||
@@ -39,7 +37,7 @@ public struct Mut<T: ~Copyable>: ~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<T: ~Copyable>: ~Copyable, ~Escapable {
|
||||
@_transparent
|
||||
@_lifetime(&owner)
|
||||
public init<Owner: ~Copyable & ~Escapable>(
|
||||
unsafeAddress: UnsafeMutablePointer<T>,
|
||||
unsafeAddress: UnsafeMutablePointer<Target>,
|
||||
mutating owner: inout Owner
|
||||
) {
|
||||
unsafe _pointer = unsafeAddress
|
||||
@@ -58,33 +56,64 @@ public struct Mut<T: ~Copyable>: ~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<T>
|
||||
unsafeImmortalAddress: UnsafeMutablePointer<Target>
|
||||
) {
|
||||
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<T>(_pointer)
|
||||
unsafe UnsafePointer<Target>(_pointer)
|
||||
}
|
||||
|
||||
|
||||
@_transparent
|
||||
@_lifetime(self: copy self)
|
||||
unsafeMutableAddress {
|
||||
unsafe _pointer
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
extension Inout where Target: ~Copyable {
|
||||
package func _withUnsafeTarget<E: Error, R: ~Copyable>(
|
||||
_ 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<Wrapped>? {
|
||||
if self == nil {
|
||||
return nil
|
||||
}
|
||||
let pointer = unsafe UnsafeMutablePointer<Wrapped>(
|
||||
Builtin.unprotectedAddressOf(&self))
|
||||
return unsafe Inout(unsafeAddress: pointer, mutating: &self)
|
||||
}
|
||||
|
||||
@_lifetime(&self)
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
public mutating func insert(_ value: consuming Wrapped) -> Inout<Wrapped> {
|
||||
self = .some(value)
|
||||
return mutate()._consumingUnsafelyUnwrap()
|
||||
}
|
||||
|
||||
}
|
||||
#endif
|
||||
+107
-24
@@ -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<Element: ~Copyable>: ~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<Element>.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<Element> {
|
||||
_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<Element>) {
|
||||
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<Element>) {
|
||||
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<Element>) {
|
||||
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<Element> {
|
||||
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<Element: ~Copyable, E: Error, R: ~Copyable>(
|
||||
of type: Element.Type,
|
||||
capacity: Int,
|
||||
_ body: (inout InputSpan<Element>) 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
|
||||
File renamed without changes.
@@ -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"
|
||||
)
|
||||
File renamed without changes.
+9
-11
@@ -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<Element>,
|
||||
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) }
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+2
-2
@@ -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)
|
||||
}
|
||||
File renamed without changes.
+7
-7
@@ -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<Element>
|
||||
File renamed without changes.
+12
-16
@@ -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<Element> {
|
||||
internal func segments() -> _UnsafeDequeSegments<Element> {
|
||||
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<Int>
|
||||
) -> _UnsafeWrappedBuffer<Element> {
|
||||
) -> _UnsafeDequeSegments<Element> {
|
||||
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<Element> {
|
||||
internal func mutableSegments() -> _UnsafeMutableDequeSegments<Element> {
|
||||
assertMutable()
|
||||
return .init(mutating: segments())
|
||||
}
|
||||
@@ -206,7 +206,7 @@ extension Deque._UnsafeHandle {
|
||||
@inline(__always)
|
||||
internal func mutableSegments(
|
||||
forOffsets range: Range<Int>
|
||||
) -> _UnsafeMutableWrappedBuffer<Element> {
|
||||
) -> _UnsafeMutableDequeSegments<Element> {
|
||||
assertMutable()
|
||||
return .init(mutating: segments(forOffsets: range))
|
||||
}
|
||||
@@ -214,7 +214,7 @@ extension Deque._UnsafeHandle {
|
||||
|
||||
extension Deque._UnsafeHandle {
|
||||
@inlinable
|
||||
internal func availableSegments() -> _UnsafeMutableWrappedBuffer<Element> {
|
||||
internal func availableSegments() -> _UnsafeMutableDequeSegments<Element> {
|
||||
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<Element> {
|
||||
) -> _UnsafeMutableDequeSegments<Element> {
|
||||
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<Element> {
|
||||
) -> _UnsafeMutableDequeSegments<Element> {
|
||||
assertMutable()
|
||||
assert(offset >= 0 && offset <= self.count)
|
||||
assert(self.count + gapSize <= capacity)
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -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<Int>(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<Int>(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<E: Error>(
|
||||
maximumCount: Int,
|
||||
initializingWith body: (inout OutputSpan<Element>) 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<Element>
|
||||
) {
|
||||
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<Element>
|
||||
) {
|
||||
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<Element>
|
||||
) {
|
||||
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<Element> & ~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<Element>
|
||||
) {
|
||||
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<Element>
|
||||
) {
|
||||
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<Element>) {
|
||||
unsafe items.withUnsafeBufferPointer { source in
|
||||
unsafe self.append(copying: source)
|
||||
}
|
||||
}
|
||||
|
||||
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
|
||||
@_alwaysEmitIntoClient
|
||||
internal mutating func _append<
|
||||
S: BorrowingSequence<Element> & ~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<S: BorrowingSequence<Element> & ~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<Element>) {
|
||||
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<Element> & Sequence<Element>
|
||||
>(
|
||||
copying items: S
|
||||
) {
|
||||
self._append(copying: items)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -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<Index>,
|
||||
consumingWith consumer: (inout InputSpan<Element>) -> 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<R: RangeExpression<Index>>(
|
||||
_ subrange: R,
|
||||
consumingWith consumer: (inout InputSpan<Element>) -> 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<Element>) -> 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<Element>) -> 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<Element>) -> 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<Index>) -> SubrangeConsumer {
|
||||
SubrangeConsumer(_base: &self, offsetRange: subrange)
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@inline(__always)
|
||||
@_lifetime(&self)
|
||||
public mutating func consume<R: RangeExpression<Index>>(
|
||||
_ 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<RigidDeque>
|
||||
|
||||
@usableFromInline
|
||||
internal var _offsetRange: Range<Int>
|
||||
|
||||
@usableFromInline
|
||||
internal var _buffer1: UnsafeMutableBufferPointer<Element>
|
||||
|
||||
@usableFromInline
|
||||
internal var _buffer2: UnsafeMutableBufferPointer<Element>
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@inline(__always)
|
||||
@_lifetime(&_base)
|
||||
internal init(_base: inout RigidDeque, offsetRange: Range<Int>) {
|
||||
_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<Element> {
|
||||
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
|
||||
@@ -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<Element>
|
||||
|
||||
@usableFromInline
|
||||
internal var _nextSegment: Span<Element>
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@_lifetime(borrow _deque)
|
||||
internal init(_deque: borrowing RigidDeque<Element>) {
|
||||
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<Element> {
|
||||
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<Element> {
|
||||
_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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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<Element> {
|
||||
_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<Element> {
|
||||
_checkItemIndex(index)
|
||||
let slot = _handle.slot(forOffset: index)
|
||||
return Inout(unsafeAddress: _handle.mutablePtr(at: slot), mutating: &self)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -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
|
||||
@@ -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<E: Error>(
|
||||
capacity: Int,
|
||||
initializingWith initializer: (inout OutputSpan<Element>) 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<Element>) {
|
||||
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<P: Producer<Element> & ~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<Element> & ~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<Element>
|
||||
) {
|
||||
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<Element>
|
||||
) {
|
||||
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<Element> & Sequence<Element>
|
||||
>(
|
||||
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<Element> & Collection<Element>
|
||||
>(
|
||||
capacity: Int? = nil,
|
||||
copying contents: S
|
||||
) {
|
||||
self.init(capacity: capacity ?? contents.count)
|
||||
self._append(copying: contents)
|
||||
}
|
||||
#endif
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -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<Int>(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<E: Error>(
|
||||
addingCount newItemCount: Int,
|
||||
at index: Int,
|
||||
initializingWith initializer: (inout OutputSpan<Element>) 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<Element>,
|
||||
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<Element>,
|
||||
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<Element>,
|
||||
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<Element> & ~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<Element>, 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<Element>,
|
||||
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<Element>, 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<Element> & ~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<Element>,
|
||||
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<Element> & ~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<Element>, 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<Element> & Collection<Element>
|
||||
>(
|
||||
copying items: borrowing C, at index: Int
|
||||
) {
|
||||
_insertContainer(
|
||||
at: index, copying: items, newCount: items.count)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -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<Int>(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<Int>(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<E: Error>(
|
||||
addingCount newItemCount: Int,
|
||||
initializingWith body: (inout OutputSpan<Element>) 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<Element>
|
||||
) {
|
||||
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<Element>
|
||||
) {
|
||||
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<Element>
|
||||
) {
|
||||
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<Element> & ~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<Element>
|
||||
) {
|
||||
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<Element>
|
||||
) {
|
||||
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<Element>) {
|
||||
unsafe items.withUnsafeBufferPointer { source in
|
||||
unsafe self.prepend(copying: source)
|
||||
}
|
||||
}
|
||||
|
||||
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
|
||||
@inlinable
|
||||
internal mutating func _prepend<
|
||||
S: BorrowingSequence<Element> & ~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<Element> & ~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<S: BorrowingSequence<Element> & ~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<C: Container<Element> & ~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<Int>` instance
|
||||
/// to a rigid deque of integers.
|
||||
///
|
||||
/// var numbers = RigidDeque<Int>(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<Element>
|
||||
) {
|
||||
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<Int>` instance
|
||||
/// to a rigid deque of integers.
|
||||
///
|
||||
/// var numbers = RigidDeque<Int>(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<Element>
|
||||
) {
|
||||
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<S: BorrowingSequence<Element> & Sequence<Element>>(
|
||||
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<S: BorrowingSequence<Element> & Collection<Element>>(
|
||||
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<C: Container<Element> & Sequence<Element>>(
|
||||
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<C: Container<Element> & Collection<Element>>(
|
||||
copying items: borrowing C
|
||||
) {
|
||||
self._prepend(copying: items, exactCount: items.count)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
@@ -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<Int>) {
|
||||
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
|
||||
Loaded 100 of 164 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user