Merge pull request #508 from lorentey/container-previews-1

First round of noncopyable constructs: `Box`, `RigidArray`, `DynamicArray`
This commit is contained in:
Karoy Lorentey authored and GitHub committed 2025-08-29 18:23:24 -07:00
commit b5fc030a8e
122 files changed
+9099 -424

No files matched your search

+2 -2
View File
@@ -9,8 +9,8 @@ jobs:
name: Test
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@main
with:
linux_exclude_swift_versions: '[{"swift_version": "5.8"}, {"swift_version": "5.9"}]'
windows_exclude_swift_versions: '[{"swift_version": "5.9"}]'
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"}]'
macos_exclude_xcode_versions: '[{"xcode_version": "16.0"}, {"xcode_version": "16.1"}]'
enable_macos_checks: true
enable_wasm_sdk_build: true
+27
View File
@@ -47,6 +47,33 @@ include(CTest)
include(GNUInstallDirs)
include(SwiftSupport)
set(collections_swift_flags
"-enable-upcoming-feature MemberImportVisibility"
"-enable-experimental-feature BuiltinModule"
"-enable-experimental-feature Lifetimes"
"-enable-experimental-feature InoutLifetimeDependence"
)
foreach(flag ${collections_swift_flags})
add_compile_options("$<$<COMPILE_LANGUAGE:Swift>:SHELL:${flag}>")
endforeach()
#add_compile_options("$<$<COMPILE_LANGUAGE:Swift>:SHELL:${collections_swift_flags}>")
set(availability_defs
"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"
)
foreach(def ${availability_defs})
add_compile_options("$<$<COMPILE_LANGUAGE:Swift>:SHELL:-enable-experimental-feature \"AvailabilityMacro=${def}\">")
endforeach()
add_subdirectory(Sources)
# if(BUILD_TESTING)
# add_subdirectory(Tests)
+110 -78
View File
@@ -1,4 +1,4 @@
// swift-tools-version:5.10
// swift-tools-version:6.2
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
@@ -12,12 +12,29 @@
import PackageDescription
let _traits: Set<Trait> = [
.default(
enabledTraits: [
//"UnstableContainersPreview"
]),
.trait(
name: "UnstableContainersPreview",
description: """
Enables source-unstable components of the ContainersPreview module in
swift-collections. This allows experimental use of the Container
protocols and associated algorithms.
"""),
]
// This package recognizes the conditional compilation flags listed below.
// To use enable them, uncomment the corresponding lines or define them
// from the package manager command line:
//
// swift build -Xswiftc -DCOLLECTIONS_INTERNAL_CHECKS
var defines: [String] = [
var defines: [SwiftSetting] = [
.define(
"COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW",
.when(traits: ["UnstableContainersPreview"])),
// Enables internal consistency checks at the end of initializers and
// mutating operations. This can have very significant overhead, so enabling
@@ -26,7 +43,7 @@ var defines: [String] = [
// This is mostly useful while debugging an issue with the implementation of
// the hash table itself. This setting should never be enabled in production
// code.
// "COLLECTIONS_INTERNAL_CHECKS",
// .define("COLLECTIONS_INTERNAL_CHECKS"),
// Hashing collections provided by this package usually seed their hash
// function with the address of the memory location of their storage,
@@ -40,10 +57,10 @@ var defines: [String] = [
// This is mostly useful while debugging an issue with the implementation of
// the hash table itself. This setting should never be enabled in production
// code.
// "COLLECTIONS_DETERMINISTIC_HASHING",
// .define("COLLECTIONS_DETERMINISTIC_HASHING"),
// Enables randomized testing of some data structure implementations.
"COLLECTIONS_RANDOMIZED_TESTING",
.define("COLLECTIONS_RANDOMIZED_TESTING"),
// Enable this to build the sources as a single, large module.
// This removes the distinct modules for each data structure, instead
@@ -52,11 +69,45 @@ var defines: [String] = [
// "COLLECTIONS_SINGLE_MODULE",
]
var _settings: [SwiftSetting] = defines.map { .define($0) }
_settings += [
.enableUpcomingFeature("MemberImportVisibility"),
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 extraSettings: [SwiftSetting] = [
.enableUpcomingFeature("MemberImportVisibility"),
// .strictMemorySafety(),
.enableExperimentalFeature("BuiltinModule"),
.enableExperimentalFeature("Lifetimes"),
.enableExperimentalFeature("InoutLifetimeDependence"),
// .enableExperimentalFeature("SuppressedAssociatedTypes"),
// .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.
]
let _sharedSettings: [SwiftSetting] = (
defines
+ availabilityMacros.map { name, value in
.enableExperimentalFeature("AvailabilityMacro=\(name): \(value)")
}
+ extraSettings
)
let _settings: [SwiftSetting] = _sharedSettings + []
let _testSettings: [SwiftSetting] = _sharedSettings + []
struct CustomTarget {
enum Kind {
case exported
@@ -70,6 +121,8 @@ struct CustomTarget {
var dependencies: [Target.Dependency]
var directory: String
var exclude: [String]
var sources: [String]?
var settings: [SwiftSetting]
}
extension CustomTarget.Kind {
@@ -94,14 +147,18 @@ extension CustomTarget {
name: String,
dependencies: [Target.Dependency] = [],
directory: String? = nil,
exclude: [String] = []
exclude: [String] = [],
sources: [String]? = nil,
settings: [SwiftSetting]? = nil
) -> CustomTarget {
CustomTarget(
kind: kind,
name: name,
dependencies: dependencies,
directory: directory ?? name,
exclude: exclude)
exclude: exclude,
sources: sources,
settings: settings ?? (kind.isTest ? _testSettings : _settings))
}
func toTarget() -> Target {
@@ -117,7 +174,8 @@ extension CustomTarget {
dependencies: dependencies,
path: kind.path(for: directory),
exclude: exclude,
swiftSettings: _settings,
sources: sources,
swiftSettings: settings,
linkerSettings: linkerSettings)
case .test:
return Target.testTarget(
@@ -125,63 +183,17 @@ extension CustomTarget {
dependencies: dependencies,
path: kind.path(for: directory),
exclude: exclude,
swiftSettings: _settings,
swiftSettings: settings,
linkerSettings: linkerSettings)
}
}
}
extension Array where Element == CustomTarget {
func toMonolithicTarget(
name: String,
linkerSettings: [LinkerSetting] = []
) -> Target {
let targets = self.filter { !$0.kind.isTest }
return Target.target(
name: name,
path: "Sources",
exclude: [
"CMakeLists.txt",
"BitCollections/BitCollections.docc",
"Collections/Collections.docc",
"DequeModule/DequeModule.docc",
"HashTreeCollections/HashTreeCollections.docc",
"HeapModule/HeapModule.docc",
"OrderedCollections/OrderedCollections.docc",
] + targets.flatMap { t in
t.exclude.map { "\(t.name)/\($0)" }
},
sources: targets.map { "\($0.directory)" },
swiftSettings: _settings,
linkerSettings: linkerSettings)
}
func toMonolithicTestTarget(
name: String,
dependencies: [Target.Dependency] = [],
linkerSettings: [LinkerSetting] = []
) -> Target {
let targets = self.filter { $0.kind.isTest }
return Target.testTarget(
name: name,
dependencies: dependencies,
path: "Tests",
exclude: [
"README.md",
] + targets.flatMap { t in
t.exclude.map { "\(t.name)/\($0)" }
},
sources: targets.map { "\($0.name)" },
swiftSettings: _settings,
linkerSettings: linkerSettings)
}
}
let targets: [CustomTarget] = [
.target(
kind: .testSupport,
name: "_CollectionsTestSupport",
dependencies: ["InternalCollectionsUtilities"]),
dependencies: ["InternalCollectionsUtilities", "ContainersPreview"]),
.target(
kind: .test,
name: "CollectionsTestSupportTests",
@@ -203,6 +215,25 @@ let targets: [CustomTarget] = [
"UnsafeBitSet/_UnsafeBitSet.swift.gyb",
"UnsafeBufferPointer+Extras.swift.gyb",
"UnsafeMutableBufferPointer+Extras.swift.gyb",
"UnsafeRawBufferPointer+Extras.swift.gyb",
"UnsafeMutableRawBufferPointer+Extras.swift.gyb",
"LifetimeOverride.swift.gyb",
]),
.target(
kind: .exported,
name: "ArrayModule",
dependencies: [
"InternalCollectionsUtilities",
"ContainersPreview",
],
exclude: ["CMakeLists.txt"]
),
.target(
kind: .test,
name: "ArrayTests",
dependencies: [
"ArrayModule", "_CollectionsTestSupport"
]),
.target(
@@ -217,6 +248,18 @@ let targets: [CustomTarget] = [
"BitCollections", "_CollectionsTestSupport", "OrderedCollections"
]),
.target(
kind: .exported,
name: "ContainersPreview",
dependencies: ["InternalCollectionsUtilities"],
exclude: ["CMakeLists.txt"]),
.target(
kind: .test,
name: "ContainersTests",
dependencies: [
"ContainersPreview", "_CollectionsTestSupport"
]),
.target(
kind: .exported,
name: "DequeModule",
@@ -262,7 +305,9 @@ let targets: [CustomTarget] = [
name: "_RopeModule",
dependencies: ["InternalCollectionsUtilities"],
directory: "RopeModule",
exclude: ["CMakeLists.txt"]),
exclude: ["CMakeLists.txt"],
// FIXME: _modify accessors in RopeModule seem to be broken in Swift 6 mode
settings: _sharedSettings + [.swiftLanguageMode(.v5)]),
.target(
kind: .test,
name: "RopeModuleTests",
@@ -294,28 +339,15 @@ let targets: [CustomTarget] = [
exclude: ["CMakeLists.txt"])
]
var _products: [Product] = []
var _targets: [Target] = []
if defines.contains("COLLECTIONS_SINGLE_MODULE") {
_products = [
.library(name: "Collections", targets: ["Collections"]),
]
_targets = [
targets.toMonolithicTarget(name: "Collections"),
targets.toMonolithicTestTarget(
name: "CollectionsTests",
dependencies: ["Collections"]),
]
} else {
_products = targets.compactMap { t in
guard t.kind == .exported else { return nil }
return .library(name: t.name, targets: [t.name])
}
_targets = targets.map { $0.toTarget() }
let _products: [Product] = targets.compactMap { t in
guard t.kind == .exported else { return nil }
return .library(name: t.name, targets: [t.name])
}
let _targets: [Target] = targets.map { $0.toTarget() }
let package = Package(
name: "swift-collections",
products: _products,
traits: _traits,
targets: _targets
)
+387
View File
@@ -0,0 +1,387 @@
// swift-tools-version:6.0
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 - 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 PackageDescription
// This package recognizes the conditional compilation flags listed below.
// To use enable them, uncomment the corresponding lines or define them
// from the package manager command line:
//
// swift build -Xswiftc -DCOLLECTIONS_INTERNAL_CHECKS
var defines: [String] = [
// Enables internal consistency checks at the end of initializers and
// mutating operations. This can have very significant overhead, so enabling
// this setting invalidates all documented performance guarantees.
//
// This is mostly useful while debugging an issue with the implementation of
// the hash table itself. This setting should never be enabled in production
// code.
// "COLLECTIONS_INTERNAL_CHECKS",
// Hashing collections provided by this package usually seed their hash
// function with the address of the memory location of their storage,
// to prevent some common hash table merge/copy operations from regressing to
// quadratic behavior. This setting turns off this mechanism, seeding
// the hash function with the table's size instead.
//
// When used in conjunction with the SWIFT_DETERMINISTIC_HASHING environment
// variable, this enables reproducible hashing behavior.
//
// This is mostly useful while debugging an issue with the implementation of
// the hash table itself. This setting should never be enabled in production
// code.
// "COLLECTIONS_DETERMINISTIC_HASHING",
// Enables randomized testing of some data structure implementations.
"COLLECTIONS_RANDOMIZED_TESTING",
// Enable this to build the sources as a single, large module.
// 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",
]
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 extraSettings: [SwiftSetting] = [
.enableUpcomingFeature("MemberImportVisibility"),
.enableExperimentalFeature("BuiltinModule"),
]
let _sharedSettings: [SwiftSetting] = (
defines.map { .define($0) }
+ availabilityMacros.map { name, value in
.enableExperimentalFeature("AvailabilityMacro=\(name): \(value)")
}
+ extraSettings
)
let _settings: [SwiftSetting] = _sharedSettings + []
let _testSettings: [SwiftSetting] = _sharedSettings + []
struct CustomTarget {
enum Kind {
case exported
case hidden
case test
case testSupport
}
var kind: Kind
var name: String
var dependencies: [Target.Dependency]
var directory: String
var exclude: [String]
var sources: [String]?
var settings: [SwiftSetting]
}
extension CustomTarget.Kind {
func path(for name: String) -> String {
switch self {
case .exported, .hidden: return "Sources/\(name)"
case .test, .testSupport: return "Tests/\(name)"
}
}
var isTest: Bool {
switch self {
case .exported, .hidden: return false
case .test, .testSupport: return true
}
}
}
extension CustomTarget {
static func target(
kind: Kind,
name: String,
dependencies: [Target.Dependency] = [],
directory: String? = nil,
exclude: [String] = [],
sources: [String]? = nil,
settings: [SwiftSetting]? = nil
) -> CustomTarget {
CustomTarget(
kind: kind,
name: name,
dependencies: dependencies,
directory: directory ?? name,
exclude: exclude,
sources: sources,
settings: settings ?? (kind.isTest ? _testSettings : _settings))
}
func toTarget() -> Target {
var linkerSettings: [LinkerSetting] = []
if kind == .testSupport {
linkerSettings.append(
.linkedFramework("XCTest", .when(platforms: [.macOS, .iOS, .watchOS, .tvOS])))
}
switch kind {
case .exported, .hidden, .testSupport:
return Target.target(
name: name,
dependencies: dependencies,
path: kind.path(for: directory),
exclude: exclude,
sources: sources,
swiftSettings: settings,
linkerSettings: linkerSettings)
case .test:
return Target.testTarget(
name: name,
dependencies: dependencies,
path: kind.path(for: directory),
exclude: exclude,
swiftSettings: settings,
linkerSettings: linkerSettings)
}
}
}
extension Array where Element == CustomTarget {
func toMonolithicTarget(
name: String,
linkerSettings: [LinkerSetting] = []
) -> Target {
let targets = self.filter { !$0.kind.isTest }
return Target.target(
name: name,
path: "Sources",
exclude: [
"CMakeLists.txt",
"BitCollections/BitCollections.docc",
"Collections/Collections.docc",
"DequeModule/DequeModule.docc",
"HashTreeCollections/HashTreeCollections.docc",
"HeapModule/HeapModule.docc",
"OrderedCollections/OrderedCollections.docc",
] + targets.flatMap { t in
t.exclude.map { "\(t.name)/\($0)" }
},
sources: targets.map { "\($0.directory)" },
swiftSettings: _settings,
linkerSettings: linkerSettings)
}
@MainActor
func toMonolithicTestTarget(
name: String,
dependencies: [Target.Dependency] = [],
linkerSettings: [LinkerSetting] = []
) -> Target {
let targets = self.filter { $0.kind.isTest }
return Target.testTarget(
name: name,
dependencies: dependencies,
path: "Tests",
exclude: [
"README.md",
] + targets.flatMap { t in
t.exclude.map { "\(t.name)/\($0)" }
},
sources: targets.map { "\($0.name)" },
swiftSettings: _testSettings,
linkerSettings: linkerSettings)
}
}
let targets: [CustomTarget] = [
.target(
kind: .testSupport,
name: "_CollectionsTestSupport",
dependencies: ["InternalCollectionsUtilities", "ContainersPreview"]),
.target(
kind: .test,
name: "CollectionsTestSupportTests",
dependencies: ["_CollectionsTestSupport"]),
.target(
kind: .hidden,
name: "InternalCollectionsUtilities",
exclude: [
"CMakeLists.txt",
"Debugging.swift.gyb",
"Descriptions.swift.gyb",
"IntegerTricks/FixedWidthInteger+roundUpToPowerOfTwo.swift.gyb",
"IntegerTricks/Integer rank.swift.gyb",
"IntegerTricks/UInt+first and last set bit.swift.gyb",
"IntegerTricks/UInt+reversed.swift.gyb",
"RandomAccessCollection+Offsets.swift.gyb",
"UnsafeBitSet/_UnsafeBitSet+Index.swift.gyb",
"UnsafeBitSet/_UnsafeBitSet+_Word.swift.gyb",
"UnsafeBitSet/_UnsafeBitSet.swift.gyb",
"UnsafeBufferPointer+Extras.swift.gyb",
"UnsafeMutableBufferPointer+Extras.swift.gyb",
"UnsafeRawBufferPointer+Extras.swift.gyb",
"UnsafeMutableRawBufferPointer+Extras.swift.gyb",
"LifetimeOverride.swift.gyb",
]),
.target(
kind: .exported,
name: "ArrayModule",
dependencies: [
"InternalCollectionsUtilities",
"ContainersPreview",
],
exclude: ["CMakeLists.txt"]
),
.target(
kind: .test,
name: "ArrayTests",
dependencies: [
"ArrayModule", "_CollectionsTestSupport"
]),
.target(
kind: .exported,
name: "BitCollections",
dependencies: ["InternalCollectionsUtilities"],
exclude: ["CMakeLists.txt"]),
.target(
kind: .test,
name: "BitCollectionsTests",
dependencies: [
"BitCollections", "_CollectionsTestSupport", "OrderedCollections"
]),
.target(
kind: .exported,
name: "ContainersPreview",
dependencies: ["InternalCollectionsUtilities"],
exclude: ["CMakeLists.txt"]),
.target(
kind: .test,
name: "ContainersTests",
dependencies: [
"ContainersPreview", "_CollectionsTestSupport"
]),
.target(
kind: .exported,
name: "DequeModule",
dependencies: ["InternalCollectionsUtilities"],
exclude: ["CMakeLists.txt"]),
.target(
kind: .test,
name: "DequeTests",
dependencies: ["DequeModule", "_CollectionsTestSupport"]),
.target(
kind: .exported,
name: "HashTreeCollections",
dependencies: ["InternalCollectionsUtilities"],
exclude: ["CMakeLists.txt"]),
.target(
kind: .test,
name: "HashTreeCollectionsTests",
dependencies: ["HashTreeCollections", "_CollectionsTestSupport"]),
.target(
kind: .exported,
name: "HeapModule",
dependencies: ["InternalCollectionsUtilities"],
exclude: ["CMakeLists.txt"]),
.target(
kind: .test,
name: "HeapTests",
dependencies: ["HeapModule", "_CollectionsTestSupport"]),
.target(
kind: .exported,
name: "OrderedCollections",
dependencies: ["InternalCollectionsUtilities"],
exclude: ["CMakeLists.txt"]),
.target(
kind: .test,
name: "OrderedCollectionsTests",
dependencies: ["OrderedCollections", "_CollectionsTestSupport"]),
.target(
kind: .exported,
name: "_RopeModule",
dependencies: ["InternalCollectionsUtilities"],
directory: "RopeModule",
exclude: ["CMakeLists.txt"],
// FIXME: _modify accessors in RopeModule seem to be broken in Swift 6 mode
settings: _sharedSettings + [.swiftLanguageMode(.v5)]),
.target(
kind: .test,
name: "RopeModuleTests",
dependencies: ["_RopeModule", "_CollectionsTestSupport"]),
// These aren't ready for production use yet.
// .target(
// kind: .exported,
// name: "SortedCollections",
// dependencies: ["InternalCollectionsUtilities"],
// directory: "SortedCollections"),
// .target(
// kind: .test,
// name: "SortedCollectionsTests",
// dependencies: ["SortedCollections", "_CollectionsTestSupport"]),
.target(
kind: .exported,
name: "Collections",
dependencies: [
"BitCollections",
"DequeModule",
"HashTreeCollections",
"HeapModule",
"OrderedCollections",
"_RopeModule",
//"SortedCollections",
],
exclude: ["CMakeLists.txt"])
]
var _products: [Product] = []
var _targets: [Target] = []
if defines.contains("COLLECTIONS_SINGLE_MODULE") {
_products = [
.library(name: "Collections", targets: ["Collections"]),
]
_targets = [
targets.toMonolithicTarget(name: "Collections"),
targets.toMonolithicTestTarget(
name: "CollectionsTests",
dependencies: ["Collections"]),
]
} else {
_products = targets.compactMap { t in
guard t.kind == .exported else { return nil }
return .library(name: t.name, targets: [t.name])
}
_targets = targets.map { $0.toTarget() }
}
let package = Package(
name: "swift-collections",
products: _products,
targets: _targets
)
+30
View File
@@ -0,0 +1,30 @@
#[[
This source file is part of the Swift Collections Open Source Project
Copyright (c) 2022 - 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)
set(module_name ${COLLECTIONS_MODULE_NAME})
else()
set(module_name ArrayModule)
add_library(ArrayModule
${COLLECTIONS_ARRAY_SOURCES})
target_link_libraries(ArrayModule PRIVATE
InternalCollectionsUtilities ContainersPreview)
set_target_properties(ArrayModule PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
_install_target(ArrayModule)
set_property(GLOBAL APPEND PROPERTY SWIFT_COLLECTIONS_EXPORTS ArrayModule)
endif()
target_sources(${module_name} PRIVATE
"DynamicArray.swift"
"DynamicArray+Experimental.swift"
"RigidArray.swift"
"RigidArray+Experimental.swift"
)
@@ -0,0 +1,365 @@
//===----------------------------------------------------------------------===//
//
// 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
import ContainersPreview
#endif
#if compiler(>=6.2) && (compiler(>=6.3) || !os(Windows)) // FIXME: [2025-08-17] Windows has no 6.2 snapshot with OutputSpan
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
#if FIXME
extension DynamicArray /*where Element: Copyable*/ {
@available(SwiftStdlib 6.2, *)
@_alwaysEmitIntoClient
@inline(__always)
public init<C: Container<Element> & ~Copyable & ~Escapable>(
capacity: Int? = nil,
copying contents: borrowing C
) {
self.init(consuming: RigidArray(capacity: capacity, copying: contents))
}
@available(SwiftStdlib 6.2, *)
@_alwaysEmitIntoClient
@inline(__always)
public init<C: Container<Element> & Sequence<Element>>(
capacity: Int? = nil,
copying contents: C
) {
self.init(consuming: RigidArray(capacity: capacity, copying: contents))
}
}
#endif
#if FIXME
extension DynamicArray where Element: ~Copyable {
@inlinable
@inline(__always)
@_lifetime(borrow self)
public func borrowElement(at index: Int) -> Borrow<Element> {
_storage.borrowElement(at: index)
}
}
#endif
#if FIXME
extension DynamicArray: RandomAccessContainer where Element: ~Copyable {}
#endif
#if FIXME
extension DynamicArray where Element: ~Copyable {
@inlinable
@_lifetime(&self)
public mutating func mutateElement(at index: Int) -> Inout<Element> {
_storage.mutateElement(at: index)
}
}
#endif
extension DynamicArray where Element: ~Copyable {
@available(SwiftStdlib 5.0, *)
@_alwaysEmitIntoClient
@_transparent
internal mutating func _edit<R: ~Copyable>(
freeCapacity: Int,
inPlaceMutation: (inout OutputSpan<Element>) -> R,
reallocatingMutation: (inout InputSpan<Element>, inout OutputSpan<Element>) -> R
) -> R {
if _storage.freeCapacity >= freeCapacity {
return edit(inPlaceMutation)
}
let newCapacity = _grow(freeCapacity: freeCapacity)
return _storage.reallocate(capacity: newCapacity, with: reallocatingMutation)
}
}
#if FIXME
extension DynamicArray where Element: ~Copyable {
/// Removes all the elements that satisfy the given predicate.
///
/// Use this method to remove every element in a container that meets
/// particular criteria. The order of the remaining elements is preserved.
///
/// - Parameter shouldBeRemoved: A closure that takes an element of the
/// sequence as its argument and returns a Boolean value indicating
/// whether the element should be removed from the array.
///
/// - Complexity: O(`count`)
@available(SwiftStdlib 6.2, *)
@_alwaysEmitIntoClient
public mutating func removeAll<E: Error>(
where shouldBeRemoved: (borrowing Element) throws(E) -> Bool
) throws(E) {
// FIXME: Remove this in favor of a standard algorithm.
let suffixStart = try _halfStablePartition(isSuffixElement: shouldBeRemoved)
removeSubrange(suffixStart...)
}
}
#endif
extension DynamicArray where Element: ~Copyable {
@available(SwiftStdlib 5.0, *)
@_alwaysEmitIntoClient
public mutating func append(
moving items: inout InputSpan<Element>
) {
_ensureFreeCapacity(items.count)
_storage.append(moving: &items)
}
@available(SwiftStdlib 5.0, *)
@_alwaysEmitIntoClient
public mutating func append(
moving items: inout OutputSpan<Element>
) {
_ensureFreeCapacity(items.count)
_storage.append(moving: &items)
}
}
extension DynamicArray {
#if FIXME
public mutating func _appendContainer<
C: Container<Element> & ~Copyable & ~Escapable
>(
copying newElements: borrowing C
) {
var i = newElements.startIndex
while true {
let span = newElements.span(after: &i)
if span.isEmpty { break }
self.append(copying: span)
}
}
#endif
#if FIXME
/// Copies the elements of a container 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.
///
/// - Parameters
/// - newElements: A container whose contents to copy into the array.
///
/// - Complexity: O(`newElements.count`), when amortized over many invocations
/// over the same array.
@available(SwiftStdlib 6.2, *)
@_alwaysEmitIntoClient
public mutating func append<
C: Container<Element> & ~Copyable & ~Escapable
>(
copying newElements: borrowing C
) {
_appendContainer(copying: newElements)
}
#endif
#if FIXME
/// Copies the elements of a container 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.
///
/// - Parameters
/// - newElements: A container whose contents to copy into the array.
///
/// - Complexity: O(`newElements.count`), when amortized over many invocations
/// over the same array.
@available(SwiftStdlib 6.2, *)
@_alwaysEmitIntoClient
public mutating func append<
C: Container<Element> & Sequence<Element>
>(
copying newElements: borrowing C
) {
_appendContainer(copying: newElements)
}
#endif
}
#if FIXME
extension DynamicArray {
@available(SwiftStdlib 6.2, *)
@inlinable
internal mutating func _insertContainer<
C: Container<Element> & ~Copyable & ~Escapable
>(
copying newElements: borrowing C, at index: Int
) {
// FIXME: Avoiding moving the subsequent elements twice.
let newCount = newElements.count
_ensureFreeCapacity(newCount)
_storage._insertContainer(
at: index, copying: newElements, newCount: newCount)
}
/// Copies the elements of a container into this array at the specified
/// position.
///
/// The new elements are inserted before the element currently at the
/// specified index. If you pass the array’s `endIndex` as the `index`
/// parameter, then the new elements are appended to the end of the array.
///
/// All existing elements at or following the specified position are moved to
/// make room for the new item.
///
/// If the array does not have sufficient capacity to hold enough elements,
/// then this reallocates the array's storage to extend its capacity.
///
/// - 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(*n* + *m*), where *n* is count of this array and
/// *m* is the count of `newElements`.
@available(SwiftStdlib 6.2, *)
@_alwaysEmitIntoClient
@inline(__always)
public mutating func insert<
C: Container<Element> & ~Copyable & ~Escapable
>(
copying newElements: borrowing C, at index: Int
) {
_insertContainer(copying: newElements, at: index)
}
/// Copies the elements of a container into this array at the specified
/// position.
///
/// The new elements are inserted before the element currently at the
/// specified index. If you pass the array’s `endIndex` as the `index`
/// parameter, then the new elements are appended to the end of the array.
///
/// All existing elements at or following the specified position are moved to
/// make room for the new item.
///
/// If the array does not have sufficient capacity to hold enough elements,
/// then this reallocates the array's storage to extend its capacity.
///
/// - 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(*n* + *m*), where *n* is count of this array and
/// *m* is the count of `newElements`.
@available(SwiftStdlib 6.2, *)
@_alwaysEmitIntoClient
@inline(__always)
public mutating func insert<
C: Container<Element> & Collection<Element>
>(
copying newElements: borrowing C, at index: Int
) {
_insertContainer(copying: newElements, at: index)
}
}
#endif
#if FIXME
extension DynamicArray {
@available(SwiftStdlib 6.2, *)
@inlinable
public mutating func _replaceSubrange<
C: Container<Element> & ~Copyable & ~Escapable
>(
_ subrange: Range<Int>,
copyingContainer newElements: borrowing C
) {
// FIXME: Avoiding moving the subsequent elements twice.
let c = newElements.count
_ensureFreeCapacity(c)
_storage._replaceSubrange(
subrange, copyingContainer: newElements, newCount: c)
}
/// Replaces the specified subrange of elements by copying the elements of
/// the given container.
///
/// This method has the effect of removing the specified range of elements
/// from the 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 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 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.
///
/// - 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(SwiftStdlib 6.2, *)
@inlinable
@inline(__always)
public mutating func replaceSubrange<
C: Container<Element> & ~Copyable & ~Escapable
>(
_ subrange: Range<Int>,
copying newElements: borrowing C
) {
_replaceSubrange(subrange, copyingContainer: newElements)
}
/// Replaces the specified subrange of elements by copying the elements of
/// the given container.
///
/// This method has the effect of removing the specified range of elements
/// from the 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 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 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.
///
/// - 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(SwiftStdlib 6.2, *)
@inlinable
@inline(__always)
public mutating func replaceSubrange<
C: Container<Element> & Collection<Element>
>(
_ subrange: Range<Int>,
copying newElements: borrowing C
) {
_replaceSubrange(subrange, copyingContainer: newElements)
}
}
#endif
#endif
#endif
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,455 @@
//===----------------------------------------------------------------------===//
//
// 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
import ContainersPreview
#endif
#if compiler(>=6.2) && (compiler(>=6.3) || !os(Windows)) // FIXME: [2025-08-17] Windows has no 6.2 snapshot with OutputSpan
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
extension RigidArray /*where Element: Copyable*/ {
#if FIXME
@_alwaysEmitIntoClient
@inline(__always)
public init<C: Container<Element> & Sequence<Element>>(
capacity: Int,
copying contents: C
) {
self.init(capacity: capacity)
self.append(copying: contents)
}
#endif
#if FIXME
@_alwaysEmitIntoClient
@inline(__always)
public init<C: Container<Element> & ~Copyable & ~Escapable>(
capacity: Int? = nil,
copying contents: borrowing C
) {
self.init(capacity: capacity ?? contents.count)
self.append(copying: contents)
}
#endif
#if FIXME
@_alwaysEmitIntoClient
@inline(__always)
public init<C: Container<Element> & Collection<Element>>(
capacity: Int? = nil,
copying contents: C
) {
self.init(capacity: capacity ?? contents.count)
self.append(copying: contents)
}
#endif
}
#if FIXME
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")
return unsafe Borrow(
unsafeAddress: _storage.baseAddress.unsafelyUnwrapped.advanced(by: index),
borrowing: self
)
}
}
#endif
#if FIXME
extension RigidArray: RandomAccessContainer where Element: ~Copyable {
}
#endif
#if FIXME
extension RigidArray where Element: ~Copyable {
@inlinable
@_lifetime(&self)
public mutating func mutateElement(at index: Int) -> Inout<Element> {
precondition(index >= 0 && index < _count)
return unsafe Inout(
unsafeAddress: _storage.baseAddress.unsafelyUnwrapped.advanced(by: index),
mutating: &self
)
}
}
#endif
#if FIXME
extension RigidArray: MutableContainer where Element: ~Copyable {
}
#endif
extension RigidArray where Element: ~Copyable {
@available(SwiftStdlib 5.0, *)
@inlinable
public mutating func reallocate<E: Error, R: ~Copyable>(
capacity: Int,
with body: (
inout InputSpan<Element>,
inout OutputSpan<Element>
) throws(E) -> R
) throws(E) -> R {
var source = InputSpan(buffer: _storage, initializedCount: _count)
let newStorage: UnsafeMutableBufferPointer<Element> = .allocate(
capacity: capacity)
var target = OutputSpan(buffer: newStorage, initializedCount: 0)
defer {
_ = consume source
_storage.deallocate()
_count = target.finalize(for: newStorage)
_storage = newStorage
source = .init()
target = .init()
}
return try body(&source, &target)
}
}
#if FIXME
extension RigidArray where Element: ~Copyable {
/// Removes all the elements that satisfy the given predicate.
///
/// Use this method to remove every element in a container that meets
/// particular criteria. The order of the remaining elements is preserved.
///
/// - Parameter shouldBeRemoved: A closure that takes an element of the
/// sequence as its argument and returns a Boolean value indicating
/// whether the element should be removed from the array.
///
/// - Complexity: O(`count`)
@available(SwiftStdlib 6.2, *)
@_alwaysEmitIntoClient
public mutating func removeAll<E: Error>(
where shouldBeRemoved: (borrowing Element) throws(E) -> Bool
) throws(E) {
// FIXME: Remove this in favor of a standard algorithm.
let suffixStart = try _halfStablePartition(isSuffixElement: shouldBeRemoved)
removeSubrange(suffixStart...)
}
}
#endif
extension RigidArray where Element: ~Copyable {
@_lifetime(&self)
public mutating func popLast(_ count: Int) -> InputSpan<Element> {
let c = Swift.min(count, self.count)
self._count &-= c
let span = InputSpan(
buffer: self._storage._extracting(last: c),
initializedCount: c)
return _overrideLifetime(span, mutating: &self)
}
}
extension RigidArray where Element: ~Copyable {
@available(SwiftStdlib 5.0, *)
@_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
}
}
@available(SwiftStdlib 5.0, *)
@_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
}
}
}
extension RigidArray {
#if FIXME
@inlinable
internal mutating func _appendContainer<
C: Container<Element> & ~Copyable & ~Escapable
>(
copying newElements: borrowing C
) {
let (copied, end) = unsafe _freeSpace._initializePrefix(
copying: newElements)
precondition(end == newElements.endIndex, "RigidArray capacity overflow")
_count += copied
}
#endif
#if FIXME
/// Copies the elements of a container to the end of this array.
///
/// If the array does not have sufficient capacity to hold all items in the
/// container, then this triggers a runtime error.
///
/// - Parameters
/// - newElements: A container whose contents to copy into the array.
///
/// - Complexity: O(`newElements.count`)
@_alwaysEmitIntoClient
@inline(__always)
public mutating func append<C: Container<Element> & ~Copyable & ~Escapable>(
copying newElements: borrowing C
) {
_appendContainer(copying: newElements)
}
#endif
#if FIXME
/// Copies the elements of a container to the end of this array.
///
/// If the array does not have sufficient capacity to hold all items in the
/// container, then this triggers a runtime error.
///
/// - 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<
C: Container<Element> & Sequence<Element>
>(copying newElements: C) {
_appendContainer(copying: newElements)
}
#endif
}
extension RigidArray where Element: ~Copyable {
@available(SwiftStdlib 5.0, *)
@_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.append(moving: source)
count = 0
}
}
@available(SwiftStdlib 5.0, *)
@_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.append(moving: source)
count = 0
}
}
}
extension RigidArray {
#if FIXME
@inlinable
internal mutating func _insertContainer<
C: Container<Element> & ~Copyable & ~Escapable
>(
at index: Int,
copying items: borrowing C,
newCount: Int
) {
precondition(index >= 0 && index <= _count, "Index out of bounds")
precondition(newCount <= freeCapacity, "RigidArray capacity overflow")
let target = unsafe _openGap(at: index, count: newCount)
let (copied, end) = unsafe target._initializePrefix(copying: items)
precondition(
copied == newCount && end == items.endIndex,
"Broken Container: count doesn't match contents")
_count += newCount
}
#endif
#if FIXME
/// Copies the elements of a container into this array at the specified
/// position.
///
/// The new elements are inserted before the element currently at the
/// specified index. If you pass the array’s `endIndex` as the `index`
/// parameter, then the new elements are appended to the end of the array.
///
/// All existing elements at or following the specified position are moved to
/// make room for the new item.
///
/// If the capacity of the array isn't sufficient to accommodate the new
/// elements, then this method triggers a runtime error.
///
/// - 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(*n* + *m*), where *n* is count of this array and
/// *m* is the count of `newElements`.
@_alwaysEmitIntoClient
@inline(__always)
public mutating func insert<
C: Container<Element> & ~Copyable & ~Escapable
>(
copying newElements: borrowing C, at index: Int
) {
_insertContainer(
at: index, copying: newElements, newCount: newElements.count)
}
#endif
#if FIXME
/// Copies the elements of a container into this array at the specified
/// position.
///
/// The new elements are inserted before the element currently at the
/// specified index. If you pass the array’s `endIndex` as the `index`
/// parameter, then the new elements are appended to the end of the array.
///
/// All existing elements at or following the specified position are moved to
/// make room for the new item.
///
/// If the capacity of the array isn't sufficient to accommodate the new
/// elements, then this method triggers a runtime error.
///
/// - 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(*n* + *m*), where *n* is count of this array and
/// *m* is the count of `newElements`.
@_alwaysEmitIntoClient
@inline(__always)
public mutating func insert<
C: Container<Element> & Collection<Element>
>(
copying newElements: borrowing C, at index: Int
) {
_insertContainer(
at: index, copying: newElements, newCount: newElements.count)
}
#endif
}
extension RigidArray {
#if FIXME
@inlinable
public mutating func _replaceSubrange<
C: Container<Element> & ~Copyable & ~Escapable
>(
_ subrange: Range<Int>,
copyingContainer newElements: borrowing C,
newCount: Int
) {
let gap = unsafe _gapForReplacement(of: subrange, withNewCount: newCount)
let (copied, end) = unsafe gap._initializePrefix(copying: newElements)
precondition(
copied == newCount && end == newElements.endIndex,
"Broken Container: count doesn't match contents")
}
#endif
#if FIXME
/// Replaces the specified subrange of elements by copying the elements of
/// the given container.
///
/// This method has the effect of removing the specified range of elements
/// from the 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 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.
///
/// - 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`)
@inlinable
@inline(__always)
public mutating func replaceSubrange<
C: Container<Element> & ~Copyable & ~Escapable
>(
_ subrange: Range<Int>,
copying newElements: borrowing C
) {
_replaceSubrange(
subrange, copyingContainer: newElements, newCount: newElements.count)
}
#endif
#if FIXME
/// Replaces the specified subrange of elements by copying the elements of
/// the given container.
///
/// This method has the effect of removing the specified range of elements
/// from the 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 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.
///
/// - 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`.
@inlinable
@inline(__always)
public mutating func replaceSubrange<
C: Container<Element> & Collection<Element>
>(
_ subrange: Range<Int>,
copying newElements: C
) {
_replaceSubrange(
subrange, copyingContainer: newElements, newCount: newElements.count)
}
#endif
}
#endif
#endif
File diff suppressed because it is too large. Load diff
+4 -1
View File
@@ -54,7 +54,11 @@ else()
add_subdirectory(Collections)
endif()
add_subdirectory(InternalCollectionsUtilities)
add_subdirectory(ContainersPreview)
if(NOT COLLECTIONS_FOUNDATION_TOOLCHAIN_MODULE)
add_subdirectory(ArrayModule)
add_subdirectory(BitCollections)
add_subdirectory(HashTreeCollections)
add_subdirectory(HeapModule)
@@ -62,4 +66,3 @@ endif()
add_subdirectory(DequeModule)
add_subdirectory(OrderedCollections)
add_subdirectory(RopeModule)
add_subdirectory(InternalCollectionsUtilities)
+58
View File
@@ -0,0 +1,58 @@
//===----------------------------------------------------------------------===//
//
// 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
import Builtin
@frozen
@safe
public struct Borrow<T: ~Copyable>: Copyable, ~Escapable {
@usableFromInline
package let _pointer: UnsafePointer<T>
#if compiler(>=6.2) && FIXME
@_lifetime(borrow value)
@_alwaysEmitIntoClient
@_transparent
public init(_ value: borrowing @_addressable T) {
unsafe _pointer = UnsafePointer(Builtin.unprotectedAddressOfBorrow(value))
}
#endif
@_lifetime(borrow owner)
@_alwaysEmitIntoClient
@_transparent
public init<Owner: ~Copyable & ~Escapable>(
unsafeAddress: UnsafePointer<T>,
borrowing owner: borrowing Owner
) {
unsafe _pointer = unsafeAddress
}
@_lifetime(copy owner)
@_alwaysEmitIntoClient
@_transparent
public init<Owner: ~Copyable & ~Escapable>(
unsafeAddress: UnsafePointer<T>,
copying owner: borrowing Owner
) {
unsafe _pointer = unsafeAddress
}
@_alwaysEmitIntoClient
public subscript() -> T {
@_transparent
unsafeAddress {
unsafe _pointer
}
}
}
#endif
+114
View File
@@ -0,0 +1,114 @@
//===----------------------------------------------------------------------===//
//
// 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)
@frozen
@safe
public struct Box<T: ~Copyable>: ~Copyable {
@usableFromInline
internal let _pointer: UnsafeMutablePointer<T>
@_alwaysEmitIntoClient
@_transparent
public init(_ value: consuming T) {
unsafe _pointer = UnsafeMutablePointer<T>.allocate(capacity: 1)
unsafe _pointer.initialize(to: value)
}
@_alwaysEmitIntoClient
@inlinable
deinit {
unsafe _pointer.deinitialize(count: 1)
unsafe _pointer.deallocate()
}
}
extension Box where T: ~Copyable {
@_alwaysEmitIntoClient
public subscript() -> T {
@_transparent
unsafeAddress {
unsafe UnsafePointer<T>(_pointer)
}
@_transparent
unsafeMutableAddress {
unsafe _pointer
}
}
@_alwaysEmitIntoClient
@_transparent
public consuming func consume() -> T {
let result = unsafe _pointer.move()
unsafe _pointer.deallocate()
discard self
return result
}
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
@_alwaysEmitIntoClient
@_transparent
@_lifetime(immortal)
public consuming func leak() -> Inout<T> {
let result = unsafe Inout<T>(unsafeImmortalAddress: _pointer)
discard self
return result
}
#endif
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
@_alwaysEmitIntoClient
@_transparent
@_lifetime(borrow self)
public func borrow() -> Borrow<T> {
unsafe Borrow(unsafeAddress: UnsafePointer(_pointer), borrowing: self)
}
#endif
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
@_alwaysEmitIntoClient
@_transparent
@_lifetime(&self)
public mutating func mutate() -> Inout<T> {
unsafe Inout(unsafeAddress: _pointer, mutating: &self)
}
#endif
}
extension Box where T: Copyable {
@_alwaysEmitIntoClient
@_transparent
public borrowing func copy() -> T {
unsafe _pointer.pointee
}
}
extension Box where T: ~Copyable {
@available(SwiftStdlib 5.0, *)
public var span: Span<T> {
@_alwaysEmitIntoClient
@_lifetime(borrow self)
get {
unsafe Span(_unsafeStart: _pointer, count: 1)
}
}
@available(SwiftStdlib 5.0, *)
public var mutableSpan: MutableSpan<T> {
@_alwaysEmitIntoClient
@_lifetime(&self)
mutating get {
unsafe MutableSpan(_unsafeStart: _pointer, count: 1)
}
}
}
#endif
+31
View File
@@ -0,0 +1,31 @@
#[[
This source file is part of the Swift Collections Open Source Project
Copyright (c) 2022 - 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)
set(module_name ${COLLECTIONS_MODULE_NAME})
else()
set(module_name ContainersPreview)
add_library(ContainersPreview
${COLLECTIONS_CONTAINERS_SOURCES})
target_link_libraries(ContainersPreview PRIVATE
InternalCollectionsUtilities)
set_target_properties(ContainersPreview PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
_install_target(ContainersPreview)
set_property(GLOBAL APPEND PROPERTY SWIFT_COLLECTIONS_EXPORTS ContainersPreview)
endif()
target_sources(${module_name} PRIVATE
"Borrow.swift"
"Box.swift"
"Inout.swift"
"InputSpan.swift"
"Shared.swift"
)
+90
View File
@@ -0,0 +1,90 @@
//===----------------------------------------------------------------------===//
//
// 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
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 an `Inout<T>`, one must have exclusive access
/// to the instance of `T`. This is achieved through the 'inout' operator, '&'.
@frozen
@safe
public struct Inout<T: ~Copyable>: ~Copyable, ~Escapable {
@usableFromInline
package let _pointer: UnsafeMutablePointer<T>
/// Initializes an instance of 'Inout' extending the exclusive access of the
/// passed instance.
///
/// - 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))
}
/// Unsafely initializes an instance of 'Inout' using the given 'unsafeAddress'
/// as the mutable reference based on the lifetime of the given 'owner'
/// argument.
///
/// - Parameter unsafeAddress: The address to use to mutably reference an
/// instance of type 'T'.
/// - Parameter owner: The owning instance that this 'Inout' instance's
/// lifetime is based on.
@unsafe
@_alwaysEmitIntoClient
@_transparent
@_lifetime(&owner)
public init<Owner: ~Copyable & ~Escapable>(
unsafeAddress: UnsafeMutablePointer<T>,
mutating owner: inout Owner
) {
unsafe _pointer = unsafeAddress
}
/// Unsafely initializes an instance of 'Inout' using the given
/// 'unsafeImmortalAddress' as the mutable reference acting as though its
/// lifetime is immortal.
///
/// - Parameter unsafeImmortalAddress: The address to use to mutably reference
/// an immortal instance of type 'T'.
@_lifetime(immortal)
@unsafe
@_alwaysEmitIntoClient
@_transparent
public init(
unsafeImmortalAddress: UnsafeMutablePointer<T>
) {
unsafe _pointer = unsafeImmortalAddress
}
}
extension Inout where T: ~Copyable {
/// Dereferences the mutable reference allowing for in-place reads and writes
/// to the underlying instance.
@_alwaysEmitIntoClient
public subscript() -> T {
@_transparent
unsafeAddress {
unsafe UnsafePointer<T>(_pointer)
}
@_lifetime(copy self)
@_transparent
unsafeMutableAddress {
unsafe _pointer
}
}
}
#endif
+462
View File
@@ -0,0 +1,462 @@
//===----------------------------------------------------------------------===//
//
// 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
#if !COLLECTIONS_SINGLE_MODULE
import InternalCollectionsUtilities
#endif
import Builtin
@safe
@frozen
public struct InputSpan<Element: ~Copyable>: ~Copyable, ~Escapable {
@usableFromInline
internal let _pointer: UnsafeMutableRawPointer?
public let capacity: Int
@usableFromInline
internal var _count: Int
@_alwaysEmitIntoClient
@inlinable
deinit {
if _count > 0 {
let c = _count
unsafe _first().withMemoryRebound(to: Element.self, capacity: _count) {
_ = unsafe $0.deinitialize(count: c)
}
}
}
@_lifetime(immortal)
public init() {
_pointer = nil
capacity = 0
_count = 0
}
}
extension InputSpan: @unchecked Sendable where Element: Sendable & ~Copyable {}
extension InputSpan where Element: ~Copyable {
@_alwaysEmitIntoClient
@_transparent
@unsafe
internal func _start() -> UnsafeMutableRawPointer {
unsafe _pointer.unsafelyUnwrapped
}
@_alwaysEmitIntoClient
@_transparent
@unsafe
internal func _first() -> UnsafeMutableRawPointer {
// NOTE: `_pointer` must be known to be not-nil.
unsafe _start().advanced(by: _count &* MemoryLayout<Element>.stride)
}
@unsafe
@_alwaysEmitIntoClient
@_transparent
internal func _unsafeRawAddressOfSlot(
uncheckedOffset offset: Int
) -> UnsafeMutableRawPointer {
let offset = (capacity &- _count &+ offset) &* MemoryLayout<Element>.stride
return unsafe _start().advanced(by: offset)
}
@unsafe
@_alwaysEmitIntoClient
@_transparent
internal func _unsafeAddressOfElement(
unchecked index: Index
) -> UnsafeMutablePointer<Element> {
_unsafeRawAddressOfSlot(
uncheckedOffset: index
).assumingMemoryBound(to: Element.self)
}
}
extension InputSpan where Element: ~Copyable {
/// Consume the input span and return the number of initialized elements
/// remaining at the end of the underlying memory region.
///
/// This method should be invoked in the scope where the `InputSpan` was
/// created, when it is time to commit the contents of the updated buffer
/// back into the construct that was accessed.
///
/// The context that created the input span is expected to remember what
/// memory region the span is addressing. This consuming method expects to
/// receive a copy of the same buffer pointer as a (loose) proof of ownership.
///
/// - Parameter buffer: The buffer we expect the `InputSpan` to reference.
/// This must be the same region of memory passed to
/// the `InputSpan` initializer.
/// - Returns: The number of initialized elements remaining at the end of the
/// underlying buffer.
@unsafe
@_alwaysEmitIntoClient
public consuming func finalize(
for buffer: UnsafeMutableBufferPointer<Element>
) -> Int {
precondition(
unsafe UnsafeMutableRawPointer(buffer.baseAddress) == self._pointer
&& buffer.count == self.capacity,
"InputSpan identity mismatch")
let count = self._count
discard self
return count
}
}
extension InputSpan {
/// Consume the input span and return the number of initialized elements
/// remaining at the end of the underlying memory region.
///
/// This method should be invoked in the scope where the `InputSpan` was
/// created, when it is time to commit the contents of the updated buffer
/// back into the construct that was accessed.
///
/// The context that created the input span is expected to remember what
/// memory region the span is addressing. This consuming method expects to
/// receive a copy of the same buffer pointer as a (loose) proof of ownership.
///
/// - Parameter buffer: The buffer we expect the `InputSpan` to reference.
/// This must be the same region of memory passed to
/// the `InputSpan` initializer.
/// - Returns: The number of initialized elements remaining at the end of the
/// underlying buffer.
@unsafe
@_alwaysEmitIntoClient
public consuming func finalize(
for buffer: Slice<UnsafeMutableBufferPointer<Element>>
) -> Int {
unsafe finalize(for: UnsafeMutableBufferPointer(rebasing: buffer))
}
}
extension InputSpan where Element: ~Copyable {
/// The number of initialized elements in this span.
@_alwaysEmitIntoClient
public var count: Int { _count }
/// The number of additional elements that can be added to this span.
@_alwaysEmitIntoClient
public var freeCapacity: Int { capacity &- _count }
/// A Boolean value indicating whether the span is empty.
@_alwaysEmitIntoClient
public var isEmpty: Bool { _count == 0 }
/// A Boolean value indicating whether the span is full.
@_alwaysEmitIntoClient
public var isFull: Bool { _count == capacity }
}
extension InputSpan where Element: ~Copyable {
@unsafe
@_alwaysEmitIntoClient
@_lifetime(borrow buffer)
public init(
_uncheckedBuffer buffer: UnsafeMutableBufferPointer<Element>,
initializedCount: Int
) {
unsafe _pointer = .init(buffer.baseAddress)
capacity = buffer.count
_count = initializedCount
}
@unsafe
@_alwaysEmitIntoClient
@_lifetime(borrow buffer)
public init(
buffer: UnsafeMutableBufferPointer<Element>, initializedCount: Int
) {
precondition(buffer._isWellAligned(), "Misaligned OutputSpan")
if let baseAddress = buffer.baseAddress {
precondition(
unsafe baseAddress.advanced(by: buffer.count) >= baseAddress,
"Buffer must not wrap around the address space")
}
precondition(
0 <= initializedCount && initializedCount <= buffer.count,
"OutputSpan count is not within capacity")
unsafe self.init(
_uncheckedBuffer: buffer, initializedCount: initializedCount)
}
}
extension InputSpan {
/// Unsafely create an input span over partially initialized memory.
///
/// The memory in `buffer` must remain valid throughout the lifetime
/// of the newly-created `InputSpan`. There must be exactly
/// `initializedCount` initialized instances at the end of the buffer,
/// preceded by uninitialized memory.
///
/// - Parameters:
/// - buffer: an `UnsafeMutableBufferPointer` with some number of
/// initialized elements, all compacted into the end of the buffer
/// - initializedCount: the number of initialized elements
/// at the end of `buffer`.
@unsafe
@_alwaysEmitIntoClient
@_lifetime(borrow buffer)
public init(
buffer: borrowing Slice<UnsafeMutableBufferPointer<Element>>,
initializedCount: Int
) {
let rebased = unsafe UnsafeMutableBufferPointer(rebasing: buffer)
let os = unsafe InputSpan(
buffer: rebased, initializedCount: initializedCount)
self = unsafe _overrideLifetime(os, borrowing: buffer)
}
}
extension InputSpan where Element: ~Copyable {
/// The type that represents an initialized position in an `InputSpan`.
public typealias Index = Int
/// The range of initialized positions for this `InputSpan`.
@_alwaysEmitIntoClient
public var indices: Range<Index> {
unsafe Range(uncheckedBounds: (0, _count))
}
/// Accesses the element at the specified position.
///
/// - Parameter index: A valid index into this span.
///
/// - Complexity: O(1)
@_alwaysEmitIntoClient
public subscript(_ index: Index) -> Element {
unsafeAddress {
precondition(indices.contains(index), "Index out of bounds")
return unsafe UnsafePointer(_unsafeAddressOfElement(unchecked: index))
}
@_lifetime(self: copy self)
unsafeMutableAddress {
precondition(indices.contains(index), "Index out of bounds")
return unsafe _unsafeAddressOfElement(unchecked: index)
}
}
/// Accesses the element at the specified position.
///
/// This subscript does not validate `position`; this is an unsafe operation.
///
/// - Parameter index: A valid index into this span.
///
/// - Complexity: O(1)
@unsafe
@_alwaysEmitIntoClient
public subscript(unchecked index: Index) -> Element {
unsafeAddress {
unsafe UnsafePointer(_unsafeAddressOfElement(unchecked: index))
}
@_lifetime(self: copy self)
unsafeMutableAddress {
unsafe _unsafeAddressOfElement(unchecked: index)
}
}
/// Exchange the elements at the two given offsets
///
/// - Parameter i: A valid index into this span.
/// - Parameter j: A valid index into this span.
@_alwaysEmitIntoClient
@_lifetime(self: copy self)
public mutating func swapAt(_ i: Index, _ j: Index) {
precondition(indices.contains(Index(i)))
precondition(indices.contains(Index(j)))
unsafe swapAt(unchecked: i, unchecked: j)
}
/// Exchange the elements at the two given offsets
///
/// This subscript does not validate `i` or `j`; this is an unsafe operation.
///
/// - Parameter i: A valid index into this span.
/// - Parameter j: A valid index into this span.
@unsafe
@_alwaysEmitIntoClient
@_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 temporary = unsafe pi.move()
unsafe pi.initialize(to: pj.move())
unsafe pj.initialize(to: consume temporary)
}
}
extension InputSpan where Element: ~Copyable {
/// Prepend a single element to this span.
@_alwaysEmitIntoClient
@_lifetime(self: copy self)
public mutating func prepend(_ value: consuming Element) {
precondition(_count < capacity, "InputSpan capacity overflow")
unsafe _unsafeRawAddressOfSlot(
uncheckedOffset: -1
).initializeMemory(as: Element.self, to: value)
_count &+= 1
}
/// Remove the last initialized element from this span.
///
/// Returns the last element. The `InputSpan` must not be empty.
@_alwaysEmitIntoClient
@_lifetime(self: copy self)
public mutating func removeFirst() -> Element {
precondition(!isEmpty, "InputSpan underflow")
defer { _count &-= 1 }
return _unsafeAddressOfElement(unchecked: 0).move()
}
/// Remove the last N elements of this span, returning the memory they occupy
/// to the uninitialized state.
///
/// `n` must not be greater than `count`
@_alwaysEmitIntoClient
@_lifetime(self: copy self)
public mutating func removeFirst(_ k: Int) {
precondition(k >= 0, "Can't remove a negative number of elements")
precondition(k <= _count, "InputSpan underflow")
unsafe _unsafeRawAddressOfSlot(
uncheckedOffset: 0
).withMemoryRebound(to: Element.self, capacity: k) {
_ = unsafe $0.deinitialize(count: k)
}
_count &-= k
}
/// Remove all this span's elements and return its memory
/// to the uninitialized state.
@_alwaysEmitIntoClient
@_lifetime(self: copy self)
public mutating func removeAll() {
_ = unsafe _start().withMemoryRebound(to: Element.self, capacity: _count) {
unsafe $0.deinitialize(count: _count)
}
_count = 0
}
}
//MARK: Bulk append functions
extension InputSpan {
/// Repeatedly append an element to this span.
@_alwaysEmitIntoClient
@_lifetime(self: copy self)
public mutating func prepend(repeating repeatedValue: Element, count: Int) {
precondition(count <= freeCapacity, "InputSpan capacity overflow")
unsafe _unsafeRawAddressOfSlot(
uncheckedOffset: -count
).initializeMemory(as: Element.self, repeating: repeatedValue, count: count)
_count &+= count
}
}
extension InputSpan where Element: ~Copyable {
/// Borrow the underlying initialized memory for read-only access.
@available(SwiftStdlib 5.0, *)
@_alwaysEmitIntoClient
public var span: Span<Element> {
@_lifetime(borrow self)
borrowing get {
let pointer = unsafe _pointer?
.assumingMemoryBound(to: Element.self)
.advanced(by: capacity &- _count)
let buffer = unsafe UnsafeBufferPointer(start: pointer, count: _count)
let span = unsafe Span(_unsafeElements: buffer)
return unsafe _overrideLifetime(span, borrowing: self)
}
}
/// Exclusively borrow the underlying initialized memory for mutation.
@available(SwiftStdlib 5.0, *)
@_alwaysEmitIntoClient
public var mutableSpan: MutableSpan<Element> {
@_lifetime(&self)
mutating get {
let pointer = unsafe _pointer?
.assumingMemoryBound(to: Element.self)
.advanced(by: capacity &- _count)
let buffer = unsafe UnsafeMutableBufferPointer(
start: pointer, count: _count)
let span = unsafe MutableSpan(_unsafeElements: buffer)
return unsafe _overrideLifetime(span, borrowing: self)
}
}
}
extension InputSpan where Element: ~Copyable {
/// Call the given closure with the unsafe buffer pointer addressed by this
/// InputSpan and a mutable reference to its count of initialized elements.
///
/// This method provides a way to process or consume the contents of an
/// `InputSpan` using unsafe operations, such as by dispatching to code
/// written in legacy (memory-unsafe) languages.
///
/// The supplied closure may process the buffer in any way it wants; however,
/// when it finishes (whether by returning or throwing), it must leave the
/// buffer in a state that satisfies the invariants of the input span:
///
/// 1. The inout integer passed in as the second argument must be the exact
/// number of initialized items in the buffer passed in as the first
/// argument.
/// 2. These initialized elements must be located in a single contiguous
/// region located at the end of the buffer. The initialized region must
/// be preceded by uninitialized memory.
///
/// This function cannot verify these two invariants, and therefore
/// this is an unsafe operation. Violating the invariants of `InputSpan`
/// may result in undefined behavior.
@_alwaysEmitIntoClient
@_lifetime(self: copy self)
public mutating func withUnsafeMutableBufferPointer<E: Error, R: ~Copyable>(
_ body: (
UnsafeMutableBufferPointer<Element>,
_ initializedCount: inout Int
) throws(E) -> R
) throws(E) -> R {
guard let start = unsafe _pointer, capacity > 0 else {
let buffer = UnsafeMutableBufferPointer<Element>(_empty: ())
var initializedCount = 0
defer {
precondition(initializedCount == 0, "InputSpan capacity overflow")
}
return unsafe try body(buffer, &initializedCount)
}
// bind memory by hand to sidestep alignment concerns
let binding = Builtin.bindMemory(
start._rawValue, capacity._builtinWordValue, Element.self
)
defer { Builtin.rebindMemory(start._rawValue, binding) }
let buffer = unsafe UnsafeMutableBufferPointer<Element>(
/*_uncheckedStart*/start: .init(start._rawValue), count: capacity
)
var initializedCount = self._count
defer {
precondition(
0 <= initializedCount && initializedCount <= capacity,
"InputSpan capacity overflow"
)
self._count = initializedCount
}
return unsafe try body(buffer, &initializedCount)
}
}
#endif
+164
View File
@@ -0,0 +1,164 @@
//===----------------------------------------------------------------------===//
//
// 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
import Builtin // For Shared.isIdentical
/// A utility adapter that wraps a noncopyable storage type in a copy-on-write
/// struct, enabling efficient implementation of value semantics. The type
/// allows safe borrowing and mutating access to its storage, with minimal fuss.
///
/// Like `ManagedBufferPointer`, this type is intended to be used within the
/// internal implementation of public types. Instances of it aren't designed
/// to be exposed as public.
@safe
@frozen
public struct Shared<Storage: ~Copyable> {
@usableFromInline
internal var _box: _Box
@inlinable
public init(_ storage: consuming Storage) {
unsafe self._box = _Box(storage)
}
}
extension Shared: @unchecked Sendable where Storage: Sendable & ~Copyable {}
extension Shared where Storage: ~Copyable {
@unsafe
@usableFromInline
internal final class _Box {
@exclusivity(unchecked)
@usableFromInline
internal var storage: Storage
@inlinable
internal init(_ storage: consuming Storage) {
unsafe self.storage = storage
}
}
}
extension Shared where Storage: ~Copyable {
@inlinable
@inline(__always)
public mutating func isUnique() -> Bool {
unsafe isKnownUniquelyReferenced(&_box)
}
/// - Returns true if this instance was already uniquely referenced.
@discardableResult
@inlinable
public mutating func ensureUnique(
cloner: (borrowing Storage) -> Storage
) -> Bool {
if isUnique() { return true }
replace(using: cloner)
return false
}
@inlinable
public mutating func replace(
using body: (borrowing Storage) -> Storage
) {
unsafe _box = _Box(body(_box.storage))
}
@inlinable
public mutating func edit(
shared cloner: (borrowing Storage) -> Storage,
unique updater: (inout Storage) -> Void
) {
if isUnique() {
unsafe updater(&_box.storage)
} else {
unsafe _box = _Box(cloner(_box.storage))
}
}
}
import struct SwiftShims.HeapObject
extension Shared where Storage: ~Copyable {
// FIXME: Can we avoid hacks like this? If not, perhaps `_Box.storage` should be tail-allocated.
@inlinable
internal var _address: UnsafePointer<Storage> {
// Adapted from _getUnsafePointerToStoredProperties
let p = unsafe (
UnsafeRawPointer(Builtin.bridgeToRawPointer(_box))
+ MemoryLayout<HeapObject>.size)
return unsafe p.alignedUp(for: Storage.self).assumingMemoryBound(to: Storage.self)
}
@inlinable
internal var _mutableAddress: UnsafeMutablePointer<Storage> {
// Adapted from _getUnsafePointerToStoredProperties
let p = unsafe (
UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(_box))
+ MemoryLayout<HeapObject>.size)
return unsafe p.alignedUp(for: Storage.self).assumingMemoryBound(to: Storage.self)
}
}
extension Shared where Storage: ~Copyable {
@inlinable
@inline(__always)
public var value: Storage {
@_lifetime(borrow self)
unsafeAddress {
unsafe _address
}
@_lifetime(&self)
unsafeMutableAddress {
precondition(isUnique())
return unsafe _mutableAddress
}
}
}
extension Shared where Storage: ~Copyable {
@inlinable
@_lifetime(borrow self)
public borrowing func borrow() -> Borrow<Storage> {
// This is gloriously (and very explicitly) unsafe, as it should be.
// `Shared` is carefully constructed to guarantee that
// lifetime(self) == lifetime(_box.storage).
unsafe Borrow(unsafeAddress: _address, borrowing: self)
}
@inlinable
@_lifetime(&self)
public mutating func mutate() -> Inout<Storage> {
// This is gloriously (and very explicitly) unsafe, as it should be.
// `Shared` is carefully constructed to guarantee that
// lifetime(self) == lifetime(_box.storage).
unsafe Inout(unsafeAddress: _mutableAddress, mutating: &self)
}
}
extension Shared where Storage: ~Copyable {
@inlinable
public func isIdentical(to other: Self) -> Bool {
if #available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) {
return unsafe self._box === other._box
} else {
// To call the standard `===`, we need to do `_SharedBox` -> AnyObject conversions
// that are only supported in the Swift 6+ runtime.
let a = unsafe Builtin.bridgeToRawPointer(self._box)
let b = unsafe Builtin.bridgeToRawPointer(other._box)
return Bool(Builtin.cmp_eq_RawPointer(a, b))
}
}
}
#endif
@@ -23,9 +23,12 @@ endif()
target_sources(${module_name} PRIVATE
"autogenerated/Debugging.swift"
"autogenerated/Descriptions.swift"
"autogenerated/LifetimeOverride.swift"
"autogenerated/RandomAccessCollection+Offsets.swift"
"autogenerated/UnsafeBufferPointer+Extras.swift"
"autogenerated/UnsafeMutableBufferPointer+Extras.swift"
"autogenerated/UnsafeRawBufferPointer+Extras.swift"
"autogenerated/UnsafeMutableRawBufferPointer+Extras.swift"
"IntegerTricks/autogenerated/FixedWidthInteger+roundUpToPowerOfTwo.swift"
"IntegerTricks/autogenerated/Integer rank.swift"
"IntegerTricks/autogenerated/UInt+first and last set bit.swift"
@@ -0,0 +1,93 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org 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
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
%{
from gyb_utils import *
}%
${autogenerated_warning()}
#if compiler(>=6.2)
% for modifier in visibility_levels:
${visibility_boilerplate(modifier)}
/// Unsafely discard any lifetime dependency on the `dependent` argument.
/// Return a value identical to `dependent` with an immortal lifetime.
@unsafe
@_unsafeNonescapableResult
@_alwaysEmitIntoClient
@_transparent
@_lifetime(immortal)
${modifier} func _unsafeImmortalize<T: ~Copyable & ~Escapable>(
_ dependent: consuming T
) -> T {
// TODO: Remove @_unsafeNonescapableResult. Instead, the unsafe dependence
// should be expressed by a builtin that is hidden within the function body.
dependent
}
/// Unsafely discard any lifetime dependency on the `dependent` argument.
/// Return a value identical to `dependent` with a lifetime dependency
/// on the caller's borrow scope of the `source` argument.
@unsafe
@_unsafeNonescapableResult
@_alwaysEmitIntoClient
@_transparent
@_lifetime(borrow source)
${modifier} func _overrideLifetime<
T: ~Copyable & ~Escapable, U: ~Copyable & ~Escapable
>(
_ dependent: consuming T, borrowing source: borrowing U
) -> T {
// TODO: Remove @_unsafeNonescapableResult. Instead, the unsafe dependence
// should be expressed by a builtin that is hidden within the function body.
dependent
}
/// Unsafely discard any lifetime dependency on the `dependent` argument.
/// Return a value identical to `dependent` that inherits
/// all lifetime dependencies from the `source` argument.
@unsafe
@_unsafeNonescapableResult
@_alwaysEmitIntoClient
@_transparent
@_lifetime(copy source)
${modifier} func _overrideLifetime<
T: ~Copyable & ~Escapable, U: ~Copyable & ~Escapable
>(
_ dependent: consuming T, copying source: borrowing U
) -> T {
// TODO: Remove @_unsafeNonescapableResult. Instead, the unsafe dependence
// should be expressed by a builtin that is hidden within the function body.
dependent
}
/// Unsafely discard any lifetime dependency on the `dependent` argument.
/// Return a value identical to `dependent` with a lifetime dependency
/// on the caller's exclusive borrow scope of the `source` argument.
@unsafe
@_unsafeNonescapableResult
@_alwaysEmitIntoClient
@_transparent
@_lifetime(&source)
${modifier} func _overrideLifetime<
T: ~Copyable & ~Escapable,
U: ~Copyable & ~Escapable
>(
_ dependent: consuming T,
mutating source: inout U
) -> T {
// TODO: Remove @_unsafeNonescapableResult. Instead, the unsafe dependence
// should be expressed by a builtin that is hidden within the function body.
dependent
}
% end
${visibility_boilerplate("end")}
#endif
@@ -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 - 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
@@ -24,5 +24,63 @@ extension UnsafeBufferPointer {
return baseAddress.unsafelyUnwrapped + index
}
}
extension UnsafeBufferPointer where Element: ~Copyable {
/// Returns a Boolean value indicating whether two `UnsafeBufferPointer`
/// instances refer to the same region in memory.
@inlinable @inline(__always)
${modifier} func _isIdentical(to other: Self) -> Bool {
(self.baseAddress == other.baseAddress) && (self.count == other.count)
}
}
extension UnsafeBufferPointer where Element: ~Copyable {
/// Returns a buffer pointer containing the initial elements of this buffer,
/// up to the specified maximum length.
///
/// If the maximum length exceeds the length of this buffer pointer,
/// then the result contains all the elements.
///
/// The returned buffer's first item is always at offset 0; unlike buffer
/// slices, extracted buffers do not share their indices with the
/// buffer from which they are extracted.
///
/// - Parameter maxLength: The maximum number of elements to return.
/// `maxLength` must be greater than or equal to zero.
/// - Returns: A buffer pointer with at most `maxLength` elements.
///
/// - Complexity: O(1)
@_alwaysEmitIntoClient
@inline(__always)
public func _extracting(first maxLength: Int) -> Self {
precondition(maxLength >= 0, "Can't have a prefix of negative length")
let newCount = Swift.min(maxLength, count)
return Self(start: baseAddress, count: newCount)
}
/// Returns a buffer pointer containing the final elements of this buffer,
/// up to the given maximum length.
///
/// If the maximum length exceeds the length of this buffer pointer,
/// the result contains all the elements.
///
/// The returned buffer's first item is always at offset 0; unlike buffer
/// slices, extracted buffers do not share their indices with the
/// span from which they are extracted.
///
/// - Parameter maxLength: The maximum number of elements to return.
/// `maxLength` must be greater than or equal to zero.
/// - Returns: A buffer pointer with at most `maxLength` elements.
///
/// - Complexity: O(1)
@_alwaysEmitIntoClient
@inline(__always)
public func _extracting(last maxLength: Int) -> Self {
precondition(maxLength >= 0, "Can't have a suffix of negative length")
let newCount = Swift.min(maxLength, count)
return extracting(Range(uncheckedBounds: (count - newCount, count)))
}
}
% end
${visibility_boilerplate("end")}
@@ -2,7 +2,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 - 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
@@ -16,6 +16,188 @@ ${autogenerated_warning()}
% for modifier in visibility_levels:
${visibility_boilerplate(modifier)}
extension UnsafeMutableBufferPointer where Element: ~Copyable {
/// Returns a Boolean value indicating whether two
/// `UnsafeMutableBufferPointer` instances refer to the same region in
/// memory.
@inlinable @inline(__always)
${modifier} func _isIdentical(to other: Self) -> Bool {
(self.baseAddress == other.baseAddress) && (self.count == other.count)
}
}
extension UnsafeMutableBufferPointer where Element: ~Copyable {
/// Returns a buffer pointer containing the initial elements of this buffer,
/// up to the specified maximum length.
///
/// If the maximum length exceeds the length of this buffer pointer,
/// then the result contains all the elements.
///
/// The returned buffer's first item is always at offset 0; unlike buffer
/// slices, extracted buffers do not share their indices with the
/// buffer from which they are extracted.
///
/// - Parameter maxLength: The maximum number of elements to return.
/// `maxLength` must be greater than or equal to zero.
/// - Returns: A buffer pointer with at most `maxLength` elements.
///
/// - Complexity: O(1)
@_alwaysEmitIntoClient
@inline(__always)
public func _extracting(first maxLength: Int) -> Self {
precondition(maxLength >= 0, "Can't have a prefix of negative length")
let newCount = Swift.min(maxLength, count)
return Self(start: baseAddress, count: newCount)
}
/// Returns a buffer pointer containing the final elements of this buffer,
/// up to the given maximum length.
///
/// If the maximum length exceeds the length of this buffer pointer,
/// the result contains all the elements.
///
/// The returned buffer's first item is always at offset 0; unlike buffer
/// slices, extracted buffers do not share their indices with the
/// buffer from which they are extracted.
///
/// - Parameter maxLength: The maximum number of elements to return.
/// `maxLength` must be greater than or equal to zero.
/// - Returns: A buffer pointer with at most `maxLength` elements.
///
/// - Complexity: O(1)
@_alwaysEmitIntoClient
@inline(__always)
public func _extracting(last maxLength: Int) -> Self {
precondition(maxLength >= 0, "Can't have a suffix of negative length")
let newCount = Swift.min(maxLength, count)
return extracting(Range(uncheckedBounds: (count - newCount, count)))
}
}
extension UnsafeMutableBufferPointer where Element: ~Copyable {
@inlinable
${modifier} func _moveInitializePrefix(
from source: UnsafeMutableBufferPointer<Element>
) -> Int {
if source.isEmpty { return 0 }
precondition(source.count <= self.count)
self.baseAddress.unsafelyUnwrapped.moveInitialize(
from: source.baseAddress.unsafelyUnwrapped, count: source.count)
return source.count
}
}
extension UnsafeMutableBufferPointer {
/// Initialize slots at the start of this buffer by copying data from `source`.
///
/// If `Element` is not bitwise copyable, then the memory region addressed by `self` must be
/// entirely uninitialized, while `source` must be fully initialized.
///
/// The `source` buffer must fit entirely in `self`.
///
/// - Returns: The index after the last item that was initialized in this buffer.
@inlinable
${modifier} func _initializePrefix(
copying source: UnsafeBufferPointer<Element>
) -> Int {
if source.isEmpty { return 0 }
precondition(source.count <= self.count)
self.baseAddress.unsafelyUnwrapped.initialize(
from: source.baseAddress.unsafelyUnwrapped, count: source.count)
return source.count
}
@inlinable
${modifier} func _initializePrefix(
copying source: UnsafeMutableBufferPointer<Element>
) -> Int {
_initializePrefix(copying: UnsafeBufferPointer(source))
}
#if compiler(>=6.2)
/// Initialize slots at the start of this buffer by copying data from `source`.
///
/// If `Element` is not bitwise copyable, then the memory region addressed by `self` must be
/// entirely uninitialized.
///
/// The `source` span must fit entirely in `self`.
///
/// - Returns: The index after the last item that was initialized in this buffer.
@available(SwiftStdlib 6.2, *)
@inlinable
${modifier} func _initializePrefix(copying source: Span<Element>) -> Int {
source.withUnsafeBufferPointer { self._initializePrefix(copying: $0) }
}
#endif
#if compiler(>=6.2) && FIXME
/// Initialize all slots in this buffer by copying data from `items`, which must fit entirely
/// in this buffer.
///
/// If `items` contains more elements than can fit into this buffer, then this function
/// will return an index other than `items.endIndex`. In that case, `self` may not be fully
/// populated.
///
/// If `Element` is not bitwise copyable, then this function must be called on an
/// entirely uninitialized buffer.
///
/// - Returns: A pair of values `(count, end)`, where `count` is the number of items that were
/// successfully initialized, and `end` is the index into `items` after the last copied item.
@available(SwiftStdlib 6.2, *)
@inlinable
${modifier} func _initializePrefix<
C: Container<Element> & ~Copyable & ~Escapable
>(
copying items: borrowing C
) -> (copied: Int, end: C.Index) {
var target = self
var i = items.startIndex
while true {
let start = i
let span = items.span(after: &i)
if span.isEmpty { break }
guard span.count <= target.count else {
return (self.count - target.count, start)
}
target._initializeAndDropPrefix(copying: span)
}
return (self.count - target.count, i)
}
#endif
/// Initialize slots at the start of this buffer by copying data from `buffer`, then
/// shrink `self` to drop all initialized items from its front, leaving it addressing the
/// uninitialized remainder.
///
/// If `Element` is not bitwise copyable, then the memory region addressed by `self` must be
/// entirely uninitialized, while `buffer` must be fully initialized.
///
/// The count of `buffer` must not be greater than `self.count`.
@inlinable
${modifier} mutating func _initializeAndDropPrefix(copying source: UnsafeBufferPointer<Element>) {
let i = _initializePrefix(copying: source)
self = self.extracting(i...)
}
#if compiler(>=6.2)
/// Initialize slots at the start of this buffer by copying data from `span`, then
/// shrink `self` to drop all initialized items from its front, leaving it addressing the
/// uninitialized remainder.
///
/// If `Element` is not bitwise copyable, then the memory region addressed by `self` must be
/// entirely uninitialized.
///
/// The count of `span` must not be greater than `self.count`.
@available(SwiftStdlib 5.0, *)
@inlinable
${modifier} mutating func _initializeAndDropPrefix(copying span: Span<Element>) {
span.withUnsafeBufferPointer { buffer in
self._initializeAndDropPrefix(copying: buffer)
}
}
#endif
}
extension UnsafeMutableBufferPointer {
@inlinable
${modifier} func initialize(fromContentsOf source: Self) -> Index {
@@ -0,0 +1,30 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
%{
from gyb_utils import *
}%
${autogenerated_warning()}
% for modifier in visibility_levels:
${visibility_boilerplate(modifier)}
extension UnsafeMutableRawBufferPointer {
/// Returns a Boolean value indicating whether two
/// `UnsafeMutableRawBufferPointer` instances refer to the same region in
/// memory.
@inlinable @inline(__always)
${modifier} func _isIdentical(to other: Self) -> Bool {
(self.baseAddress == other.baseAddress) && (self.count == other.count)
}
}
% end
${visibility_boilerplate("end")}
@@ -0,0 +1,29 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
%{
from gyb_utils import *
}%
${autogenerated_warning()}
% for modifier in visibility_levels:
${visibility_boilerplate(modifier)}
extension UnsafeRawBufferPointer {
/// Returns a Boolean value indicating whether two `UnsafeRawBufferPointer`
/// instances refer to the same region in memory.
@inlinable @inline(__always)
${modifier} func _isIdentical(to other: Self) -> Bool {
(self.baseAddress == other.baseAddress) && (self.count == other.count)
}
}
% end
${visibility_boilerplate("end")}
@@ -0,0 +1,169 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org 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
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// #############################################################################
// # #
// # DO NOT EDIT THIS FILE; IT IS AUTOGENERATED. #
// # #
// #############################################################################
#if compiler(>=6.2)
// In single module mode, we need these declarations to be internal,
// but in regular builds we want them to be public. Unfortunately
// the current best way to do this is to duplicate all definitions.
#if COLLECTIONS_SINGLE_MODULE
/// Unsafely discard any lifetime dependency on the `dependent` argument.
/// Return a value identical to `dependent` with an immortal lifetime.
@unsafe
@_unsafeNonescapableResult
@_alwaysEmitIntoClient
@_transparent
@_lifetime(immortal)
internal func _unsafeImmortalize<T: ~Copyable & ~Escapable>(
_ dependent: consuming T
) -> T {
// TODO: Remove @_unsafeNonescapableResult. Instead, the unsafe dependence
// should be expressed by a builtin that is hidden within the function body.
dependent
}
/// Unsafely discard any lifetime dependency on the `dependent` argument.
/// Return a value identical to `dependent` with a lifetime dependency
/// on the caller's borrow scope of the `source` argument.
@unsafe
@_unsafeNonescapableResult
@_alwaysEmitIntoClient
@_transparent
@_lifetime(borrow source)
internal func _overrideLifetime<
T: ~Copyable & ~Escapable, U: ~Copyable & ~Escapable
>(
_ dependent: consuming T, borrowing source: borrowing U
) -> T {
// TODO: Remove @_unsafeNonescapableResult. Instead, the unsafe dependence
// should be expressed by a builtin that is hidden within the function body.
dependent
}
/// Unsafely discard any lifetime dependency on the `dependent` argument.
/// Return a value identical to `dependent` that inherits
/// all lifetime dependencies from the `source` argument.
@unsafe
@_unsafeNonescapableResult
@_alwaysEmitIntoClient
@_transparent
@_lifetime(copy source)
internal func _overrideLifetime<
T: ~Copyable & ~Escapable, U: ~Copyable & ~Escapable
>(
_ dependent: consuming T, copying source: borrowing U
) -> T {
// TODO: Remove @_unsafeNonescapableResult. Instead, the unsafe dependence
// should be expressed by a builtin that is hidden within the function body.
dependent
}
/// Unsafely discard any lifetime dependency on the `dependent` argument.
/// Return a value identical to `dependent` with a lifetime dependency
/// on the caller's exclusive borrow scope of the `source` argument.
@unsafe
@_unsafeNonescapableResult
@_alwaysEmitIntoClient
@_transparent
@_lifetime(&source)
internal func _overrideLifetime<
T: ~Copyable & ~Escapable,
U: ~Copyable & ~Escapable
>(
_ dependent: consuming T,
mutating source: inout U
) -> T {
// TODO: Remove @_unsafeNonescapableResult. Instead, the unsafe dependence
// should be expressed by a builtin that is hidden within the function body.
dependent
}
#else // !COLLECTIONS_SINGLE_MODULE
/// Unsafely discard any lifetime dependency on the `dependent` argument.
/// Return a value identical to `dependent` with an immortal lifetime.
@unsafe
@_unsafeNonescapableResult
@_alwaysEmitIntoClient
@_transparent
@_lifetime(immortal)
public func _unsafeImmortalize<T: ~Copyable & ~Escapable>(
_ dependent: consuming T
) -> T {
// TODO: Remove @_unsafeNonescapableResult. Instead, the unsafe dependence
// should be expressed by a builtin that is hidden within the function body.
dependent
}
/// Unsafely discard any lifetime dependency on the `dependent` argument.
/// Return a value identical to `dependent` with a lifetime dependency
/// on the caller's borrow scope of the `source` argument.
@unsafe
@_unsafeNonescapableResult
@_alwaysEmitIntoClient
@_transparent
@_lifetime(borrow source)
public func _overrideLifetime<
T: ~Copyable & ~Escapable, U: ~Copyable & ~Escapable
>(
_ dependent: consuming T, borrowing source: borrowing U
) -> T {
// TODO: Remove @_unsafeNonescapableResult. Instead, the unsafe dependence
// should be expressed by a builtin that is hidden within the function body.
dependent
}
/// Unsafely discard any lifetime dependency on the `dependent` argument.
/// Return a value identical to `dependent` that inherits
/// all lifetime dependencies from the `source` argument.
@unsafe
@_unsafeNonescapableResult
@_alwaysEmitIntoClient
@_transparent
@_lifetime(copy source)
public func _overrideLifetime<
T: ~Copyable & ~Escapable, U: ~Copyable & ~Escapable
>(
_ dependent: consuming T, copying source: borrowing U
) -> T {
// TODO: Remove @_unsafeNonescapableResult. Instead, the unsafe dependence
// should be expressed by a builtin that is hidden within the function body.
dependent
}
/// Unsafely discard any lifetime dependency on the `dependent` argument.
/// Return a value identical to `dependent` with a lifetime dependency
/// on the caller's exclusive borrow scope of the `source` argument.
@unsafe
@_unsafeNonescapableResult
@_alwaysEmitIntoClient
@_transparent
@_lifetime(&source)
public func _overrideLifetime<
T: ~Copyable & ~Escapable,
U: ~Copyable & ~Escapable
>(
_ dependent: consuming T,
mutating source: inout U
) -> T {
// TODO: Remove @_unsafeNonescapableResult. Instead, the unsafe dependence
// should be expressed by a builtin that is hidden within the function body.
dependent
}
#endif // COLLECTIONS_SINGLE_MODULE
#endif
@@ -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 - 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
@@ -30,6 +30,63 @@ extension UnsafeBufferPointer {
return baseAddress.unsafelyUnwrapped + index
}
}
extension UnsafeBufferPointer where Element: ~Copyable {
/// Returns a Boolean value indicating whether two `UnsafeBufferPointer`
/// instances refer to the same region in memory.
@inlinable @inline(__always)
internal func _isIdentical(to other: Self) -> Bool {
(self.baseAddress == other.baseAddress) && (self.count == other.count)
}
}
extension UnsafeBufferPointer where Element: ~Copyable {
/// Returns a buffer pointer containing the initial elements of this buffer,
/// up to the specified maximum length.
///
/// If the maximum length exceeds the length of this buffer pointer,
/// then the result contains all the elements.
///
/// The returned buffer's first item is always at offset 0; unlike buffer
/// slices, extracted buffers do not share their indices with the
/// buffer from which they are extracted.
///
/// - Parameter maxLength: The maximum number of elements to return.
/// `maxLength` must be greater than or equal to zero.
/// - Returns: A buffer pointer with at most `maxLength` elements.
///
/// - Complexity: O(1)
@_alwaysEmitIntoClient
@inline(__always)
public func _extracting(first maxLength: Int) -> Self {
precondition(maxLength >= 0, "Can't have a prefix of negative length")
let newCount = Swift.min(maxLength, count)
return Self(start: baseAddress, count: newCount)
}
/// Returns a buffer pointer containing the final elements of this buffer,
/// up to the given maximum length.
///
/// If the maximum length exceeds the length of this buffer pointer,
/// the result contains all the elements.
///
/// The returned buffer's first item is always at offset 0; unlike buffer
/// slices, extracted buffers do not share their indices with the
/// span from which they are extracted.
///
/// - Parameter maxLength: The maximum number of elements to return.
/// `maxLength` must be greater than or equal to zero.
/// - Returns: A buffer pointer with at most `maxLength` elements.
///
/// - Complexity: O(1)
@_alwaysEmitIntoClient
@inline(__always)
public func _extracting(last maxLength: Int) -> Self {
precondition(maxLength >= 0, "Can't have a suffix of negative length")
let newCount = Swift.min(maxLength, count)
return extracting(Range(uncheckedBounds: (count - newCount, count)))
}
}
#else // !COLLECTIONS_SINGLE_MODULE
extension UnsafeBufferPointer {
@inlinable
@@ -39,4 +96,62 @@ extension UnsafeBufferPointer {
return baseAddress.unsafelyUnwrapped + index
}
}
extension UnsafeBufferPointer where Element: ~Copyable {
/// Returns a Boolean value indicating whether two `UnsafeBufferPointer`
/// instances refer to the same region in memory.
@inlinable @inline(__always)
public func _isIdentical(to other: Self) -> Bool {
(self.baseAddress == other.baseAddress) && (self.count == other.count)
}
}
extension UnsafeBufferPointer where Element: ~Copyable {
/// Returns a buffer pointer containing the initial elements of this buffer,
/// up to the specified maximum length.
///
/// If the maximum length exceeds the length of this buffer pointer,
/// then the result contains all the elements.
///
/// The returned buffer's first item is always at offset 0; unlike buffer
/// slices, extracted buffers do not share their indices with the
/// buffer from which they are extracted.
///
/// - Parameter maxLength: The maximum number of elements to return.
/// `maxLength` must be greater than or equal to zero.
/// - Returns: A buffer pointer with at most `maxLength` elements.
///
/// - Complexity: O(1)
@_alwaysEmitIntoClient
@inline(__always)
public func _extracting(first maxLength: Int) -> Self {
precondition(maxLength >= 0, "Can't have a prefix of negative length")
let newCount = Swift.min(maxLength, count)
return Self(start: baseAddress, count: newCount)
}
/// Returns a buffer pointer containing the final elements of this buffer,
/// up to the given maximum length.
///
/// If the maximum length exceeds the length of this buffer pointer,
/// the result contains all the elements.
///
/// The returned buffer's first item is always at offset 0; unlike buffer
/// slices, extracted buffers do not share their indices with the
/// span from which they are extracted.
///
/// - Parameter maxLength: The maximum number of elements to return.
/// `maxLength` must be greater than or equal to zero.
/// - Returns: A buffer pointer with at most `maxLength` elements.
///
/// - Complexity: O(1)
@_alwaysEmitIntoClient
@inline(__always)
public func _extracting(last maxLength: Int) -> Self {
precondition(maxLength >= 0, "Can't have a suffix of negative length")
let newCount = Swift.min(maxLength, count)
return extracting(Range(uncheckedBounds: (count - newCount, count)))
}
}
#endif // COLLECTIONS_SINGLE_MODULE
@@ -2,7 +2,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 - 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
@@ -22,6 +22,188 @@
// but in regular builds we want them to be public. Unfortunately
// the current best way to do this is to duplicate all definitions.
#if COLLECTIONS_SINGLE_MODULE
extension UnsafeMutableBufferPointer where Element: ~Copyable {
/// Returns a Boolean value indicating whether two
/// `UnsafeMutableBufferPointer` instances refer to the same region in
/// memory.
@inlinable @inline(__always)
internal func _isIdentical(to other: Self) -> Bool {
(self.baseAddress == other.baseAddress) && (self.count == other.count)
}
}
extension UnsafeMutableBufferPointer where Element: ~Copyable {
/// Returns a buffer pointer containing the initial elements of this buffer,
/// up to the specified maximum length.
///
/// If the maximum length exceeds the length of this buffer pointer,
/// then the result contains all the elements.
///
/// The returned buffer's first item is always at offset 0; unlike buffer
/// slices, extracted buffers do not share their indices with the
/// buffer from which they are extracted.
///
/// - Parameter maxLength: The maximum number of elements to return.
/// `maxLength` must be greater than or equal to zero.
/// - Returns: A buffer pointer with at most `maxLength` elements.
///
/// - Complexity: O(1)
@_alwaysEmitIntoClient
@inline(__always)
public func _extracting(first maxLength: Int) -> Self {
precondition(maxLength >= 0, "Can't have a prefix of negative length")
let newCount = Swift.min(maxLength, count)
return Self(start: baseAddress, count: newCount)
}
/// Returns a buffer pointer containing the final elements of this buffer,
/// up to the given maximum length.
///
/// If the maximum length exceeds the length of this buffer pointer,
/// the result contains all the elements.
///
/// The returned buffer's first item is always at offset 0; unlike buffer
/// slices, extracted buffers do not share their indices with the
/// buffer from which they are extracted.
///
/// - Parameter maxLength: The maximum number of elements to return.
/// `maxLength` must be greater than or equal to zero.
/// - Returns: A buffer pointer with at most `maxLength` elements.
///
/// - Complexity: O(1)
@_alwaysEmitIntoClient
@inline(__always)
public func _extracting(last maxLength: Int) -> Self {
precondition(maxLength >= 0, "Can't have a suffix of negative length")
let newCount = Swift.min(maxLength, count)
return extracting(Range(uncheckedBounds: (count - newCount, count)))
}
}
extension UnsafeMutableBufferPointer where Element: ~Copyable {
@inlinable
internal func _moveInitializePrefix(
from source: UnsafeMutableBufferPointer<Element>
) -> Int {
if source.isEmpty { return 0 }
precondition(source.count <= self.count)
self.baseAddress.unsafelyUnwrapped.moveInitialize(
from: source.baseAddress.unsafelyUnwrapped, count: source.count)
return source.count
}
}
extension UnsafeMutableBufferPointer {
/// Initialize slots at the start of this buffer by copying data from `source`.
///
/// If `Element` is not bitwise copyable, then the memory region addressed by `self` must be
/// entirely uninitialized, while `source` must be fully initialized.
///
/// The `source` buffer must fit entirely in `self`.
///
/// - Returns: The index after the last item that was initialized in this buffer.
@inlinable
internal func _initializePrefix(
copying source: UnsafeBufferPointer<Element>
) -> Int {
if source.isEmpty { return 0 }
precondition(source.count <= self.count)
self.baseAddress.unsafelyUnwrapped.initialize(
from: source.baseAddress.unsafelyUnwrapped, count: source.count)
return source.count
}
@inlinable
internal func _initializePrefix(
copying source: UnsafeMutableBufferPointer<Element>
) -> Int {
_initializePrefix(copying: UnsafeBufferPointer(source))
}
#if compiler(>=6.2)
/// Initialize slots at the start of this buffer by copying data from `source`.
///
/// If `Element` is not bitwise copyable, then the memory region addressed by `self` must be
/// entirely uninitialized.
///
/// The `source` span must fit entirely in `self`.
///
/// - Returns: The index after the last item that was initialized in this buffer.
@available(SwiftStdlib 6.2, *)
@inlinable
internal func _initializePrefix(copying source: Span<Element>) -> Int {
source.withUnsafeBufferPointer { self._initializePrefix(copying: $0) }
}
#endif
#if compiler(>=6.2) && FIXME
/// Initialize all slots in this buffer by copying data from `items`, which must fit entirely
/// in this buffer.
///
/// If `items` contains more elements than can fit into this buffer, then this function
/// will return an index other than `items.endIndex`. In that case, `self` may not be fully
/// populated.
///
/// If `Element` is not bitwise copyable, then this function must be called on an
/// entirely uninitialized buffer.
///
/// - Returns: A pair of values `(count, end)`, where `count` is the number of items that were
/// successfully initialized, and `end` is the index into `items` after the last copied item.
@available(SwiftStdlib 6.2, *)
@inlinable
internal func _initializePrefix<
C: Container<Element> & ~Copyable & ~Escapable
>(
copying items: borrowing C
) -> (copied: Int, end: C.Index) {
var target = self
var i = items.startIndex
while true {
let start = i
let span = items.span(after: &i)
if span.isEmpty { break }
guard span.count <= target.count else {
return (self.count - target.count, start)
}
target._initializeAndDropPrefix(copying: span)
}
return (self.count - target.count, i)
}
#endif
/// Initialize slots at the start of this buffer by copying data from `buffer`, then
/// shrink `self` to drop all initialized items from its front, leaving it addressing the
/// uninitialized remainder.
///
/// If `Element` is not bitwise copyable, then the memory region addressed by `self` must be
/// entirely uninitialized, while `buffer` must be fully initialized.
///
/// The count of `buffer` must not be greater than `self.count`.
@inlinable
internal mutating func _initializeAndDropPrefix(copying source: UnsafeBufferPointer<Element>) {
let i = _initializePrefix(copying: source)
self = self.extracting(i...)
}
#if compiler(>=6.2)
/// Initialize slots at the start of this buffer by copying data from `span`, then
/// shrink `self` to drop all initialized items from its front, leaving it addressing the
/// uninitialized remainder.
///
/// If `Element` is not bitwise copyable, then the memory region addressed by `self` must be
/// entirely uninitialized.
///
/// The count of `span` must not be greater than `self.count`.
@available(SwiftStdlib 5.0, *)
@inlinable
internal mutating func _initializeAndDropPrefix(copying span: Span<Element>) {
span.withUnsafeBufferPointer { buffer in
self._initializeAndDropPrefix(copying: buffer)
}
}
#endif
}
extension UnsafeMutableBufferPointer {
@inlinable
internal func initialize(fromContentsOf source: Self) -> Index {
@@ -149,6 +331,188 @@ extension Slice {
}
}
#else // !COLLECTIONS_SINGLE_MODULE
extension UnsafeMutableBufferPointer where Element: ~Copyable {
/// Returns a Boolean value indicating whether two
/// `UnsafeMutableBufferPointer` instances refer to the same region in
/// memory.
@inlinable @inline(__always)
public func _isIdentical(to other: Self) -> Bool {
(self.baseAddress == other.baseAddress) && (self.count == other.count)
}
}
extension UnsafeMutableBufferPointer where Element: ~Copyable {
/// Returns a buffer pointer containing the initial elements of this buffer,
/// up to the specified maximum length.
///
/// If the maximum length exceeds the length of this buffer pointer,
/// then the result contains all the elements.
///
/// The returned buffer's first item is always at offset 0; unlike buffer
/// slices, extracted buffers do not share their indices with the
/// buffer from which they are extracted.
///
/// - Parameter maxLength: The maximum number of elements to return.
/// `maxLength` must be greater than or equal to zero.
/// - Returns: A buffer pointer with at most `maxLength` elements.
///
/// - Complexity: O(1)
@_alwaysEmitIntoClient
@inline(__always)
public func _extracting(first maxLength: Int) -> Self {
precondition(maxLength >= 0, "Can't have a prefix of negative length")
let newCount = Swift.min(maxLength, count)
return Self(start: baseAddress, count: newCount)
}
/// Returns a buffer pointer containing the final elements of this buffer,
/// up to the given maximum length.
///
/// If the maximum length exceeds the length of this buffer pointer,
/// the result contains all the elements.
///
/// The returned buffer's first item is always at offset 0; unlike buffer
/// slices, extracted buffers do not share their indices with the
/// buffer from which they are extracted.
///
/// - Parameter maxLength: The maximum number of elements to return.
/// `maxLength` must be greater than or equal to zero.
/// - Returns: A buffer pointer with at most `maxLength` elements.
///
/// - Complexity: O(1)
@_alwaysEmitIntoClient
@inline(__always)
public func _extracting(last maxLength: Int) -> Self {
precondition(maxLength >= 0, "Can't have a suffix of negative length")
let newCount = Swift.min(maxLength, count)
return extracting(Range(uncheckedBounds: (count - newCount, count)))
}
}
extension UnsafeMutableBufferPointer where Element: ~Copyable {
@inlinable
public func _moveInitializePrefix(
from source: UnsafeMutableBufferPointer<Element>
) -> Int {
if source.isEmpty { return 0 }
precondition(source.count <= self.count)
self.baseAddress.unsafelyUnwrapped.moveInitialize(
from: source.baseAddress.unsafelyUnwrapped, count: source.count)
return source.count
}
}
extension UnsafeMutableBufferPointer {
/// Initialize slots at the start of this buffer by copying data from `source`.
///
/// If `Element` is not bitwise copyable, then the memory region addressed by `self` must be
/// entirely uninitialized, while `source` must be fully initialized.
///
/// The `source` buffer must fit entirely in `self`.
///
/// - Returns: The index after the last item that was initialized in this buffer.
@inlinable
public func _initializePrefix(
copying source: UnsafeBufferPointer<Element>
) -> Int {
if source.isEmpty { return 0 }
precondition(source.count <= self.count)
self.baseAddress.unsafelyUnwrapped.initialize(
from: source.baseAddress.unsafelyUnwrapped, count: source.count)
return source.count
}
@inlinable
public func _initializePrefix(
copying source: UnsafeMutableBufferPointer<Element>
) -> Int {
_initializePrefix(copying: UnsafeBufferPointer(source))
}
#if compiler(>=6.2)
/// Initialize slots at the start of this buffer by copying data from `source`.
///
/// If `Element` is not bitwise copyable, then the memory region addressed by `self` must be
/// entirely uninitialized.
///
/// The `source` span must fit entirely in `self`.
///
/// - Returns: The index after the last item that was initialized in this buffer.
@available(SwiftStdlib 6.2, *)
@inlinable
public func _initializePrefix(copying source: Span<Element>) -> Int {
source.withUnsafeBufferPointer { self._initializePrefix(copying: $0) }
}
#endif
#if compiler(>=6.2) && FIXME
/// Initialize all slots in this buffer by copying data from `items`, which must fit entirely
/// in this buffer.
///
/// If `items` contains more elements than can fit into this buffer, then this function
/// will return an index other than `items.endIndex`. In that case, `self` may not be fully
/// populated.
///
/// If `Element` is not bitwise copyable, then this function must be called on an
/// entirely uninitialized buffer.
///
/// - Returns: A pair of values `(count, end)`, where `count` is the number of items that were
/// successfully initialized, and `end` is the index into `items` after the last copied item.
@available(SwiftStdlib 6.2, *)
@inlinable
public func _initializePrefix<
C: Container<Element> & ~Copyable & ~Escapable
>(
copying items: borrowing C
) -> (copied: Int, end: C.Index) {
var target = self
var i = items.startIndex
while true {
let start = i
let span = items.span(after: &i)
if span.isEmpty { break }
guard span.count <= target.count else {
return (self.count - target.count, start)
}
target._initializeAndDropPrefix(copying: span)
}
return (self.count - target.count, i)
}
#endif
/// Initialize slots at the start of this buffer by copying data from `buffer`, then
/// shrink `self` to drop all initialized items from its front, leaving it addressing the
/// uninitialized remainder.
///
/// If `Element` is not bitwise copyable, then the memory region addressed by `self` must be
/// entirely uninitialized, while `buffer` must be fully initialized.
///
/// The count of `buffer` must not be greater than `self.count`.
@inlinable
public mutating func _initializeAndDropPrefix(copying source: UnsafeBufferPointer<Element>) {
let i = _initializePrefix(copying: source)
self = self.extracting(i...)
}
#if compiler(>=6.2)
/// Initialize slots at the start of this buffer by copying data from `span`, then
/// shrink `self` to drop all initialized items from its front, leaving it addressing the
/// uninitialized remainder.
///
/// If `Element` is not bitwise copyable, then the memory region addressed by `self` must be
/// entirely uninitialized.
///
/// The count of `span` must not be greater than `self.count`.
@available(SwiftStdlib 5.0, *)
@inlinable
public mutating func _initializeAndDropPrefix(copying span: Span<Element>) {
span.withUnsafeBufferPointer { buffer in
self._initializeAndDropPrefix(copying: buffer)
}
}
#endif
}
extension UnsafeMutableBufferPointer {
@inlinable
public func initialize(fromContentsOf source: Self) -> Index {
@@ -0,0 +1,45 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// #############################################################################
// # #
// # DO NOT EDIT THIS FILE; IT IS AUTOGENERATED. #
// # #
// #############################################################################
// In single module mode, we need these declarations to be internal,
// but in regular builds we want them to be public. Unfortunately
// the current best way to do this is to duplicate all definitions.
#if COLLECTIONS_SINGLE_MODULE
extension UnsafeMutableRawBufferPointer {
/// Returns a Boolean value indicating whether two
/// `UnsafeMutableRawBufferPointer` instances refer to the same region in
/// memory.
@inlinable @inline(__always)
internal func _isIdentical(to other: Self) -> Bool {
(self.baseAddress == other.baseAddress) && (self.count == other.count)
}
}
#else // !COLLECTIONS_SINGLE_MODULE
extension UnsafeMutableRawBufferPointer {
/// Returns a Boolean value indicating whether two
/// `UnsafeMutableRawBufferPointer` instances refer to the same region in
/// memory.
@inlinable @inline(__always)
public func _isIdentical(to other: Self) -> Bool {
(self.baseAddress == other.baseAddress) && (self.count == other.count)
}
}
#endif // COLLECTIONS_SINGLE_MODULE
@@ -0,0 +1,43 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// #############################################################################
// # #
// # DO NOT EDIT THIS FILE; IT IS AUTOGENERATED. #
// # #
// #############################################################################
// In single module mode, we need these declarations to be internal,
// but in regular builds we want them to be public. Unfortunately
// the current best way to do this is to duplicate all definitions.
#if COLLECTIONS_SINGLE_MODULE
extension UnsafeRawBufferPointer {
/// Returns a Boolean value indicating whether two `UnsafeRawBufferPointer`
/// instances refer to the same region in memory.
@inlinable @inline(__always)
internal func _isIdentical(to other: Self) -> Bool {
(self.baseAddress == other.baseAddress) && (self.count == other.count)
}
}
#else // !COLLECTIONS_SINGLE_MODULE
extension UnsafeRawBufferPointer {
/// Returns a Boolean value indicating whether two `UnsafeRawBufferPointer`
/// instances refer to the same region in memory.
@inlinable @inline(__always)
public func _isIdentical(to other: Self) -> Bool {
(self.baseAddress == other.baseAddress) && (self.count == other.count)
}
}
#endif // COLLECTIONS_SINGLE_MODULE
@@ -15,7 +15,7 @@ extension OrderedSet {
/// testing and the member uniqueness guarantees of `OrderedSet`.
///
/// - Complexity: O(`self.count + other.count`)
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
@available(SwiftStdlib 5.1, *)
public func difference(
from other: Self
) -> CollectionDifference<Element> {
@@ -91,7 +91,7 @@ extension OrderedSet {
///
/// - Complexity: O(*n* + *c*), where *n* is `self.count` and *c*
/// is the number of changes contained by the parameter.
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
@available(SwiftStdlib 5.1, *)
public func applying(_ difference: CollectionDifference<Element>) -> Self? {
guard let array = self.elements.applying(difference) else { return nil }
let result = OrderedSet(array)
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
struct Builder {
typealias _Chunk = BigString._Chunk
@@ -38,7 +38,7 @@ extension BigString {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension Rope<BigString._Chunk>.Builder {
internal func _breakState() -> _CharacterRecognizer {
let chars = self.prefixSummary.characters
@@ -57,7 +57,7 @@ extension Rope<BigString._Chunk>.Builder {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString.Builder {
mutating func append(_ str: __owned some StringProtocol) {
append(Substring(str))
@@ -129,7 +129,7 @@ extension BigString.Builder {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString.Builder {
mutating func finalize() -> BigString {
// Resync breaks in suffix.
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
/// The estimated maximum number of UTF-8 code units that `BigString` is guaranteed to be able
/// to hold without encountering an overflow in its operations. This corresponds to the capacity
@@ -31,7 +31,7 @@ extension BigString {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
var _characterCount: Int { _rope.summary.characters }
var _unicodeScalarCount: Int { _rope.summary.unicodeScalars }
@@ -39,7 +39,7 @@ extension BigString {
var _utf8Count: Int { _rope.summary.utf8 }
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
func _distance(
from start: Index,
@@ -91,7 +91,7 @@ extension BigString {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
// FIXME: See if we need direct implementations for these.
@@ -113,7 +113,7 @@ extension BigString {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
// FIXME: See if we need direct implementations for these.
@@ -134,7 +134,7 @@ extension BigString {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
func _index(
_ i: Index,
@@ -201,7 +201,7 @@ extension BigString {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
func _index(
_ i: Index,
@@ -249,7 +249,7 @@ extension BigString {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
func _characterIndex(after i: Index) -> Index {
let i = _characterIndex(roundingDown: i)
@@ -281,7 +281,7 @@ extension BigString {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
func _characterIndex(before i: Index) -> Index {
let i = _characterIndex(roundingDown: i)
@@ -316,7 +316,7 @@ extension BigString {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
func _characterIndex(roundingDown i: Index) -> Index {
let offset = i.utf8Offset
@@ -390,7 +390,7 @@ extension BigString {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
func _characterIndex(roundingUp i: Index) -> Index {
let j = _characterIndex(roundingDown: i)
@@ -421,7 +421,7 @@ extension BigString {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
func _character(at start: Index) -> (character: Character, end: Index) {
let start = _characterIndex(roundingDown: start)
@@ -504,7 +504,7 @@ extension BigString {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
func _foreachChunk(
from start: Index,
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
public func _dump(heightLimit: Int = .max) {
_rope._dump(heightLimit: heightLimit)
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
public struct Index: Sendable {
typealias _Rope = BigString._Rope
@@ -38,7 +38,7 @@ extension BigString {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString.Index {
@inline(__always)
internal static func _bitsForUTF8Offset(_ utf8Offset: Int) -> UInt64 {
@@ -93,7 +93,7 @@ extension BigString.Index {
}
extension String.Index {
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
func _copyingAlignmentBits(from i: BigString.Index) -> String.Index {
var bits = _abi_rawBits & ~3
bits |= (i._flags &>> 8) & 3
@@ -101,7 +101,7 @@ extension String.Index {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString.Index {
internal var _chunkIndex: String.Index {
assert(_rope != nil)
@@ -111,7 +111,7 @@ extension BigString.Index {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString.Index {
internal mutating func _clearUTF16TrailingSurrogate() {
_flags = 0
@@ -176,28 +176,28 @@ extension BigString.Index {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString.Index: Equatable {
public static func ==(left: Self, right: Self) -> Bool {
left._orderingValue == right._orderingValue
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString.Index: Comparable {
public static func <(left: Self, right: Self) -> Bool {
left._orderingValue < right._orderingValue
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString.Index: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(_orderingValue)
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString.Index: CustomStringConvertible {
public var description: String {
let utf16Offset = _isUTF16TrailingSurrogate ? "+1" : ""
@@ -205,7 +205,7 @@ extension BigString.Index: CustomStringConvertible {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
func resolve(_ i: Index, preferEnd: Bool) -> Index {
if var ri = i._rope, _rope.isValid(ri) {
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
func _ingester(
forInserting input: __owned Substring,
@@ -22,7 +22,7 @@ extension BigString {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
internal struct _Ingester {
typealias _Chunk = BigString._Chunk
@@ -141,7 +141,7 @@ extension BigString {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension String {
func _nextSlice(
after i: Index,
@@ -157,7 +157,7 @@ extension String {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString._Chunk {
init(_ string: String) {
guard !string.isEmpty else { self.init(); return }
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
public func _invariantCheck() {
#if COLLECTIONS_INTERNAL_CHECKS
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
struct ChunkIterator {
var base: _Rope.Iterator
@@ -24,7 +24,7 @@ extension BigString {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString.ChunkIterator: IteratorProtocol {
typealias Element = String
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
internal protocol _StringMetric: RopeMetric where Element == BigString._Chunk {
/// Measure the distance between the given start and end positions within
/// the specified chunk.
@@ -47,7 +47,7 @@ internal protocol _StringMetric: RopeMetric where Element == BigString._Chunk {
) -> (found: Bool, forward: Bool)
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
internal struct _CharacterMetric: _StringMetric {
typealias Element = BigString._Chunk
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
struct Summary {
// FIXME: We only need 48 * 3 = 192 bits to represent a nonnegative value; pack these better
@@ -35,14 +35,14 @@ extension BigString {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString.Summary: CustomStringConvertible {
var description: String {
"❨\(utf8)⋅\(utf16)⋅\(unicodeScalars)⋅\(characters)❩"
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString.Summary: RopeSummary {
@inline(__always)
static var maxNodeSize: Int {
@@ -10,7 +10,7 @@
//===----------------------------------------------------------------------===//
/// The core of a B-tree based String implementation.
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
public struct BigString: Sendable {
typealias _Rope = Rope<_Chunk>
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString._Chunk {
mutating func append(_ other: __owned Self) {
self._append(other.string[...], other.counts)
@@ -64,7 +64,7 @@ extension BigString._Chunk {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString._Chunk {
mutating func _insert(
_ slice: Slice,
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString._Chunk {
@inline(__always)
var hasBreaks: Bool { counts.hasBreaks }
@@ -38,7 +38,7 @@ extension BigString._Chunk {
var wholeCharacters: Substring { string[firstBreak...] }
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString._Chunk {
var immediateLastBreakState: _CharacterRecognizer? {
guard hasBreaks else { return nil }
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString._Chunk {
struct Counts: Equatable {
/// The number of UTF-8 code units within this chunk.
@@ -97,7 +97,7 @@ extension BigString._Chunk {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString._Chunk.Counts {
var characters: Int {
get { Int(_characters) }
@@ -123,7 +123,7 @@ extension BigString._Chunk.Counts {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString._Chunk.Counts {
mutating func append(_ other: Self) {
assert(hasSpaceToMerge(other))
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString._Chunk: CustomStringConvertible {
var description: String {
let counts = """
@@ -9,14 +9,14 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension UInt8 {
/// Returns true if this is a leading code unit in the UTF-8 encoding of a Unicode scalar that
/// is outside the BMP.
var _isUTF8NonBMPLeadingCodeUnit: Bool { self >= 0b11110000 }
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString._Chunk {
func characterDistance(
from start: String.Index,
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString._Chunk {
/// UTF-16 index lookup.
func index(at utf8Offset: Int, utf16TrailingSurrogate: Bool) -> String.Index {
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString._Chunk: RopeElement {
typealias Summary = BigString.Summary
typealias Index = String.Index
@@ -114,7 +114,7 @@ extension BigString._Chunk: RopeElement {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString._Chunk {
static func _redistributeData(
_ left: inout Self,
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString._Chunk {
func splitCounts(at i: String.Index) -> (left: Counts, right: Counts) {
precondition(i <= string.endIndex)
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
internal struct _Chunk {
typealias Slice = (string: Substring, characters: Int, prefix: Int, suffix: Int)
@@ -44,7 +44,7 @@ extension BigString {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString._Chunk {
@inline(__always)
static var maxUTF8Count: Int { 255 }
@@ -56,7 +56,7 @@ extension BigString._Chunk {
static var maxSlicingError: Int { 3 }
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString._Chunk {
@inline(__always)
mutating func take() -> Self {
@@ -73,7 +73,7 @@ extension BigString._Chunk {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString._Chunk {
@inline(__always)
var characterCount: Int { counts.characters }
@@ -97,7 +97,7 @@ extension BigString._Chunk {
var lastScalar: UnicodeScalar { string.unicodeScalars.last! }
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString._Chunk {
var availableSpace: Int { Swift.max(0, Self.maxUTF8Count - utf8Count) }
@@ -107,7 +107,7 @@ extension BigString._Chunk {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString._Chunk {
func hasSpaceToMerge(_ other: some StringProtocol) -> Bool {
utf8Count + other.utf8.count <= Self.maxUTF8Count
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString: BidirectionalCollection {
public typealias SubSequence = BigSubstring
@@ -59,7 +59,7 @@ extension BigString: BidirectionalCollection {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
public func index(roundingDown i: Index) -> Index {
_characterIndex(roundingDown: i)
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString: Comparable {
public static func < (left: Self, right: Self) -> Bool {
// FIXME: Implement properly normalized comparisons & hashing.
@@ -34,7 +34,7 @@ extension BigString: Comparable {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
/// Lexicographically compare the UTF-8 representations of `left` to `right`, returning a Boolean
/// value indicating whether `left` is ordered before `right`.
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString: CustomDebugStringConvertible {
public var debugDescription: String {
description.debugDescription
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString: CustomStringConvertible {
public var description: String {
String(self)
@@ -9,14 +9,14 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
public func isIdentical(to other: Self) -> Bool {
self._rope.isIdentical(to: other._rope)
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString: Equatable {
public static func ==(left: Self, right: Self) -> Bool {
// FIXME: Implement properly normalized comparisons & hashing.
@@ -40,7 +40,7 @@ extension BigString: Equatable {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
/// Lexicographically compare the UTF-8 representations of `left` to `right`, returning a Boolean
/// value indicating whether `left` is equal to `right`.
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
self.init(value)
@@ -9,14 +9,14 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString: Hashable {
public func hash(into hasher: inout Hasher) {
hashCharacters(into: &hasher)
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
internal func hashCharacters(into hasher: inout Hasher) {
// FIXME: Implement properly normalized comparisons & hashing.
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString: LosslessStringConvertible {
// init?(_: String) is implemented by RangeReplaceableCollection.init(_:)
}
@@ -13,7 +13,7 @@
import InternalCollectionsUtilities
#endif
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString: RangeReplaceableCollection {
public init() {
self.init(_rope: _Rope())
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString: Sequence {
public typealias Element = Character
@@ -18,7 +18,7 @@ extension BigString: Sequence {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
public struct Iterator {
internal let _base: BigString
@@ -66,7 +66,7 @@ extension BigString {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString.Iterator: IteratorProtocol {
public typealias Element = Character
@@ -158,7 +158,7 @@ extension BigString.Iterator: IteratorProtocol {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString.Iterator {
// The UTF-8 offset of the current position, from the start of the string.
var utf8Offset: Int {
@@ -9,14 +9,14 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString: TextOutputStream {
public mutating func write(_ string: String) {
append(contentsOf: string)
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString: TextOutputStreamable {
public func write(to target: inout some TextOutputStream) {
for chunk in _rope {
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
mutating func _append(contentsOf other: __owned Substring) {
if other.isEmpty { return }
@@ -39,7 +39,7 @@ extension BigString {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
var _firstUnicodeScalar: Unicode.Scalar {
assert(!isEmpty)
@@ -104,14 +104,14 @@ extension BigString {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
var isUndersized: Bool {
_utf8Count < _Chunk.minUTF8Count
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
/// Note: This assumes `other` already has the correct break positions.
mutating func _append(_ other: __owned _Chunk) {
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
internal init(_from input: some StringProtocol) {
var builder = _Rope.Builder()
@@ -84,7 +84,7 @@ extension BigString {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension String {
public init(_ big: BigString) {
guard !big.isEmpty else {
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
mutating func _insert(
contentsOf other: __owned Substring,
@@ -52,7 +52,7 @@ extension BigString {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
mutating func _insert(contentsOf other: __owned Self, at index: Index) {
guard index < endIndex else {
@@ -76,7 +76,7 @@ extension BigString {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
mutating func _insert(contentsOf other: __owned Self, in range: Range<Index>, at index: Index) {
guard index < endIndex else {
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
func _breakState(
upTo index: Index,
@@ -59,7 +59,7 @@ extension BigString {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
/// - Returns: the position at which the grapheme breaks finally sync up with the originals.
/// (or nil if they never did).
@@ -97,7 +97,7 @@ extension BigString {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString._Rope {
mutating func resyncBreaks(
old: inout _CharacterRecognizer,
@@ -155,7 +155,7 @@ extension BigString._Rope {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString._Chunk {
/// Resyncronize chunk metadata with the (possibly) reshuffled grapheme
/// breaks after an insertion that ended at `index`.
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
mutating func _removeSubrange(_ bounds: Range<Index>) {
precondition(bounds.upperBound <= endIndex, "Index out of bounds")
@@ -20,7 +20,7 @@ extension BigString {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
mutating func removeCharacter(at i: Index) -> Character {
let start = self.resolve(i, preferEnd: false)
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
mutating func _replaceSubrange(
_ range: Range<Index>,
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
mutating func split(
at index: Index
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension Range<BigString.Index> {
internal var _isEmptyUTF8: Bool {
lowerBound.utf8Offset == upperBound.utf8Offset
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
public struct UTF16View: Sendable {
var _base: BigString
@@ -30,7 +30,7 @@ extension BigString {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString.UTF16View: Equatable {
public static func ==(left: Self, right: Self) -> Bool {
BigString.utf8IsEqual(left._base, to: right._base)
@@ -41,14 +41,14 @@ extension BigString.UTF16View: Equatable {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString.UTF16View: Hashable {
public func hash(into hasher: inout Hasher) {
_base.hashUTF8(into: &hasher)
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString.UTF16View: Sequence {
public typealias Element = UInt16
@@ -67,7 +67,7 @@ extension BigString.UTF16View: Sequence {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString.UTF16View.Iterator: IteratorProtocol {
public typealias Element = UInt16
@@ -91,7 +91,7 @@ extension BigString.UTF16View.Iterator: IteratorProtocol {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString.UTF16View: BidirectionalCollection {
public typealias Index = BigString.Index
public typealias SubSequence = BigSubstring.UTF16View
@@ -136,7 +136,7 @@ extension BigString.UTF16View: BidirectionalCollection {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString.UTF16View {
public func index(roundingDown i: Index) -> Index {
_base._utf16Index(roundingDown: i)
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
public struct UTF8View: Sendable {
var _base: BigString
@@ -30,7 +30,7 @@ extension BigString {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString.UTF8View: Equatable {
public static func ==(left: Self, right: Self) -> Bool {
BigString.utf8IsEqual(left._base, to: right._base)
@@ -41,14 +41,14 @@ extension BigString.UTF8View: Equatable {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString.UTF8View: Hashable {
public func hash(into hasher: inout Hasher) {
_base.hashUTF8(into: &hasher)
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString.UTF8View: Sequence {
public typealias Element = UInt8
@@ -67,7 +67,7 @@ extension BigString.UTF8View: Sequence {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString.UTF8View.Iterator: IteratorProtocol {
public typealias Element = UInt8
@@ -127,7 +127,7 @@ extension BigString.UTF8View.Iterator: IteratorProtocol {
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString.UTF8View: BidirectionalCollection {
public typealias Index = BigString.Index
public typealias SubSequence = BigSubstring.UTF8View
@@ -172,7 +172,7 @@ extension BigString.UTF8View: BidirectionalCollection {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString.UTF8View {
public func index(roundingDown i: Index) -> Index {
_base._utf8Index(roundingDown: i)
@@ -13,7 +13,7 @@
import InternalCollectionsUtilities
#endif
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
public struct UnicodeScalarView: Sendable {
var _base: BigString
@@ -47,28 +47,28 @@ extension BigString {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString.UnicodeScalarView: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
self.init(value.unicodeScalars)
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString.UnicodeScalarView: CustomStringConvertible {
public var description: String {
String(_base)
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString.UnicodeScalarView: CustomDebugStringConvertible {
public var debugDescription: String {
description.debugDescription
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString.UnicodeScalarView: Equatable {
public static func ==(left: Self, right: Self) -> Bool {
BigString.utf8IsEqual(left._base, to: right._base)
@@ -79,14 +79,14 @@ extension BigString.UnicodeScalarView: Equatable {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString.UnicodeScalarView: Hashable {
public func hash(into hasher: inout Hasher) {
_base.hashUTF8(into: &hasher)
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString.UnicodeScalarView: Sequence {
public typealias Element = UnicodeScalar
@@ -105,7 +105,7 @@ extension BigString.UnicodeScalarView: Sequence {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString.UnicodeScalarView.Iterator: IteratorProtocol {
public typealias Element = UnicodeScalar
@@ -129,7 +129,7 @@ extension BigString.UnicodeScalarView.Iterator: IteratorProtocol {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString.UnicodeScalarView: BidirectionalCollection {
public typealias Index = BigString.Index
public typealias SubSequence = BigSubstring.UnicodeScalarView
@@ -174,7 +174,7 @@ extension BigString.UnicodeScalarView: BidirectionalCollection {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString.UnicodeScalarView {
public func index(roundingDown i: Index) -> Index {
_base._unicodeScalarIndex(roundingDown: i)
@@ -185,7 +185,7 @@ extension BigString.UnicodeScalarView {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString.UnicodeScalarView: RangeReplaceableCollection {
public init() {
self._base = BigString()
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring {
public struct UTF16View: Sendable {
internal var _base: BigString
@@ -37,7 +37,7 @@ extension BigSubstring {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
public init?(_ utf16: BigSubstring.UTF16View) {
guard
@@ -50,12 +50,12 @@ extension BigString {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring.UTF16View {
public var base: BigString.UTF16View { _base.utf16 }
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring.UTF16View: Equatable {
public static func ==(left: Self, right: Self) -> Bool {
var i1 = left._bounds.lowerBound
@@ -90,7 +90,7 @@ extension BigSubstring.UTF16View: Equatable {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring.UTF16View: Hashable {
public func hash(into hasher: inout Hasher) {
for codeUnit in self {
@@ -100,7 +100,7 @@ extension BigSubstring.UTF16View: Hashable {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring.UTF16View: Sequence {
public typealias Element = UInt16
@@ -124,7 +124,7 @@ extension BigSubstring.UTF16View: Sequence {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring.UTF16View: BidirectionalCollection {
public typealias Index = BigString.Index
public typealias SubSequence = Self
@@ -185,7 +185,7 @@ extension BigSubstring.UTF16View: BidirectionalCollection {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring.UTF16View {
public func index(roundingDown i: Index) -> Index {
precondition(i >= startIndex && i <= endIndex, "Index out of bounds")
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring {
public struct UTF8View: Sendable {
internal var _base: BigString
@@ -37,7 +37,7 @@ extension BigSubstring {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
public init?(_ utf8: BigSubstring.UTF8View) {
guard
@@ -50,12 +50,12 @@ extension BigString {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring.UTF8View {
public var base: BigString.UTF8View { _base.utf8 }
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring.UTF8View: Equatable {
public static func ==(left: Self, right: Self) -> Bool {
BigString.utf8IsEqual(left._base, in: left._bounds, to: right._base, in: right._bounds)
@@ -67,14 +67,14 @@ extension BigSubstring.UTF8View: Equatable {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring.UTF8View: Hashable {
public func hash(into hasher: inout Hasher) {
_base.hashUTF8(into: &hasher, from: _bounds.lowerBound, to: _bounds.upperBound)
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring.UTF8View: Sequence {
public typealias Element = UInt8
@@ -98,7 +98,7 @@ extension BigSubstring.UTF8View: Sequence {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring.UTF8View: BidirectionalCollection {
public typealias Index = BigString.Index
public typealias SubSequence = Self
@@ -159,7 +159,7 @@ extension BigSubstring.UTF8View: BidirectionalCollection {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring.UTF8View {
public func index(roundingDown i: Index) -> Index {
precondition(i >= startIndex && i <= endIndex, "Index out of bounds")
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring {
public struct UnicodeScalarView: Sendable {
internal var _base: BigString
@@ -52,40 +52,40 @@ extension BigSubstring {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigString {
public init(_ unicodeScalars: BigSubstring.UnicodeScalarView) {
self.init(_from: unicodeScalars._base, in: unicodeScalars._bounds)
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring.UnicodeScalarView {
public var base: BigString.UnicodeScalarView { _base.unicodeScalars }
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring.UnicodeScalarView: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
self.init(value.unicodeScalars)
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring.UnicodeScalarView: CustomStringConvertible {
public var description: String {
String(_from: _base, in: _bounds)
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring.UnicodeScalarView: CustomDebugStringConvertible {
public var debugDescription: String {
description.debugDescription
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring.UnicodeScalarView: Equatable {
public static func ==(left: Self, right: Self) -> Bool {
BigString.utf8IsEqual(left._base, in: left._bounds, to: right._base, in: right._bounds)
@@ -97,14 +97,14 @@ extension BigSubstring.UnicodeScalarView: Equatable {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring.UnicodeScalarView: Hashable {
public func hash(into hasher: inout Hasher) {
_base.hashUTF8(into: &hasher, from: _bounds.lowerBound, to: _bounds.upperBound)
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring.UnicodeScalarView: Sequence {
public typealias Element = UnicodeScalar
@@ -128,7 +128,7 @@ extension BigSubstring.UnicodeScalarView: Sequence {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring.UnicodeScalarView: BidirectionalCollection {
public typealias Index = BigString.Index
public typealias SubSequence = Self
@@ -191,7 +191,7 @@ extension BigSubstring.UnicodeScalarView: BidirectionalCollection {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring.UnicodeScalarView {
public func index(roundingDown i: Index) -> Index {
precondition(i >= startIndex && i <= endIndex, "Index out of bounds")
@@ -204,7 +204,7 @@ extension BigSubstring.UnicodeScalarView {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring.UnicodeScalarView {
/// Run the closure `body` to mutate the contents of this view within `range`, then update
/// the bounds of this view to maintain their logical position in the resulting string.
@@ -237,7 +237,7 @@ extension BigSubstring.UnicodeScalarView {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring.UnicodeScalarView: RangeReplaceableCollection {
public init() {
self.init(_substring: BigSubstring())
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
public struct BigSubstring: Sendable {
var _base: BigString
var _bounds: Range<Index>
@@ -32,12 +32,12 @@ public struct BigSubstring: Sendable {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring {
public var base: BigString { _base }
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring {
func _foreachChunk(
_ body: (Substring) -> Void
@@ -46,33 +46,33 @@ extension BigSubstring {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring: CustomStringConvertible {
public var description: String {
String(_from: _base, in: _bounds)
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring: CustomDebugStringConvertible {
public var debugDescription: String {
description.debugDescription
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
self.init(value)
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring: LosslessStringConvertible {
// init?(_: String) is implemented by RangeReplaceableCollection.init(_:)
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring: Equatable {
public static func ==(left: Self, right: Self) -> Bool {
// FIXME: Implement properly normalized comparisons & hashing.
@@ -103,7 +103,7 @@ extension BigSubstring: Equatable {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring: Hashable {
public func hash(into hasher: inout Hasher) {
var it = self.makeIterator()
@@ -115,7 +115,7 @@ extension BigSubstring: Hashable {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring: Comparable {
public static func < (left: Self, right: Self) -> Bool {
// FIXME: Implement properly normalized comparisons & hashing.
@@ -140,7 +140,7 @@ extension BigSubstring: Comparable {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring: Sequence {
public typealias Element = Character
@@ -164,7 +164,7 @@ extension BigSubstring: Sequence {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring: BidirectionalCollection {
public typealias Index = BigString.Index
public typealias SubSequence = Self
@@ -225,7 +225,7 @@ extension BigSubstring: BidirectionalCollection {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring {
public func index(roundingDown i: Index) -> Index {
precondition(i >= startIndex && i <= endIndex, "Index out of bounds")
@@ -238,7 +238,7 @@ extension BigSubstring {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring {
/// Run the closure `body` to mutate the contents of this view within `range`, then update
/// the bounds of this view to maintain an approximation of their logical position in the
@@ -273,7 +273,7 @@ extension BigSubstring {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension BigSubstring: RangeReplaceableCollection {
public init() {
let str = BigString()
@@ -134,15 +134,19 @@ extension Rope._Node {
}
extension Rope._Node {
@inlinable @inline(__always)
@inlinable
@_transparent
internal mutating func isUnique() -> Bool {
isKnownUniquelyReferenced(&object)
}
@inlinable
internal mutating func ensureUnique() {
guard !isKnownUniquelyReferenced(&object) else { return }
guard !isKnownUniquelyReferenced(&object) else {
return
}
self = copy()
assert(isUnique())
}
@inlinable @inline(never)
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension StringProtocol {
@inline(__always)
var _indexOfLastCharacter: Index {
@@ -45,7 +45,7 @@ extension StringProtocol {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension String {
internal func _lpad(to width: Int, with pad: Character = " ") -> String {
let c = self.count
@@ -60,7 +60,7 @@ extension String {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension String {
@discardableResult
mutating func _appendQuotedProtectingLeft(
@@ -9,10 +9,10 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
internal typealias _CharacterRecognizer = Unicode._CharacterRecognizer
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension _CharacterRecognizer {
internal func _isKnownEqual(to other: Self) -> Bool {
if #available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *) { // SwiftStdlib 5.9
@@ -23,7 +23,7 @@ extension _CharacterRecognizer {
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension _CharacterRecognizer {
mutating func firstBreak(
in str: Substring
@@ -52,7 +52,7 @@ extension _CharacterRecognizer {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
extension _CharacterRecognizer {
init(partialCharacter: Substring.UnicodeScalarView) {
self.init()
+104
View File
@@ -0,0 +1,104 @@
//===----------------------------------------------------------------------===//
//
// 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 XCTest
#if COLLECTIONS_SINGLE_MODULE
import Collections
#else
import _CollectionsTestSupport
import ArrayModule
#endif
struct ArrayLayout {
var capacity: Int
var count: Int
init(capacity: Int, count: Int) {
precondition(count >= 0 && count <= capacity)
self.capacity = capacity
self.count = count
}
}
func withSomeArrayLayouts<E: Error>(
_ label: String,
ofCapacities capacities: some Sequence<Int>,
file: StaticString = #filePath,
line: UInt = #line,
run body: (ArrayLayout) throws(E) -> Void
) throws(E) {
let context = TestContext.current
for capacity in capacities {
var counts: Set<Int> = []
counts.insert(0)
counts.insert(capacity)
counts.insert(capacity / 2)
if capacity >= 1 {
counts.insert(1)
counts.insert(capacity - 1)
}
if capacity >= 2 {
counts.insert(2)
counts.insert(capacity - 2)
}
for count in counts {
let layout = ArrayLayout(capacity: capacity, count: count)
let entry = context.push("\(label): \(layout)", file: file, line: line)
var done = false
defer {
context.pop(entry)
if !done {
print(context.currentTrace(title: "Throwing trace"))
}
}
try body(layout)
done = true
}
}
}
#if compiler(>=6.2) && (compiler(>=6.3) || !os(Windows)) // FIXME: [2025-08-17] Windows has no 6.2 snapshot with OutputSpan
extension RigidArray where Element: ~Copyable {
init(layout: ArrayLayout, using generator: (Int) -> Element) {
self.init(capacity: layout.capacity) { span in
for i in 0 ..< layout.count {
span.append(generator(i))
}
}
}
}
extension DynamicArray where Element: ~Copyable {
init(layout: ArrayLayout, using generator: (Int) -> Element) {
self.init(consuming: RigidArray(layout: layout, using: generator))
}
}
extension LifetimeTracker {
func rigidArray<Element>(
layout: ArrayLayout,
using generator: (Int) -> Element = { $0 }
) -> RigidArray<LifetimeTracked<Element>> {
RigidArray(layout: layout, using: { self.instance(for: generator($0)) })
}
func dynamicArray<Element>(
layout: ArrayLayout,
using generator: (Int) -> Element = { $0 }
) -> DynamicArray<LifetimeTracked<Element>> {
let contents = RigidArray(layout: layout) {
self.instance(for: generator($0))
}
return DynamicArray(consuming: contents)
}
}
#endif
+879
View File
@@ -0,0 +1,879 @@
//===----------------------------------------------------------------------===//
//
// 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 XCTest
#if COLLECTIONS_SINGLE_MODULE
import Collections
#else
import _CollectionsTestSupport
import ArrayModule
#endif
#if compiler(>=6.2) && (compiler(>=6.3) || !os(Windows)) // FIXME: [2025-08-17] Windows has no 6.2 snapshot with OutputSpan
#if !COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
/// Check if `left` and `right` contain equal elements in the same order.
@available(SwiftStdlib 5.0, *)
public func expectContainerContents<
Element: Equatable,
C2: Collection<Element>,
>(
_ left: borrowing DynamicArray<Element>,
equalTo right: C2,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
line: UInt = #line
) {
expectContainerContents(
left.span,
equalTo: right,
message(), trapping: trapping, file: file, line: line)
}
/// Check if `left` and `right` contain equal elements in the same order.
@available(SwiftStdlib 5.0, *)
public func expectContainerContents<
E1: ~Copyable,
C2: Collection,
>(
_ left: borrowing DynamicArray<E1>,
equivalentTo right: C2,
by areEquivalent: (borrowing E1, C2.Element) -> Bool,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
line: UInt = #line
) {
expectContainerContents(
left.span,
equivalentTo: right,
by: areEquivalent,
message(), trapping: trapping, file: file, line: line)
}
#endif
@available(SwiftStdlib 6.2, *)
class DynamicArrayTests: CollectionTestCase {
func test_validate_Container() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
let items = DynamicArray(consuming: tracker.rigidArray(layout: layout))
let expected = (0 ..< layout.count).map { tracker.instance(for: $0) }
expectEqual(tracker.instances, 2 * layout.count)
expectContainerContents(items, equalTo: expected)
#if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
checkContainer(items, expectedContents: expected)
#endif
}
}
}
func test_basics() {
withLifetimeTracking { tracker in
typealias Value = LifetimeTrackedStruct<Int>
var array = DynamicArray<Value>()
expectTrue(array.isEmpty)
expectEqual(array.count, 0)
expectEqual(array.capacity, 0)
expectEqual(tracker.instances, 0)
array.append(tracker.structInstance(for: 10))
expectFalse(array.isEmpty)
expectEqual(array.count, 1)
expectEqual(array.capacity, 1) // This assumes a specific growth behavior
expectEqual(array[0].payload, 10)
expectEqual(tracker.instances, 1)
array.append(tracker.structInstance(for: 20))
expectFalse(array.isEmpty)
expectEqual(array.count, 2)
expectEqual(array.capacity, 2) // This assumes a specific growth behavior
expectEqual(array[0].payload, 10)
expectEqual(array[1].payload, 20)
expectEqual(tracker.instances, 2)
let old = array.remove(at: 0)
expectEqual(old.payload, 10)
expectFalse(array.isEmpty)
expectEqual(array.count, 1)
expectEqual(array.capacity, 2) // This assumes a specific growth behavior
expectEqual(array[0].payload, 20)
expectEqual(tracker.instances, 2)
_ = consume old
expectEqual(tracker.instances, 1)
let old2 = array.remove(at: 0)
expectEqual(old2.payload, 20)
expectEqual(array.count, 0)
expectEqual(array.capacity, 2) // This assumes a specific growth behavior
expectTrue(array.isEmpty)
expectEqual(tracker.instances, 1)
_ = consume old2
expectEqual(tracker.instances, 0)
}
}
func test_init_capacity() {
do {
let a = DynamicArray<Int>(capacity: 0)
expectEqual(a.capacity, 0)
expectEqual(a.count, 0)
expectEqual(a.freeCapacity, 0)
expectTrue(a.isEmpty)
}
do {
let a = DynamicArray<Int>(capacity: 10)
expectEqual(a.capacity, 10)
expectEqual(a.count, 0)
expectEqual(a.freeCapacity, 10)
expectTrue(a.isEmpty)
}
}
func test_init_generator() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
let a = tracker.dynamicArray(layout: layout)
expectEqual(a.capacity, layout.capacity)
expectEqual(a.count, layout.count)
expectEqual(a.freeCapacity, layout.capacity - layout.count)
expectEqual(a.isEmpty, layout.count == 0)
expectContainerContents(a, equivalentTo: 0 ..< layout.count, by: { $0.payload == $1 })
}
}
}
func test_init_repeating() {
withEvery("c", in: [0, 10, 100]) { c in
withLifetimeTracking { tracker in
let value = tracker.instance(for: 0)
let a = DynamicArray(repeating: value, count: c)
expectEqual(a.capacity, c)
expectEqual(a.count, c)
expectEqual(a.freeCapacity, 0)
expectEqual(a.isEmpty, c == 0)
for i in 0 ..< c {
expectIdentical(a[i], value)
}
}
}
}
func test_init_copying_Sequence() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
let a = DynamicArray(
capacity: layout.capacity,
copying: (0 ..< layout.count).map { tracker.instance(for: $0) })
expectEqual(tracker.instances, layout.count)
expectEqual(a.capacity, layout.capacity)
expectEqual(a.count, layout.count)
expectEqual(a.isEmpty, layout.count == 0)
for i in 0 ..< layout.count {
expectEqual(a[i].payload, i)
}
}
}
}
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
func test_init_copying_Container() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withEvery("spanCounts", in: [
[1],
[3, 5, 7],
[10, 3],
] as [[Int]]) { spanCounts in
withLifetimeTracking { tracker in
let additions = StaccatoContainer(
contents: RigidArray(
copying: (0 ..< layout.count).map { tracker.instance(for: $0) }),
spanCounts: spanCounts)
let array = DynamicArray(
capacity: layout.capacity, copying: additions)
expectEqual(tracker.instances, layout.count)
expectEqual(array.capacity, layout.capacity)
expectEqual(array.count, layout.count)
for i in 0 ..< layout.count {
expectEqual(array[i].payload, i)
}
}
}
}
}
#endif
func test_span() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
let a = tracker.dynamicArray(layout: layout)
let span = a.span
expectEqual(span.count, layout.count)
for i in 0 ..< span.count {
expectEqual(span[i].payload, i)
}
}
}
}
func test_mutableSpan() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
var a = tracker.dynamicArray(layout: layout)
var span = a.mutableSpan
expectEqual(span.count, layout.count)
for i in 0 ..< layout.count {
expectEqual(span[i].payload, i)
span[i] = tracker.instance(for: -i)
}
for i in 0 ..< layout.count {
expectEqual(span[i].payload, -i)
}
for i in 0 ..< layout.count {
expectEqual(a[i].payload, -i)
}
}
}
}
func test_nextSpan() {
// DynamicArray is expected to have exactly one span.
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
let a = tracker.dynamicArray(layout: layout)
let whole = a.span
var i = 0
let first = a.span(after: &i)
expectEqual(i, layout.count)
expectTrue(first.isIdentical(to: whole))
let second = a.span(after: &i)
expectEqual(i, layout.count)
expectTrue(second.isEmpty)
}
}
}
func test_previousSpan() {
// RigidArray is expected to have exactly one span.
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
let a = tracker.dynamicArray(layout: layout)
let whole = a.span
var i = layout.count
let first = a.span(before: &i)
expectEqual(i, 0)
expectTrue(first.isIdentical(to: whole))
let second = a.span(before: &i)
expectEqual(i, 0)
expectTrue(second.isEmpty)
}
}
}
func test_nextMutableSpan() {
// RigidArray is expected to have exactly one span.
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
var a = tracker.dynamicArray(layout: layout)
var i = 0
var span = a.mutableSpan(after: &i)
expectEqual(i, layout.count)
expectEqual(span.count, layout.count)
span = a.mutableSpan(after: &i)
expectEqual(i, layout.count)
expectTrue(span.isEmpty)
}
}
}
func test_index_properties() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
let a = DynamicArray(layout: layout, using: { $0 })
expectEqual(a.startIndex, 0)
expectEqual(a.endIndex, layout.count)
expectEqual(a.indices, 0 ..< layout.count)
}
}
func test_swapAt() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
var a = tracker.dynamicArray(layout: layout)
withEvery("i", in: 0 ..< layout.count / 2) { i in
a.swapAt(i, layout.count - 1 - i)
}
let expected = (0 ..< layout.count).reversed()
expectContainerContents(
a, equivalentTo: expected, by: { $0.payload == $1 })
expectEqual(tracker.instances, layout.count)
}
}
}
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
func test_borrowElement() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
let a = tracker.dynamicArray(layout: layout)
for i in 0 ..< layout.count {
let item = a.borrowElement(at: i)
expectEqual(item[].payload, i)
}
}
}
}
#endif
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
func test_mutateElement() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
var a = tracker.dynamicArray(layout: layout)
for i in 0 ..< layout.count {
var item = a.mutateElement(at: i)
expectEqual(item[].payload, i)
item[] = tracker.instance(for: -i)
expectEqual(tracker.instances, layout.count)
}
}
}
}
#endif
func test_edit() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
var a = tracker.dynamicArray(layout: layout)
a.edit { span in
expectEqual(span.capacity, layout.capacity)
expectEqual(span.count, layout.count)
if layout.capacity > 0 {
// FIXME: OutputSpan.removeAll crashes when empty in some 6.2 snapshots (rdar://158440246)
span.removeAll()
}
expectEqual(tracker.instances, 0)
}
expectEqual(a.count, 0)
a.edit { span in
expectEqual(span.capacity, layout.capacity)
expectEqual(span.count, 0)
for i in 0 ..< span.capacity {
span.append(tracker.instance(for: -i))
}
expectEqual(tracker.instances, layout.capacity)
}
expectEqual(a.count, layout.capacity)
struct TestError: Error {}
expectThrows {
try a.edit { span in
expectEqual(tracker.instances, layout.capacity)
while !span.isEmpty {
if span.count == layout.count { break }
let old = span.removeLast()
expectEqual(old.payload, -span.count)
}
throw TestError()
}
}
errorHandler: { error in
expectTrue(error is TestError)
}
expectContainerContents(
a,
equivalentTo: (0 ..< layout.count).map { -$0 },
by: { $0.payload == $1 })
expectEqual(tracker.instances, layout.count)
}
}
}
func test_reallocate() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withEvery(
"newCapacity",
in: [
layout.capacity, layout.count, layout.count + 1, layout.capacity + 1
] as Set
) { newCapacity in
withLifetimeTracking { tracker in
var a = tracker.dynamicArray(layout: layout)
expectEqual(a.count, layout.count)
expectEqual(a.capacity, layout.capacity)
a.reallocate(capacity: newCapacity)
expectEqual(a.count, layout.count)
expectEqual(a.capacity, newCapacity)
expectEqual(tracker.instances, layout.count)
expectContainerContents(
a, equivalentTo: 0 ..< layout.count, by: { $0.payload == $1 })
}
}
}
}
func test_reserveCapacity() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withEvery(
"newCapacity",
in: [
0, layout.count - 1, layout.count, layout.count + 1,
layout.capacity, layout.capacity + 1
] as Set
) { newCapacity in
withLifetimeTracking { tracker in
var a = tracker.dynamicArray(layout: layout)
expectEqual(a.count, layout.count)
expectEqual(a.capacity, layout.capacity)
a.reserveCapacity(newCapacity)
expectEqual(a.count, layout.count)
expectEqual(a.capacity, Swift.max(layout.capacity, newCapacity))
expectEqual(tracker.instances, layout.count)
expectContainerContents(
a, equivalentTo: 0 ..< layout.count, by: { $0.payload == $1 })
}
}
}
}
func test_removeAll() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
var a = tracker.dynamicArray(layout: layout)
a.removeAll()
expectTrue(a.isEmpty)
expectEqual(a.capacity, 0)
expectEqual(tracker.instances, 0)
}
}
}
func test_removeAll_keepingCapacity() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
var a = tracker.dynamicArray(layout: layout)
a.removeAll(keepingCapacity: true)
expectTrue(a.isEmpty)
expectEqual(a.capacity, layout.capacity)
expectEqual(tracker.instances, 0)
}
}
}
func test_removeLast() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
var a = tracker.dynamicArray(layout: layout)
withEvery("i", in: 0 ..< layout.count) { i in
let old = a.removeLast()
expectEqual(old.payload, layout.count - 1 - i)
expectEqual(a.count, layout.count - 1 - i)
expectEqual(a.capacity, layout.capacity)
}
expectEqual(tracker.instances, 0)
}
}
}
func test_removeLast_k() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withEvery("k", in: 0 ..< layout.count) { k in
withLifetimeTracking { tracker in
var expected = Array(0 ..< layout.count)
expected.removeLast(k)
var a = tracker.dynamicArray(layout: layout)
expectEqual(tracker.instances, layout.count)
a.removeLast(k)
expectEqual(tracker.instances, layout.count - k)
expectContainerContents(
a, equivalentTo: expected, by: { $0.payload == $1 })
}
}
}
}
func test_remove_at() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withEvery("i", in: 0 ..< layout.count) { i in
withLifetimeTracking { tracker in
var expected = Array(0 ..< layout.count)
expected.remove(at: i)
var a = tracker.dynamicArray(layout: layout)
let old = a.remove(at: i)
expectEqual(old.payload, i)
expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 })
}
}
}
}
func test_removeSubrange() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withEveryRange("range", in: 0 ..< layout.count) { range in
withLifetimeTracking { tracker in
var expected = Array(0 ..< layout.count)
expected.removeSubrange(range)
var a = tracker.dynamicArray(layout: layout)
a.removeSubrange(range)
expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 })
}
}
}
}
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
func test_removeAll_where() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
var expected = Array(0 ..< layout.count)
expected.removeAll(where: { $0.isMultiple(of: 2) })
var a = tracker.dynamicArray(layout: layout)
a.removeAll(where: { $0.payload.isMultiple(of: 2) })
expectContainerContents(
a, equivalentTo: expected, by: { $0.payload == $1 })
}
}
}
#endif
func test_popLast() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
var expected = Array(0 ..< layout.count)
let expectedItem = expected.popLast()
var a = tracker.dynamicArray(layout: layout)
let item = a.popLast()
expectEquivalent(item, expectedItem, by: { $0?.payload == $1 })
expectContainerContents(
a, equivalentTo: expected, by: { $0.payload == $1 })
}
}
}
func test_append_geometric_growth() {
// This test depends on the precise growth curve of DynamicArray,
// which is not part of its stable API. The test may need to be updated
// accordingly.
withLifetimeTracking { tracker in
typealias Value = LifetimeTracked<Int>
var array = DynamicArray<Value>()
expectEqual(array.capacity, 0)
array.append(tracker.instance(for: 0))
expectEqual(array.capacity, 1)
array.append(tracker.instance(for: 1))
expectEqual(array.capacity, 2)
array.append(tracker.instance(for: 2))
expectEqual(array.capacity, 3)
array.append(tracker.instance(for: 3))
expectEqual(array.capacity, 5)
array.append(tracker.instance(for: 4))
expectEqual(array.capacity, 5)
array.append(tracker.instance(for: 5))
expectEqual(array.capacity, 8)
array.append(tracker.instance(for: 6))
expectEqual(array.capacity, 8)
array.append(tracker.instance(for: 7))
expectEqual(array.capacity, 8)
array.append(tracker.instance(for: 8))
expectEqual(array.capacity, 12)
for i in 9 ..< 100 {
array.append(tracker.instance(for: i))
}
expectEqual(tracker.instances, 100)
expectEqual(array.count, 100)
expectEqual(array.capacity, 140)
do {
let additions = RigidArray(capacity: 300) { span in
for i in 0 ..< 300 {
span.append(tracker.instance(for: 100 + i))
}
}
array.append(copying: additions.span)
}
expectEqual(array.capacity, 400)
expectEqual(tracker.instances, 400)
for i in 0 ..< 400 {
expectEqual(array[i].payload, i)
}
_ = consume array
expectEqual(tracker.instances, 0)
}
}
func test_append() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
let c = 2 * layout.capacity + 10
var a = tracker.dynamicArray(layout: layout)
for i in layout.count ..< c {
a.append(tracker.instance(for: i))
expectEqual(a.count, i + 1)
expectContainerContents(a, equivalentTo: 0 ..< i + 1, by: { $0.payload == $1 })
}
expectEqual(tracker.instances, c)
}
}
}
func test_append_copying_MinimalSequence() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withEvery("isContiguous", in: [false, true]) { isContiguous in
withLifetimeTracking { tracker in
let c = 2 * layout.capacity + 10
var a = tracker.dynamicArray(layout: layout)
a.append(copying: MinimalSequence(
elements: (layout.count ..< c).map { tracker.instance(for: $0) },
underestimatedCount: .half,
isContiguous: isContiguous))
expectContainerContents(
a, equivalentTo: 0 ..< c, by: { $0.payload == $1})
expectEqual(tracker.instances, c)
}
}
}
}
func test_append_copying_Span() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withEvery("additions", in: [0, 1, 10, 100]) { additions in
withLifetimeTracking { tracker in
var a = tracker.dynamicArray(layout: layout)
let b = RigidArray(capacity: additions) { span in
for i in 0 ..< additions {
span.append(tracker.instance(for: layout.count + i))
}
}
a.append(copying: b.span)
let c = layout.count + additions
expectContainerContents(
a, equivalentTo: 0 ..< c, by: { $0.payload == $1 })
expectEqual(tracker.instances, c)
}
}
}
}
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
func test_append_copying_Container() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withEvery("additions", in: [0, 1, 10, 100]) { additions in
withEvery("spanCount", in: 1 ... Swift.max(1, layout.capacity - layout.count)) { spanCount in
withLifetimeTracking { tracker in
var a = tracker.dynamicArray(layout: layout)
let c = layout.count + additions
let addition = (layout.count ..< c).map {
tracker.instance(for: $0)
}
let b = StaccatoContainer(
contents: RigidArray(copying: addition),
spanCounts: [spanCount])
a.append(copying: b)
expectContainerContents(
a, equivalentTo: 0 ..< c, by: { $0.payload == $1 })
expectEqual(tracker.instances, c)
}
}
}
}
}
#endif
func test_insert_at() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withEvery("i", in: 0 ... layout.count) { i in
withLifetimeTracking { tracker in
var expected = Array(0 ..< layout.count)
expected.insert(-1, at: i)
var a = tracker.dynamicArray(layout: layout)
a.insert(tracker.instance(for: -1), at: i)
expectContainerContents(
a, equivalentTo: expected, by: { $0.payload == $1 })
expectEqual(tracker.instances, layout.count + 1)
}
}
}
}
func test_insert_copying_Collection() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withEvery("c", in: [0, 1, 10, 100]) { c in
withEvery("i", in: 0 ... layout.count) { i in
withLifetimeTracking { tracker in
let addition = (layout.count ..< layout.count + c)
var expected = Array(0 ..< layout.count)
expected.insert(contentsOf: addition, at: i)
let trackedAddition = addition.map { tracker.instance(for: $0) }
var a = tracker.dynamicArray(layout: layout)
a.insert(copying: trackedAddition, at: i)
expectContainerContents(
a, equivalentTo: expected, by: { $0.payload == $1 })
expectEqual(tracker.instances, layout.count + c)
}
}
}
}
}
func test_insert_copying_Span() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withEvery("i", in: 0 ... layout.count) { i in
withEvery("c", in: [0, 1, 10, 100]) { c in
withLifetimeTracking { tracker in
let addition = Array(layout.count ..< layout.count + c)
var expected = Array(0 ..< layout.count)
expected.insert(contentsOf: addition, at: i)
let rigidAddition = RigidArray(
copying: (0 ..< addition.count).lazy.map { tracker.instance(for: addition[$0]) }
)
var a = tracker.dynamicArray(layout: layout)
a.insert(copying: rigidAddition.span, at: i)
expectContainerContents(
a, equivalentTo: expected, by: { $0.payload == $1 })
expectEqual(tracker.instances, layout.count + c)
}
}
}
}
}
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
func test_insert_copying_Container() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withEvery("i", in: 0 ... layout.count) { i in
withEvery("c", in: [0, 1, 10, 100]) { c in
withEvery("spanCount", in: 1 ... Swift.max(1, layout.capacity - layout.count)) { spanCount in
withLifetimeTracking { tracker in
var expected = Array(0 ..< layout.count)
let addition = Array(layout.count ..< layout.count + c)
expected.insert(contentsOf: addition, at: i)
var a = tracker.dynamicArray(layout: layout)
let rigidAddition = StaccatoContainer(
contents: RigidArray(count: addition.count) {
tracker.instance(for: addition[$0])
},
spanCounts: [spanCount])
a.insert(copying: rigidAddition, at: i)
expectContainerContents(
a, equivalentTo: expected, by: { $0.payload == $1 })
expectEqual(tracker.instances, layout.count + c)
}
}
}
}
}
}
#endif
func test_replaceSubrange_copying_Collection() {
withSomeArrayLayouts("layout", ofCapacities: [0, 5, 10]) { layout in
withEveryRange("range", in: 0 ..< layout.count) { range in
withEvery("c", in: [0, 1, 10, 100]) { c in
withLifetimeTracking { tracker in
var expected = Array(0 ..< layout.count)
let addition = (0 ..< c).map { -100 - $0 }
expected.replaceSubrange(range, with: addition)
var a = tracker.dynamicArray(layout: layout)
let trackedAddition = addition.map { tracker.instance(for: $0) }
a.replaceSubrange(range, copying: trackedAddition)
expectContainerContents(
a, equivalentTo: expected, by: { $0.payload == $1 })
expectEqual(tracker.instances, layout.count - range.count + c)
}
}
}
}
}
func test_replaceSubrange_copying_Span() {
withSomeArrayLayouts("layout", ofCapacities: [0, 5, 10]) { layout in
withEveryRange("range", in: 0 ..< layout.count) { range in
withEvery("c", in: [0, 1, 10, 100]) { c in
withLifetimeTracking { tracker in
var expected = Array(0 ..< layout.count)
let addition = (0 ..< c).map { -100 - $0 }
expected.replaceSubrange(range, with: addition)
var a = tracker.dynamicArray(layout: layout)
let trackedAddition = RigidArray(
copying: addition.map { tracker.instance(for: $0) })
a.replaceSubrange(range, copying: trackedAddition.span)
expectContainerContents(
a, equivalentTo: expected, by: { $0.payload == $1 })
expectEqual(tracker.instances, layout.count - range.count + c)
}
}
}
}
}
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
func test_replaceSubrange_copying_Container() {
withSomeArrayLayouts("layout", ofCapacities: [0, 5, 10]) { layout in
withEveryRange("range", in: 0 ..< layout.count) { range in
withEvery("c", in: [0, 1, 10, 100]) { c in
withEvery("spanCount", in: 1 ... Swift.max(1, layout.capacity - layout.count)) { spanCount in
withLifetimeTracking { tracker in
var expected = Array(0 ..< layout.count)
let addition = (0 ..< c).map { -100 - $0 }
expected.replaceSubrange(range, with: addition)
var a = tracker.dynamicArray(layout: layout)
let trackedAddition = StaccatoContainer(
contents: RigidArray(
copying: addition.map { tracker.instance(for: $0) }),
spanCounts: [spanCount])
a.replaceSubrange(range, copying: trackedAddition)
expectContainerContents(
a, equivalentTo: expected, by: { $0.payload == $1 })
expectEqual(tracker.instances, layout.count - range.count + c)
}
}
}
}
}
}
#endif
}
#endif
+825
View File
@@ -0,0 +1,825 @@
//===----------------------------------------------------------------------===//
//
// 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 XCTest
#if COLLECTIONS_SINGLE_MODULE
import Collections
#else
import _CollectionsTestSupport
import ArrayModule
#endif
#if compiler(>=6.2) && (compiler(>=6.3) || !os(Windows)) // FIXME: [2025-08-17] Windows has no 6.2 snapshot with OutputSpan
#if !COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
/// Check if `left` and `right` contain equal elements in the same order.
@available(SwiftStdlib 5.0, *)
public func expectContainerContents<
Element: Equatable,
C2: Collection<Element>,
>(
_ left: borrowing RigidArray<Element>,
equalTo right: C2,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
line: UInt = #line
) {
expectContainerContents(
left.span,
equalTo: right,
message(), trapping: trapping, file: file, line: line)
}
/// Check if `left` and `right` contain equal elements in the same order.
@available(SwiftStdlib 5.0, *)
public func expectContainerContents<
E1: ~Copyable,
C2: Collection,
>(
_ left: borrowing RigidArray<E1>,
equivalentTo right: C2,
by areEquivalent: (borrowing E1, C2.Element) -> Bool,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
line: UInt = #line
) {
expectContainerContents(
left.span,
equivalentTo: right,
by: areEquivalent,
message(), trapping: trapping, file: file, line: line)
}
#endif
@available(SwiftStdlib 5.0, *)
class RigidArrayTests: CollectionTestCase {
func test_validate_Container() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
let items = tracker.rigidArray(layout: layout)
let expected = (0 ..< layout.count).map { tracker.instance(for: $0) }
expectEqual(tracker.instances, 2 * layout.count)
expectContainerContents(items, equalTo: expected)
#if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
checkContainer(items, expectedContents: expected)
#endif
}
}
}
func test_empty() {
let a = RigidArray<Int>()
expectEqual(a.capacity, 0)
expectEqual(a.count, 0)
expectEqual(a.freeCapacity, 0)
expectTrue(a.isEmpty)
expectTrue(a.isFull)
}
func test_init_capacity() {
do {
let a = RigidArray<Int>(capacity: 0)
expectEqual(a.capacity, 0)
expectEqual(a.count, 0)
expectEqual(a.freeCapacity, 0)
expectTrue(a.isEmpty)
expectTrue(a.isFull)
}
do {
let a = RigidArray<Int>(capacity: 10)
expectEqual(a.capacity, 10)
expectEqual(a.count, 0)
expectEqual(a.freeCapacity, 10)
expectTrue(a.isEmpty)
expectFalse(a.isFull)
}
}
func test_init_generator() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
let a = tracker.rigidArray(layout: layout)
expectEqual(a.capacity, layout.capacity)
expectEqual(a.count, layout.count)
expectEqual(a.freeCapacity, layout.capacity - layout.count)
expectEqual(a.isEmpty, layout.count == 0)
expectEqual(a.isFull, layout.count == layout.capacity)
expectContainerContents(
a,
equivalentTo: 0 ..< layout.count,
by: { $0.payload == $1 })
}
}
}
func test_init_repeating() {
withEvery("c", in: [0, 10, 100]) { c in
withLifetimeTracking { tracker in
let value = tracker.instance(for: 0)
let a = RigidArray(repeating: value, count: c)
expectEqual(a.capacity, c)
expectEqual(a.count, c)
expectEqual(a.freeCapacity, 0)
expectEqual(a.isEmpty, c == 0)
expectTrue(a.isFull)
for i in 0 ..< c {
expectIdentical(a[i], value)
}
}
}
}
func test_init_copying_Collection() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
let a = RigidArray(
capacity: layout.capacity,
copying: (0 ..< layout.count).map { tracker.instance(for: $0) })
expectEqual(tracker.instances, layout.count)
expectEqual(a.capacity, layout.capacity)
expectEqual(a.count, layout.count)
expectEqual(a.freeCapacity, layout.capacity - layout.count)
expectEqual(a.isEmpty, layout.count == 0)
expectEqual(a.isFull, layout.count == layout.capacity)
for i in 0 ..< layout.count {
expectEqual(a[i].payload, i)
}
}
}
}
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
func test_init_copying_Container() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withEvery("spanCounts", in: [
[1],
[3, 5, 7],
[10, 3],
] as [[Int]]) { spanCounts in
withLifetimeTracking { tracker in
let additions = StaccatoContainer(
contents: RigidArray(
copying: (0 ..< layout.count).map { tracker.instance(for: $0) }),
spanCounts: spanCounts)
let array = RigidArray(capacity: layout.capacity, copying: additions)
expectEqual(tracker.instances, layout.count)
expectEqual(array.capacity, layout.capacity)
expectEqual(array.count, layout.count)
for i in 0 ..< layout.count {
expectEqual(array[i].payload, i)
}
}
}
}
}
#endif
func test_span() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
let a = tracker.rigidArray(layout: layout)
let span = a.span
expectEqual(span.count, layout.count)
for i in 0 ..< span.count {
expectEqual(span[i].payload, i)
}
}
}
}
func test_mutableSpan() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
var a = tracker.rigidArray(layout: layout)
var span = a.mutableSpan
expectEqual(span.count, layout.count)
for i in 0 ..< layout.count {
expectEqual(span[i].payload, i)
span[i] = tracker.instance(for: -i)
}
for i in 0 ..< layout.count {
expectEqual(span[i].payload, -i)
}
for i in 0 ..< layout.count {
expectEqual(a[i].payload, -i)
}
}
}
}
func test_nextSpan() {
// RigidArray is expected to have exactly one span.
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
let a = tracker.rigidArray(layout: layout)
let whole = a.span
var i = 0
let first = a.span(after: &i)
expectEqual(i, layout.count)
expectTrue(first.isIdentical(to: whole))
let second = a.span(after: &i)
expectEqual(i, layout.count)
expectTrue(second.isEmpty)
}
}
}
func test_previousSpan() {
// RigidArray is expected to have exactly one span.
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
let a = tracker.rigidArray(layout: layout)
let whole = a.span
var i = layout.count
let first = a.span(before: &i)
expectEqual(i, 0)
expectTrue(first.isIdentical(to: whole))
let second = a.span(before: &i)
expectEqual(i, 0)
expectTrue(second.isEmpty)
}
}
}
func test_nextMutableSpan() {
// RigidArray is expected to have exactly one span.
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
var a = tracker.rigidArray(layout: layout)
var i = 0
var span = a.mutableSpan(after: &i)
expectEqual(i, layout.count)
expectEqual(span.count, layout.count)
span = a.mutableSpan(after: &i)
expectEqual(i, layout.count)
expectTrue(span.isEmpty)
}
}
}
func test_index_properties() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
let a = RigidArray(layout: layout, using: { $0 })
expectEqual(a.startIndex, 0)
expectEqual(a.endIndex, layout.count)
expectEqual(a.indices, 0 ..< layout.count)
}
}
func test_swapAt() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
var a = tracker.rigidArray(layout: layout)
withEvery("i", in: 0 ..< layout.count / 2) { i in
a.swapAt(i, layout.count - 1 - i)
}
let expected = (0 ..< layout.count).reversed()
expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 })
expectEqual(tracker.instances, layout.count)
}
}
}
func test_subscript_borrow() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
let a = tracker.rigidArray(layout: layout)
for i in 0 ..< layout.count {
expectEqual(a[i].payload, i)
}
}
}
}
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
func test_borrowElement() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
let a = tracker.rigidArray(layout: layout)
for i in 0 ..< layout.count {
let item = a.borrowElement(at: i)
expectEqual(item[].payload, i)
}
}
}
}
#endif
func test_mutateElement() {
func modify(tracker: LifetimeTracker, i: Int, item: inout LifetimeTracked<Int>) {
expectEqual(item.payload, i)
item = tracker.instance(for: -i)
}
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
var a = tracker.rigidArray(layout: layout)
for i in 0 ..< layout.count {
modify(tracker: tracker, i: i, item: &a[i])
expectEqual(tracker.instances, layout.count)
}
}
}
}
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
func test_mutateElement() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
var a = tracker.rigidArray(layout: layout)
for i in 0 ..< layout.count {
var item = a.mutateElement(at: i)
expectEqual(item[].payload, i)
item[] = tracker.instance(for: -i)
expectEqual(tracker.instances, layout.count)
}
}
}
}
#endif
func test_edit() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
var a = tracker.rigidArray(layout: layout)
a.edit { span in
expectEqual(span.capacity, layout.capacity)
expectEqual(span.count, layout.count)
if span.count > 0 { // FIXME: rdar://158440246
span.removeAll()
}
expectEqual(tracker.instances, 0)
}
expectEqual(a.count, 0)
a.edit { span in
expectEqual(span.capacity, layout.capacity)
expectEqual(span.count, 0)
for i in 0 ..< span.capacity {
span.append(tracker.instance(for: -i))
}
expectEqual(tracker.instances, layout.capacity)
}
expectEqual(a.count, layout.capacity)
struct TestError: Error {}
expectThrows {
try a.edit { span in
expectEqual(tracker.instances, layout.capacity)
while !span.isEmpty {
if span.count == layout.count { break }
let old = span.removeLast()
expectEqual(old.payload, -span.count)
}
throw TestError()
}
}
errorHandler: { error in
expectTrue(error is TestError)
}
expectContainerContents(
a,
equivalentTo: (0 ..< layout.count).map { -$0 },
by: { $0.payload == $1 })
expectEqual(tracker.instances, layout.count)
}
}
}
func test_reallocate() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withEvery(
"newCapacity",
in: [
layout.capacity, layout.count, layout.count + 1, layout.capacity + 1
] as Set<Int>
) { newCapacity in
withLifetimeTracking { tracker in
var a = tracker.rigidArray(layout: layout)
expectEqual(a.count, layout.count)
expectEqual(a.capacity, layout.capacity)
a.reallocate(capacity: newCapacity)
expectEqual(a.count, layout.count)
expectEqual(a.capacity, newCapacity)
expectEqual(tracker.instances, layout.count)
expectContainerContents(
a, equivalentTo: 0 ..< layout.count, by: { $0.payload == $1 })
}
}
}
}
func test_reserveCapacity() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withEvery(
"newCapacity",
in: [
0, layout.count - 1, layout.count, layout.count + 1,
layout.capacity, layout.capacity + 1
] as Set
) { newCapacity in
withLifetimeTracking { tracker in
var a = tracker.rigidArray(layout: layout)
expectEqual(a.count, layout.count)
expectEqual(a.capacity, layout.capacity)
a.reserveCapacity(newCapacity)
expectEqual(a.count, layout.count)
expectEqual(a.capacity, Swift.max(layout.capacity, newCapacity))
expectEqual(tracker.instances, layout.count)
expectContainerContents(
a, equivalentTo: 0 ..< layout.count, by: { $0.payload == $1 })
}
}
}
}
func test_copy() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
let a = tracker.rigidArray(layout: layout)
let b = a.copy()
expectEqual(b.count, layout.count)
expectEqual(b.capacity, layout.capacity)
expectEqual(tracker.instances, layout.count)
expectContainerContents(a, equivalentTo: 0 ..< layout.count, by: { $0.payload == $1 })
expectContainerContents(b, equivalentTo: 0 ..< layout.count, by: { $0.payload == $1 })
}
}
}
func test_copy_capacity() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withEvery(
"newCapacity",
in: [layout.count, layout.count + 1, layout.capacity, layout.capacity + 1] as Set
) { newCapacity in
withLifetimeTracking { tracker in
let a = tracker.rigidArray(layout: layout)
let b = a.copy(capacity: newCapacity)
expectEqual(b.count, layout.count)
expectEqual(b.capacity, newCapacity)
expectEqual(tracker.instances, layout.count)
expectContainerContents(a, equivalentTo: 0 ..< layout.count, by: { $0.payload == $1 })
expectContainerContents(b, equivalentTo: 0 ..< layout.count, by: { $0.payload == $1 })
}
}
}
}
func test_removeAll() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
var a = tracker.rigidArray(layout: layout)
a.removeAll()
expectTrue(a.isEmpty)
expectEqual(a.capacity, layout.capacity)
expectEqual(tracker.instances, 0)
}
}
}
func test_removeLast() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
var a = tracker.rigidArray(layout: layout)
withEvery("i", in: 0 ..< layout.count) { i in
let old = a.removeLast()
expectEqual(old.payload, layout.count - 1 - i)
expectEqual(a.count, layout.count - 1 - i)
expectEqual(a.capacity, layout.capacity)
}
expectEqual(tracker.instances, 0)
}
}
}
func test_removeLast_k() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withEvery("k", in: 0 ..< layout.count) { k in
withLifetimeTracking { tracker in
var expected = Array(0 ..< layout.count)
expected.removeLast(k)
var a = tracker.rigidArray(layout: layout)
expectEqual(tracker.instances, layout.count)
a.removeLast(k)
expectEqual(tracker.instances, layout.count - k)
expectContainerContents(
a, equivalentTo: expected, by: { $0.payload == $1 })
}
}
}
}
func test_remove_at() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withEvery("i", in: 0 ..< layout.count) { i in
withLifetimeTracking { tracker in
var expected = Array(0 ..< layout.count)
expected.remove(at: i)
var a = tracker.rigidArray(layout: layout)
let old = a.remove(at: i)
expectEqual(old.payload, i)
expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 })
}
}
}
}
func test_removeSubrange() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withEveryRange("range", in: 0 ..< layout.count) { range in
withLifetimeTracking { tracker in
var expected = Array(0 ..< layout.count)
expected.removeSubrange(range)
var a = tracker.rigidArray(layout: layout)
a.removeSubrange(range)
expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 })
}
}
}
}
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
func test_removeAll_where() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
var expected = Array(0 ..< layout.count)
expected.removeAll(where: { $0.isMultiple(of: 2) })
var a = tracker.rigidArray(layout: layout)
a.removeAll(where: { $0.payload.isMultiple(of: 2) })
expectContainerContents(
a, equivalentTo: expected, by: { $0.payload == $1 })
}
}
}
#endif
func test_popLast() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
var expected = Array(0 ..< layout.count)
let expectedItem = expected.popLast()
var a = tracker.rigidArray(layout: layout)
let item = a.popLast()
expectEquivalent(item, expectedItem, by: { $0?.payload == $1 })
expectContainerContents(
a, equivalentTo: expected, by: { $0.payload == $1 })
}
}
}
func test_append() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
var a = tracker.rigidArray(layout: layout)
for i in layout.count ..< layout.capacity {
a.append(tracker.instance(for: i))
expectEqual(a.count, i + 1)
expectContainerContents(a, equivalentTo: 0 ..< i + 1, by: { $0.payload == $1 })
}
expectTrue(a.isFull)
expectEqual(tracker.instances, layout.capacity)
}
}
}
func test_append_copying_MinimalSequence() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withEvery("isContiguous", in: [false, true]) { isContiguous in
withLifetimeTracking { tracker in
var a = tracker.rigidArray(layout: layout)
a.append(copying: MinimalSequence(
elements: (layout.count ..< layout.capacity).map { tracker.instance(for: $0) },
underestimatedCount: .half,
isContiguous: isContiguous))
expectTrue(a.isFull)
expectEqual(tracker.instances, layout.capacity)
}
}
}
}
func test_append_copying_Span() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
var a = tracker.rigidArray(layout: layout)
let b = tracker.rigidArray(
layout: ArrayLayout(
capacity: layout.capacity - layout.count,
count: layout.capacity - layout.count),
using: { layout.count + $0 })
a.append(copying: b.span)
expectTrue(a.isFull)
expectContainerContents(a, equivalentTo: 0 ..< layout.capacity, by: { $0.payload == $1 })
expectEqual(tracker.instances, layout.capacity)
}
}
}
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
func test_append_copying_Container() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withEvery("spanCount", in: 1 ... Swift.max(1, layout.capacity - layout.count)) { spanCount in
withLifetimeTracking { tracker in
var a = tracker.rigidArray(layout: layout)
let addition = (layout.count ..< layout.capacity).map { tracker.instance(for: $0) }
let b = StaccatoContainer(
contents: RigidArray(copying: addition),
spanCounts: [spanCount])
a.append(copying: b)
expectTrue(a.isFull)
expectContainerContents(a, equivalentTo: 0 ..< layout.capacity, by: { $0.payload == $1 })
expectEqual(tracker.instances, layout.capacity)
}
}
}
}
#endif
func test_insert_at() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
guard layout.count < layout.capacity else { return }
withEvery("i", in: 0 ... layout.count) { i in
withLifetimeTracking { tracker in
var expected = Array(0 ..< layout.count)
expected.insert(-1, at: i)
var a = tracker.rigidArray(layout: layout)
a.insert(tracker.instance(for: -1), at: i)
expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 })
expectEqual(tracker.instances, layout.count + 1)
}
}
}
}
func test_insert_copying_Collection() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withEvery("i", in: 0 ... layout.count) { i in
withEvery("isContiguous", in: [false, true]) { isContiguous in
withLifetimeTracking { tracker in
let addition = (layout.count ..< layout.capacity)
var expected = Array(0 ..< layout.count)
expected.insert(contentsOf: addition, at: i)
let trackedAddition = MinimalCollection(
addition.map { tracker.instance(for: $0) },
isContiguous: isContiguous)
var a = tracker.rigidArray(layout: layout)
a.insert(copying: trackedAddition, at: i)
expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 })
expectEqual(tracker.instances, layout.capacity)
}
}
}
}
}
func test_insert_copying_Span() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withEvery("i", in: 0 ... layout.count) { i in
withLifetimeTracking { tracker in
let addition = Array(layout.count ..< layout.capacity)
var expected = Array(0 ..< layout.count)
expected.insert(contentsOf: addition, at: i)
var a = tracker.rigidArray(layout: layout)
let rigidAddition = RigidArray(capacity: addition.count) { span in
for i in 0 ..< addition.count {
span.append(tracker.instance(for: addition[i]))
}
}
a.insert(copying: rigidAddition.span, at: i)
expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 })
expectEqual(tracker.instances, layout.capacity)
}
}
}
}
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
func test_insert_copying_Container() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withEvery("i", in: 0 ... layout.count) { i in
withEvery("spanCount", in: 1 ... Swift.max(1, layout.capacity - layout.count)) { spanCount in
withLifetimeTracking { tracker in
var expected = Array(0 ..< layout.count)
let addition = Array(layout.count ..< layout.capacity)
expected.insert(contentsOf: addition, at: i)
var a = tracker.rigidArray(layout: layout)
let rigidAddition = StaccatoContainer(
contents: RigidArray(count: addition.count) {
tracker.instance(for: addition[$0])
},
spanCounts: [Swift.max(spanCount, 1)])
a.insert(copying: rigidAddition, at: i)
expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 })
expectEqual(tracker.instances, layout.capacity)
}
}
}
}
}
#endif
func test_replaceSubrange_Collection() {
withSomeArrayLayouts("layout", ofCapacities: [0, 5, 10]) { layout in
withEveryRange("range", in: 0 ..< layout.count) { range in
withEvery("isContiguous", in: [false, true]) { isContiguous in
withEvery("c", in: 0 ..< layout.capacity - layout.count + range.count) { c in
withLifetimeTracking { tracker in
var expected = Array(0 ..< layout.count)
let addition = (0 ..< c).map { -100 - $0 }
expected.replaceSubrange(range, with: addition)
let trackedAddition = MinimalCollection(
addition.map { tracker.instance(for: $0) },
isContiguous: isContiguous)
var a = tracker.rigidArray(layout: layout)
a.replaceSubrange(range, copying: trackedAddition)
expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 })
expectEqual(tracker.instances, layout.count - range.count + c)
}
}
}
}
}
}
func test_replaceSubrange_Span() {
withSomeArrayLayouts("layout", ofCapacities: [0, 5, 10]) { layout in
withEveryRange("range", in: 0 ..< layout.count) { range in
withEvery("c", in: 0 ..< layout.capacity - layout.count + range.count) { c in
withLifetimeTracking { tracker in
var expected = Array(0 ..< layout.count)
let addition = (0 ..< c).map { -100 - $0 }
expected.replaceSubrange(range, with: addition)
var a = tracker.rigidArray(layout: layout)
let trackedAddition = RigidArray(copying: addition.map { tracker.instance(for: $0) })
a.replaceSubrange(range, copying: trackedAddition.span)
expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 })
expectEqual(tracker.instances, layout.count - range.count + c)
}
}
}
}
}
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
func test_replaceSubrange_Container() {
withSomeArrayLayouts("layout", ofCapacities: [0, 5, 10]) { layout in
withEveryRange("range", in: 0 ..< layout.count) { range in
withEvery("c", in: 0 ..< layout.capacity - layout.count + range.count) { c in
withEvery("spanCount", in: 1 ... Swift.max(1, layout.capacity - layout.count)) { spanCount in
withLifetimeTracking { tracker in
var expected = Array(0 ..< layout.count)
let addition = (0 ..< c).map { -100 - $0 }
expected.replaceSubrange(range, with: addition)
var a = tracker.rigidArray(layout: layout)
let trackedAddition = StaccatoContainer(
contents: RigidArray(copying: addition.map { tracker.instance(for: $0) }),
spanCounts: [spanCount])
a.replaceSubrange(range, copying: trackedAddition)
expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 })
expectEqual(tracker.instances, layout.count - range.count + c)
}
}
}
}
}
}
#endif
}
#endif
@@ -75,7 +75,7 @@ final class BitSetCountedTests: CollectionTestCase {
func check<S: Sequence>(
_ expected: S,
_ body: (inout BitSet.Counted) -> Void,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) where S.Element == Int {
var a: BitSet.Counted = [1, 2, 3, 4]
@@ -96,7 +96,7 @@ final class BitSetCountedTests: CollectionTestCase {
func check<S: Sequence>(
_ expected: S,
_ body: (inout BitSet.Counted) -> Void,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) where S.Element == Int {
var a: BitSet.Counted = [1, 2, 3, 4]
@@ -117,7 +117,7 @@ final class BitSetCountedTests: CollectionTestCase {
func check<S: Sequence>(
_ expected: S,
_ body: (inout BitSet.Counted) -> Void,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) where S.Element == Int {
var a: BitSet.Counted = [1, 2, 3, 4]
@@ -138,7 +138,7 @@ final class BitSetCountedTests: CollectionTestCase {
func check<S: Sequence>(
_ expected: S,
_ body: (inout BitSet.Counted) -> Void,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) where S.Element == Int {
var a: BitSet.Counted = [1, 2, 3, 4]
+1 -1
View File
@@ -129,7 +129,7 @@ final class BitSetTest: CollectionTestCase {
func withInterestingSets(
_ label: String,
maximum: Int,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line,
run body: (Set<Int>) -> Void
) {
+27
View File
@@ -0,0 +1,27 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2025 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
#if COLLECTIONS_CONTAINERS_PREVIEW
import XCTest
import ContainersPreview
import Synchronization
final class BorrowTests: XCTestCase {
@available(SwiftStdlib 6.2, *)
func test_basic() {
let x: Atomic<Int>? = Atomic(0)
if let y = x.borrow() {
XCTAssertEqual(y[].load(ordering: .relaxed), 0)
}
}
}
#endif
+44
View File
@@ -0,0 +1,44 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import XCTest
#if COLLECTIONS_SINGLE_MODULE
import Collections
#else
import _CollectionsTestSupport
import ContainersPreview
#endif
#if compiler(>=6.2)
final class BoxTests: XCTestCase {
func test_basic() {
var intOnHeap = Box<Int>(0)
XCTAssertEqual(intOnHeap[], 0)
intOnHeap[] = 123
XCTAssertEqual(intOnHeap[], 123)
XCTAssertEqual(intOnHeap.copy(), 123)
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
var inoutToIntOnHeap = intOnHeap.leak()
XCTAssertEqual(inoutToIntOnHeap[], 123)
inoutToIntOnHeap[] = 321
XCTAssertEqual(inoutToIntOnHeap[], 321)
#endif
}
}
#endif
+36
View File
@@ -0,0 +1,36 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import XCTest
#if COLLECTIONS_SINGLE_MODULE
import Collections
#else
import _CollectionsTestSupport
import ContainersPreview
#endif
#if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
final class InoutTests: XCTestCase {
func test_basic() {
var x = 0
var y = Inout(&x)
var v = y[]
XCTAssertEqual(v, 0)
y[] += 10
v = y[]
XCTAssertEqual(v, 10)
XCTAssertEqual(x, 10)
}
}
#endif
+1 -1
View File
@@ -66,7 +66,7 @@ func withEveryDeque<C: Collection>(
_ label: String,
ofCapacities capacities: C,
startValue: Int = 0,
file: StaticString = #file, line: UInt = #line,
file: StaticString = #filePath, line: UInt = #line,
_ body: (DequeLayout) throws -> Void
) rethrows -> Void where C.Element == Int {
// Exhaustive tests for all deque layouts of various capacities
@@ -47,7 +47,7 @@ final class MutableCollectiontests: CollectionTestCase {
_ item: inout LifetimeTracked<Int>,
tracker: LifetimeTracker,
delta: Int,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
expectTrue(isKnownUniquelyReferenced(&item))
@@ -274,7 +274,7 @@ class TreeDictionaryTests: CollectionTestCase {
d, expectedContents: ref, by: ==)
}
@available(macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4, *)
@available(SwiftStdlib 5.6, *)
struct FancyDictionaryKey: CodingKeyRepresentable, Hashable, Codable {
var value: Int
@@ -314,7 +314,7 @@ class TreeDictionaryTests: CollectionTestCase {
])
expectEqual(try MinimalEncoder.encode(d2), v2)
if #available(macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4, *) {
if #available(SwiftStdlib 5.6, *) {
let d3: TreeDictionary<FancyDictionaryKey, Int16> = [
FancyDictionaryKey(1): 10, FancyDictionaryKey(2): 20
]
@@ -601,7 +601,7 @@ class TreeSetTests: CollectionTestCase {
func check(
_ reference: Set<Int>,
_ body: (inout TreeSet<Int>) -> Void,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
var set = x
@@ -123,7 +123,7 @@ func expectEqualSets<Element: Hashable>(
_ ref: [Element],
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
expectEqualSets(
@@ -138,7 +138,7 @@ func expectEqualSets<C: Collection>(
_ ref: Set<C.Element>,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
var ref = ref
@@ -176,7 +176,7 @@ func expectEqualDictionaries<Key: Hashable, Value: Equatable>(
_ ref: [(key: Key, value: Value)],
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
expectEqualDictionaries(
@@ -191,7 +191,7 @@ func expectEqualDictionaries<Key: Hashable, Value: Equatable>(
_ dict: Dictionary<Key, Value>,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
expectEqual(map.count, dict.count, "Mismatching count", file: file, line: line)
@@ -105,7 +105,7 @@ class OrderedDictionaryValueTests: CollectionTestCase {
_ item: inout LifetimeTracked<Int>,
tracker: LifetimeTracker,
delta: Int,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
expectTrue(isKnownUniquelyReferenced(&item))
@@ -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 - 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
@@ -18,13 +18,13 @@ import _CollectionsTestSupport
#endif
class MeasuringHashable: Hashable {
static var equalityChecks = 0
nonisolated(unsafe) static var equalityChecks = 0
static func == (lhs: MeasuringHashable, rhs: MeasuringHashable) -> Bool {
MeasuringHashable.equalityChecks += 1
return lhs._inner == rhs._inner
}
static var hashChecks = 0
nonisolated(unsafe) static var hashChecks = 0
func hash(into hasher: inout Hasher) {
MeasuringHashable.hashChecks += 1
_inner.hash(into: &hasher)
@@ -37,7 +37,7 @@ class MeasuringHashable: Hashable {
}
}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
@available(SwiftStdlib 5.1, *)
class OrderedSetDiffingTests: CollectionTestCase {
func _validatePerformance<T: Hashable>(from a: OrderedSet<T>, to b: OrderedSet<T>) {
@@ -28,7 +28,7 @@ struct OrderedSetLayout: Hashable, CustomStringConvertible {
func withOrderedSetLayouts(
scales: [Int],
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line,
run body: (OrderedSetLayout) throws -> Void
) rethrows {
@@ -913,7 +913,7 @@ class OrderedSetTests: CollectionTestCase {
}
func withSampleRanges(
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line,
_ body: (Range<Int>, Range<Int>) throws -> Void
) rethrows {
+14 -14
View File
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
import XCTest
@preconcurrency import XCTest
#if COLLECTIONS_SINGLE_MODULE
import Collections
#else
@@ -17,7 +17,7 @@ import _CollectionsTestSupport
import _RopeModule
#endif
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
@available(SwiftStdlib 5.8, *)
class TestBigString: CollectionTestCase {
override var isAvailable: Bool { isRunningOnSwiftStdlib5_8 }
@@ -138,7 +138,7 @@ class TestBigString: CollectionTestCase {
func checkCharacterIndices(
_ flat: String,
_ big: BigString,
file: StaticString = #file, line: UInt = #line
file: StaticString = #filePath, line: UInt = #line
) -> (flat: [String.Index], big: [BigString.Index]) {
// Check iterators
var it1 = flat.makeIterator()
@@ -188,7 +188,7 @@ class TestBigString: CollectionTestCase {
func checkScalarIndices(
_ flat: String,
_ big: BigString,
file: StaticString = #file, line: UInt = #line
file: StaticString = #filePath, line: UInt = #line
) -> (flat: [String.Index], big: [BigString.Index]) {
// Check iterators
var it1 = flat.unicodeScalars.makeIterator()
@@ -238,7 +238,7 @@ class TestBigString: CollectionTestCase {
func checkUTF8Indices(
_ flat: String,
_ big: BigString,
file: StaticString = #file, line: UInt = #line
file: StaticString = #filePath, line: UInt = #line
) -> (flat: [String.Index], big: [BigString.Index]) {
// Check iterators
var it1 = flat.utf8.makeIterator()
@@ -288,7 +288,7 @@ class TestBigString: CollectionTestCase {
func checkUTF16Indices(
_ flat: String,
_ big: BigString,
file: StaticString = #file, line: UInt = #line
file: StaticString = #filePath, line: UInt = #line
) -> (flat: [String.Index], big: [BigString.Index]) {
// Check iterators
var it1 = flat.utf16.makeIterator()
@@ -758,7 +758,7 @@ class TestBigString: CollectionTestCase {
func check(
_ indices: some Sequence<BigString.Index>,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
var current = str.startIndex
@@ -789,7 +789,7 @@ class TestBigString: CollectionTestCase {
func check(
_ indices: some Sequence<BigString.Index>,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
var current = str.startIndex
@@ -817,7 +817,7 @@ class TestBigString: CollectionTestCase {
func check(
_ indices: some Sequence<BigString.Index>,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
var current = str.startIndex
@@ -846,7 +846,7 @@ class TestBigString: CollectionTestCase {
func check(
_ indices: some Sequence<BigString.Index>,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
var current = str.startIndex
@@ -872,7 +872,7 @@ class TestBigString: CollectionTestCase {
func check(
_ indices: some Sequence<BigString.Index>,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
var current = str.startIndex
@@ -901,7 +901,7 @@ class TestBigString: CollectionTestCase {
func check(
_ indices: some Sequence<BigString.Index>,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
var current = str.startIndex
@@ -927,7 +927,7 @@ class TestBigString: CollectionTestCase {
func check(
_ indices: some Sequence<BigString.Index>,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
var current = str.startIndex
@@ -964,7 +964,7 @@ class TestBigString: CollectionTestCase {
func check(
_ indices: some Sequence<BigString.Index>,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
var current = str.startIndex
+3 -3
View File
@@ -505,7 +505,7 @@ class TestRope: CollectionTestCase {
func checkEqual(
_ x: Rope<Chunk>,
_ y: [Int],
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
checkEqual(x, chunkify(y), file: file, line: line)
@@ -514,7 +514,7 @@ class TestRope: CollectionTestCase {
func checkEqual(
_ x: Rope<Chunk>,
_ y: [Chunk],
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
let u = Array(x)
@@ -525,7 +525,7 @@ class TestRope: CollectionTestCase {
_ a: Rope<Chunk>,
_ b: [Int],
range: Range<Int>,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
var x = a
@@ -232,7 +232,7 @@ class SortedSetTests: CollectionTestCase {
func withSampleRanges(
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line,
_ body: (Range<Int>, Range<Int>) throws -> Void
) rethrows {
@@ -0,0 +1,217 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 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
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#if COLLECTIONS_SINGLE_MODULE
import Collections
#else
import ContainersPreview
#endif
#if compiler(>=6.2)
/// Check if `left` and `right` contain equal elements in the same order.
@available(SwiftStdlib 5.0, *)
public func expectContainerContents<
Element: Equatable,
C2: Collection<Element>,
>(
_ left: borrowing Span<Element>,
equalTo right: C2,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
line: UInt = #line
) {
var i = 0
var it = right.makeIterator()
while i < left.count {
let a = left[i]
guard let b = it.next() else {
_expectFailure(
"\(left.testDescription) is longer than expected",
message, trapping: trapping, file: file, line: line)
return
}
guard a == b else {
_expectFailure(
"'\(a)' at index \(i) is not equal to '\(b)'",
message, trapping: trapping, file: file, line: line)
return
}
i += 1
}
guard it.next() == nil else {
_expectFailure(
"\(left.testDescription) is shorter than expected",
message, trapping: trapping, file: file, line: line)
return
}
}
/// Check if `left` and `right` contain equal elements in the same order.
@available(SwiftStdlib 5.0, *)
public func expectContainerContents<
E1: ~Copyable,
C2: Collection,
>(
_ left: borrowing Span<E1>,
equivalentTo right: C2,
by areEquivalent: (borrowing E1, C2.Element) -> Bool,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
line: UInt = #line
) {
var i = 0
var it = right.makeIterator()
while i < left.count {
guard let b = it.next() else {
_expectFailure(
"\(left.testDescription) is longer than expected",
message, trapping: trapping, file: file, line: line)
return
}
guard areEquivalent(left[i], b) else {
_expectFailure(
"Element at index \(i) is not equal to '\(b)'",
message, trapping: trapping, file: file, line: line)
return
}
i += 1
}
guard it.next() == nil else {
_expectFailure(
"\(left.testDescription) is shorter than expected",
message, trapping: trapping, file: file, line: line)
return
}
}
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
@available(SwiftStdlib 6.2, *)
public func expectContainersWithEquivalentElements<
C1: Container & ~Copyable & ~Escapable,
C2: Container & ~Copyable & ~Escapable
>(
_ left: borrowing C1,
_ right: borrowing C2,
by areEquivalent: (borrowing C1.Element, borrowing C2.Element) -> Bool,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
line: UInt = #line
) {
if left.elementsEqual(right, by: areEquivalent) { return }
_expectFailure(
"Containers do not have equivalent elements",
message, trapping: trapping, file: file, line: line)
}
/// Check if `left` and `right` contain equal elements in the same order.
@available(SwiftStdlib 6.2, *)
public func expectContainersWithEqualElements<
Element: Equatable,
C1: Container<Element> & ~Copyable & ~Escapable,
C2: Container<Element> & ~Copyable & ~Escapable,
>(
_ left: borrowing C1,
_ right: borrowing C2,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
line: UInt = #line
) {
if left.elementsEqual(right) { return }
_expectFailure(
"Containers do not have equal elements",
message, trapping: trapping, file: file, line: line)
}
/// Check if `left` and `right` contain equal elements in the same order.
@available(SwiftStdlib 6.2, *)
public func expectContainerContents<
Element: Equatable,
C1: Container<Element> & ~Copyable & ~Escapable,
C2: Collection<Element>,
>(
_ left: borrowing C1,
equalTo right: C2,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
line: UInt = #line
) {
var i = left.startIndex
var it = right.makeIterator()
while i < left.endIndex {
let a = left[i]
guard let b = it.next() else {
_expectFailure(
"Container is longer than expected",
message, trapping: trapping, file: file, line: line)
return
}
guard a == b else {
_expectFailure(
"'\(a)' at index \(i) is not equal to '\(b)'",
message, trapping: trapping, file: file, line: line)
return
}
left.formIndex(after: &i)
}
guard it.next() == nil else {
_expectFailure(
"Container is shorter than expected",
message, trapping: trapping, file: file, line: line)
return
}
}
/// Check if `left` and `right` contain equal elements in the same order.
@available(SwiftStdlib 6.2, *)
public func expectContainerContents<
C1: Container & ~Copyable & ~Escapable,
C2: Collection,
>(
_ left: borrowing C1,
equivalentTo right: C2,
by areEquivalent: (borrowing C1.Element, C2.Element) -> Bool,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
line: UInt = #line
) {
var i = left.startIndex
var it = right.makeIterator()
while i < left.endIndex {
guard let b = it.next() else {
_expectFailure(
"Container is longer than expected",
message, trapping: trapping, file: file, line: line)
return
}
guard areEquivalent(left[i], b) else {
_expectFailure(
"Element at index \(i) is not equal to '\(b)'",
message, trapping: trapping, file: file, line: line)
return
}
left.formIndex(after: &i)
}
guard it.next() == nil else {
_expectFailure(
"Container is shorter than expected",
message, trapping: trapping, file: file, line: line)
return
}
}
#endif
#endif
@@ -15,7 +15,7 @@ import XCTest
public func expectFailure(
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
let message = message()
@@ -23,7 +23,7 @@ public func expectFailure(
TestContext.currentTrace(message),
file: file, line: line)
if trapping {
fatalError(message, file: file, line: line)
fatalError(message, file: (file), line: line)
}
}
@@ -51,7 +51,7 @@ public func expectTrue(
_ value: Bool,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
if value { return }
@@ -64,7 +64,7 @@ public func expectFalse(
_ value: Bool,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
if !value { return }
@@ -77,7 +77,7 @@ public func expectNil<T>(
_ value: Optional<T>,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
if value == nil { return }
@@ -90,7 +90,7 @@ public func expectNotNil<T>(
_ value: Optional<T>,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
if value != nil { return }
@@ -103,7 +103,7 @@ public func expectNotNil<T>(
_ value: Optional<T>,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line,
_ handler: (T) throws -> Void = { _ in }
) rethrows {
@@ -120,7 +120,7 @@ public func expectIdentical<T: AnyObject>(
_ left: T?, _ right: T?,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
if left === right { return }
@@ -135,7 +135,7 @@ public func expectNotIdentical<T: AnyObject>(
_ left: T, _ right: T,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
if left !== right { return }
@@ -149,7 +149,7 @@ public func expectEquivalent<A, B>(
by areEquivalent: (A, B) -> Bool,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
if areEquivalent(left, right) { return }
@@ -163,7 +163,7 @@ public func expectEquivalent<A, B>(
by areEquivalent: (A, B) -> Bool,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
if let left = left, let right = right, areEquivalent(left, right) { return }
@@ -179,7 +179,7 @@ public func expectEqual<T: Equatable>(
_ left: T, _ right: T,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
if left == right { return }
@@ -192,7 +192,7 @@ public func expectEqual<Key: Equatable, Value: Equatable>(
_ left: (key: Key, value: Value), _ right: (key: Key, value: Value),
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
if left == right { return }
@@ -206,7 +206,7 @@ public func expectEqual<T: Equatable>(
_ left: T?, _ right: T?,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
if left == right { return }
@@ -221,7 +221,7 @@ public func expectNotEqual<T: Equatable>(
_ left: T, _ right: T,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
if left != right { return }
@@ -234,7 +234,7 @@ public func expectLessThan<T: Comparable>(
_ left: T, _ right: T,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
if left < right { return }
@@ -247,7 +247,7 @@ public func expectLessThanOrEqual<T: Comparable>(
_ left: T, _ right: T,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
if left <= right { return }
@@ -260,7 +260,7 @@ public func expectGreaterThan<T: Comparable>(
_ left: T, _ right: T,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
if left > right { return }
@@ -273,7 +273,7 @@ public func expectGreaterThanOrEqual<T: Comparable>(
_ left: T, _ right: T,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
if left >= right { return }
@@ -289,7 +289,7 @@ public func expectEqualElements<S1: Sequence, S2: Sequence>(
_ right: S2,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) where S1.Element == S2.Element, S1.Element: Equatable {
let left = Array(left)
@@ -306,7 +306,7 @@ public func expectEquivalentElements<S1: Sequence, S2: Sequence>(
by areEquivalent: (S1.Element, S2.Element) -> Bool,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
let left = Array(left)
@@ -327,7 +327,7 @@ public func expectEqualElements<
_ right: S2,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) where S1.Element == (key: A, value: B), S2.Element == (key: A, value: B) {
let left = Array(left)
@@ -346,7 +346,7 @@ public func expectMonotonicallyIncreasing<S: Sequence>(
_ items: S,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) where S.Element: Comparable {
let items = Array(items)
@@ -367,7 +367,7 @@ public func expectStrictlyMonotonicallyIncreasing<S: Sequence>(
_ items: S,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) where S.Element: Comparable {
let items = Array(items)
@@ -384,11 +384,12 @@ public func expectStrictlyMonotonicallyIncreasing<S: Sequence>(
}
}
// FIXME: Remove this in favor of the better one below
public func expectThrows<T>(
_ expression: @autoclosure () throws -> T,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line,
_ errorHandler: (Error) -> Void = { _ in }
) {
@@ -403,6 +404,25 @@ public func expectThrows<T>(
}
}
public func expectThrows<T>(
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #filePath,
line: UInt = #line,
body: () throws -> T,
errorHandler: (Error) -> Void = { _ in }
) {
do {
let result = try body()
expectFailure("Expression did not throw"
+ (T.self == Void.self ? "" : " (returned '\(result)' instead)"),
trapping: trapping,
file: file, line: line)
} catch {
errorHandler(error)
}
}
public func expectType<T>(_ actual: T, _ expectedType: Any.Type) {
expectTrue(type(of: actual) == expectedType)
}
@@ -14,7 +14,7 @@
public func withEvery<Element>(
_ label: String,
by generator: () -> Element?,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line,
run body: (Element) throws -> Void
) rethrows {
@@ -38,7 +38,7 @@ public func withEvery<Element>(
public func withEvery<S: Sequence>(
_ label: String,
in items: S,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line,
run body: (S.Element) throws -> Void
) rethrows {
@@ -60,7 +60,7 @@ public func withEvery<S: Sequence>(
public func withEveryRange<T: Strideable>(
_ label: String,
in bounds: Range<T>,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line,
run body: (Range<T>) throws -> Void
) rethrows where T.Stride == Int {
@@ -104,7 +104,7 @@ public func withSome<C: Collection>(
_ label: String,
in items: C,
maxSamples: Int? = nil,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line,
run body: (C.Element) throws -> Void
) rethrows {
@@ -143,7 +143,7 @@ public func withSomeRanges<T: Strideable>(
_ label: String,
in bounds: Range<T>,
maxSamples: Int? = nil,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line,
run body: (Range<T>) throws -> Void
) rethrows where T.Stride == Int {
@@ -169,7 +169,7 @@ public func withHiddenCopies<S: Sequence, R>(
if enabled: Bool,
of value: inout S,
checker: (S) -> Void = { _ in },
file: StaticString = #file, line: UInt = #line,
file: StaticString = #filePath, line: UInt = #line,
_ body: (inout S) throws -> R
) rethrows -> R where S.Element: Equatable {
guard enabled else { return try body(&value) }
@@ -201,7 +201,7 @@ public func withHiddenCopies<
if enabled: Bool,
of value: inout S,
checker: (S) -> Void = { _ in },
file: StaticString = #file, line: UInt = #line,
file: StaticString = #filePath, line: UInt = #line,
_ body: (inout S) throws -> R
) rethrows -> R where S.Element == (key: Key, value: Value) {
guard enabled else { return try body(&value) }
@@ -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 - 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
@@ -20,7 +20,7 @@ public final class TestContext {
internal var _trace: [Entry] = []
// FIXME: This ought to be a thread-local variable.
internal static var _current: TestContext?
nonisolated(unsafe) internal static var _current: TestContext?
public init() {}
}
@@ -59,7 +59,7 @@ extension TestContext {
public init(
label: String,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
self.label = label
@@ -121,7 +121,7 @@ extension TestContext {
@discardableResult
public func push(
_ label: String,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) -> Entry {
return push(Entry(label: label, file: file, line: line))
@@ -157,7 +157,7 @@ extension TestContext {
/// Assertion failure messages within the closure will include the specified information to aid with debugging.
public func withTrace<R>(
_ label: String,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line,
_ body: () throws -> R
) rethrows -> R {
@@ -208,7 +208,7 @@ extension TestContext {
@inline(never)
public func debuggerBreak(
_ message: String,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
XCTFail(message, file: file, line: line)
@@ -241,7 +241,7 @@ extension TestContext {
///
public func failIfTraceMatches(
_ expectedTrace: String,
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
// Filter for lines that match the regex " *- "
Loaded 100 of 122 files, more files were not shown because too many files have changed in this diff. Show more